code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
for item in self: if item.name.startswith('Logging'): for s in item_status(item): yield s
def logging_subsystem(self)
A collection of logging subsystem statuses :rtype: Status
12.173227
10.151805
1.19912
for item in self: if item.name.startswith('File System'): for s in item_status(item): yield s
def filesystem(self)
A collection of filesystem related statuses :rtype: Status
13.101288
10.368018
1.263625
updated = False location_ref = location_helper(location_name, search_only=True) if location_ref in self: self._cas[:] = [loc for loc in self if loc.location_ref != location_ref] self.update() updated = True return updated
def delete(self, location_name)
Remove a given location by location name. This operation is performed only if the given location is valid, and if so, `update` is called automatically. :param str location: location name or location ref :raises UpdateElementFailed: failed to update element with reason :r...
7.146909
6.287324
1.136717
updated, created = False, False location_ref = location_helper(location) if location_ref in self: for ca in self: if ca.location_ref == location_ref: ca.update( address=contact_address if 'dynamic' not in contact_ad...
def update_or_create(self, location, contact_address, with_status=False, **kw)
Update an existing contact address or create if the location does not exist. :param str location: name of the location, the location will be added if it doesn't exist :param str contact_address: contact address IP. Can be the string 'dynamic' if this should be a ...
3.761973
3.333424
1.128561
interfaces = [] for interface in iter(self): if interface.interface_id == str(interface_id): if interface_ip: if interface.interface_ip == interface_ip: return interface else: interfaces...
def get(self, interface_id, interface_ip=None)
Get will return a list of interface references based on the specified interface id. Multiple references can be returned if a single interface has multiple IP addresses assigned. :return: If interface_ip is provided, a single ContactAddressNode element is returned if found. O...
2.674724
3.04967
0.877054
_, second = self.nicid.split('.') self.update(nicid='{}.{}'.format(str(interface_id), second))
def change_interface_id(self, interface_id)
Generic change interface ID for VLAN interfaces that are not Inline Interfaces (non-VLAN sub interfaces do not have an interface_id field). :param str, int interface_id: interface ID value
16.495918
16.226217
1.016621
first, _ = self.nicid.split('.') self.update(nicid='{}.{}'.format(first, str(vlan_id)))
def change_vlan_id(self, vlan_id)
Change a VLAN id :param str vlan_id: new vlan
10.309465
14.033316
0.734642
nicid = self.nicid if nicid: v = nicid.split('.') if len(v) > 1: return nicid.split('.')[1]
def vlan_id(self)
VLAN ID for this interface, if any :return: VLAN identifier :rtype: str
5.073148
4.701788
1.078983
data = {'inspect_unspecified_vlans': True, 'nicid': '{}-{}'.format(str(interface_id), str(second_interface_id)) if second_interface_id else str(interface_id), 'logical_interface_ref': logical_interface_ref, 'zone_ref': zone_ref} ...
def create(cls, interface_id, logical_interface_ref, second_interface_id=None, zone_ref=None, **kwargs)
:param str interface_id: two interfaces, i.e. '1-2', '4-5', '7-10', etc :param str logical_ref: logical interface reference :param str zone_ref: reference to zone, set on second inline pair :rtype: dict
3.699666
3.994451
0.926201
first, second = self.nicid.split('-') firstintf = first.split('.')[0] secondintf = second.split('.')[0] newvlan = str(vlan_id).split('-') self.update(nicid='{}.{}-{}.{}'.format( firstintf, newvlan[0], secondintf, newvlan[-1]))
def change_vlan_id(self, vlan_id)
Change a VLAN id for an inline interface. :param str vlan_id: New VLAN id. Can be in format '1-2' or a single numerical value. If in '1-2' format, this specifies the vlan ID for the first inline interface and the rightmost for the second. :return: None
4.572437
3.920923
1.166163
try: newleft, newright = newid.split('-') except ValueError: raise EngineCommandFailed('You must provide two parts when changing ' 'the interface ID on an inline interface, i.e. 1-2.') first, second = self.nicid.split('-') if '.' in first ...
def change_interface_id(self, newid)
Change the inline interface ID. The current format is nicid='1-2', where '1' is the top level interface ID (first), and '2' is the second interface in the pair. Consider the existing nicid in case this is a VLAN. :param str newid: string defining new pair, i.e. '3-4' :re...
5.122066
3.937684
1.300781
nicids = self.nicid.split('-') if nicids: u = [] for vlan in nicids: if vlan.split('.')[-1] not in u: u.append(vlan.split('.')[-1]) return '-'.join(u)
def vlan_id(self)
VLAN ID for this interface, if any :return: VLAN identifier :rtype: str
5.022125
5.055084
0.99348
data = {'inspect_unspecified_vlans': True, 'logical_interface_ref': logical_interface_ref, 'nicid': str(interface_id)} if 'reset_interface_nicid' in kw: data.update(reset_interface_nicid=kw.get('reset_interface_nicid')) return cls(da...
def create(cls, interface_id, logical_interface_ref, **kw)
:param int interface_id: the interface id :param str logical_ref: logical interface reference, must be unique from inline intfs :rtype: dict
5.032829
5.33367
0.943596
data = {'address': address, 'network_value': network_value, 'nicid': str(interface_id), 'auth_request': False, 'backup_heartbeat': False, 'nodeid': nodeid, 'outgoing': False, 'primary_mgt': F...
def create(cls, interface_id, address, network_value, nodeid=1, **kwargs)
:param int interface_id: interface id :param str address: ip address of the interface :param str network_value: network/netmask, i.e. x.x.x.x/24 :param int nodeid: for clusters, used to identify the node number :rtype: dict
4.328137
4.643305
0.932124
data = {'address': address, 'auth_request': False, 'auth_request_source': False, 'primary_heartbeat': False, 'backup_heartbeat': False, 'backup_mgt': False, 'dynamic': False, 'network_value':...
def create(cls, interface_id, address=None, network_value=None, nodeid=1, **kw)
:param int interface_id: interface id :param str address: address of this interface :param str network_value: network of this interface in cidr x.x.x.x/24 :param int nodeid: if a cluster, identifies which node this is for :rtype: dict
3.973651
3.98961
0.996
return super(LoopbackClusterInterface, cls).create( address=address, network_value='{}/32'.format(address), interface_id='Loopback Interface', ospfv2_area_ref=ospf_area, **kwargs)
def create(cls, address, ospf_area=None, **kwargs)
Create a loopback interface. Uses parent constructor :rtype: LoopbackClusterInterface
6.196225
5.16284
1.200158
self._engine.data[self.typeof] = \ [loopback for loopback in self._engine.data.get(self.typeof, []) if loopback.get('address') != self.address] self._engine.update()
def delete(self)
Delete a loopback cluster virtual interface from this engine. Changes to the engine configuration are done immediately. You can find cluster virtual loopbacks by iterating at the engine level:: for loopbacks in engine.loopback_interface: ... ...
6.973311
4.896453
1.424156
lb = self.create(address, ospf_area, **kw) if self.typeof in self._engine.data: self._engine.data[self.typeof].append(lb.data) else: self._engine.data[self.typeof] = [lb.data] self._engine.update()
def add_cvi_loopback(self, address, ospf_area=None, **kw)
Add a loopback interface as a cluster virtual loopback. This enables the loopback to 'float' between cluster members. Changes are committed immediately. :param str address: ip address for loopback :param int rank: rank of this entry :param str,Element ospf_area: optional...
4.667828
5.233302
0.891947
lb = self.create(address, rank, nodeid, ospf_area, **kwargs) self._engine.nodes[0].data[self.typeof].append(lb.data) self._engine.update()
def add_single(self, address, rank=1, nodeid=1, ospf_area=None, **kwargs)
Add a single loopback interface to this engine. This is used for single or virtual FW engines. :param str address: ip address for loopback :param int nodeid: nodeid to apply. Default to 1 for single FW :param str, Element ospf_area: ospf area href or element :raises Upda...
7.059888
7.875262
0.896464
nodes = [] for node in self._engine.nodes: node.data[self.typeof] = \ [lb for lb in node.loopback_node_dedicated_interface if lb.get('rank') != self.rank] nodes.append({node.type: node.data}) self._engine.data['nodes'] = ...
def delete(self)
Delete a loopback interface from this engine. Changes to the engine configuration are done immediately. A simple way to obtain an existing loopback is to iterate the loopbacks or to get by address:: lb = engine.loopback_interface.get('127.0.0.10') lb.del...
9.275187
5.855645
1.583974
element, updated, created = super(ActiveDirectoryServer, cls).update_or_create( defer_update=True, **kwargs) if not created: domain_controller = kwargs.pop('domain_controller', []) if domain_controller: current_dc_list = element.domai...
def update_or_create(cls, with_status=False, **kwargs)
Update or create active directory configuration. :param dict kwargs: kwargs to satisfy the `create` constructor arguments if the element doesn't exist or attributes to change :raises CreateElementFailed: failed creating element :return: element instance by type or 3-tuple if...
4.127479
3.59039
1.149591
access_list_entry = [] if entries: for entry in entries: access_list_entry.append( {'{}_entry'.format(cls.typeof): entry}) json = {'name': name, 'entries': access_list_entry, 'comment': comment} jso...
def create(cls, name, entries=None, comment=None, **kw)
Create an Access List Entry. Depending on the access list type you are creating (IPAccessList, IPv6AccessList, IPPrefixList, IPv6PrefixList, CommunityAccessList, ExtendedCommunityAccessList), entries will define a dict of the valid attributes for that ACL type. Each class has a defined ...
4.336634
4.254187
1.01938
self.data.setdefault('entries', []).append( {'{}_entry'.format(self.typeof): kw})
def add_entry(self, **kw)
Add an entry to an AccessList. Use the supported arguments for the inheriting class for keyword arguments. :raises UpdateElementFailed: failure to modify with reason :return: None
10.866925
13.994425
0.776518
field, value = next(iter(field_value.items())) self.data['entries'][:] = [entry for entry in self.data.get('entries') if entry.get('{}_entry'.format(self.typeof)) .get(field) != str(value)]
def remove_entry(self, **field_value)
Remove an AccessList entry by field specified. Use the supported arguments for the inheriting class for keyword arguments. :raises UpdateElementFailed: failed to modify with reason :return: None
5.82402
6.935322
0.839762
created = False modified = False try: element = cls.get(kw.get('name')) except ElementNotFound: element = cls.create(**kw) created = True if not created: if overwrite_existing: element.data['entries...
def update_or_create(cls, with_status=False, overwrite_existing=False, **kw)
Update or create the Access List. This method will not attempt to evaluate whether the access list has differences, instead it will update with the contents of the payload entirely. If the intent is to only add or remove a single entry, use `~add_entry` and `~remove_entry` methods. ...
3.484775
3.102162
1.123338
task = self.make_request( TaskRunFailed, href=self.href) return Task(task)
def update_status(self)
Gets the current status of this task and returns a new task object. :raises TaskRunFailed: fail to update task status
34.048729
12.746973
2.671123
params = kw.pop('params', {}) json = kw.pop('json', None) task = self.make_request( TaskRunFailed, method='create', params=params, json=json, resource=resource) timeout = kw.pop('timeout', 5) wait_for_finish = ...
def execute(self, resource, **kw)
Execute the task and return a TaskOperationPoller. :rtype: TaskOperationPoller
4.017106
3.496442
1.148912
params = kw.pop('params', {}) task = self.make_request( TaskRunFailed, method='create', resource=resource, params=params) return DownloadTask( filename=filename, task=task)
def download(self, resource, filename, **kw)
Start and return a Download Task :rtype: DownloadTask(TaskOperationPoller)
8.179606
7.896564
1.035844
if self._done is None or self._done.is_set(): raise ValueError('Task has already finished') if callable(callback): self.callbacks.append(callback)
def add_done_callback(self, callback)
Add a callback to run after the task completes. The callable must take 1 argument which will be the completed Task. :param callback: a callable that takes a single argument which will be the completed Task.
4.77158
5.046508
0.945521
if self._thread is None: return self._thread.join(timeout=timeout)
def wait(self, timeout=None)
Blocking wait for task status.
4.89429
4.251682
1.151142
if self._thread is not None: self._thread.join(timeout=timeout) return self._task.last_message
def last_message(self, timeout=5)
Wait a specified amount of time and return the last message from the task :rtype: str
5.199074
4.719085
1.101712
if self._thread is not None and self._thread.isAlive(): self._done.set()
def stop(self)
Stop the running task
5.278993
4.690171
1.125544
granted_element = element_resolver(granted_element) json = {'name': name, 'granted_element': granted_element} return ElementCreator(cls, json)
def create(cls, name, granted_element=None)
Create a new ACL :param str name: Name of ACL :param list granted_elements: Elements to grant access to. Can be engines, policies or other acl's. :type granted_elements: list(str,Element) :raises CreateElementFailed: failed creating ACL :return: instance with...
5.749005
9.180884
0.626193
elements = element_resolver(elements) self.data['granted_element'].extend(elements) self.update()
def add_permission(self, elements)
Add permission/s to this ACL. By default this change is committed after the method is called. :param list elements: Elements to grant access to. Can be engines, policies, or other ACLs :type elements: list(str,Element) :raises UpdateElementFailed: Failed updating per...
9.327366
13.526074
0.689584
elements = element_resolver(elements) for element in elements: if element in self.granted_element: self.data['granted_element'].remove(element) self.update()
def remove_permission(self, elements)
Remove permission/s to this ACL. Change is committed at end of method call. :param list elements: list of element/s to remove :type elements: list(str,Element) :raises UpdateElementFailed: Failed modifying permissions :return: None
5.026422
6.683042
0.752116
if not domain: domain = AdminDomain('Shared Domain') return Permission( granted_elements=elements, role_ref=role, granted_domain_ref=domain)
def create(cls, elements, role, domain=None)
Create a permission. :param list granted_elements: Elements for this permission. Can be engines, policies or ACLs :type granted_elements: list(str,Element) :param str,Role role: role for this permission :param str,Element domain: domain to apply (default: Shared Doma...
12.205173
7.611501
1.603517
import os.path path = os.path.abspath(filename) with open(path, "w") as text_file: text_file.write("{}".format(content))
def save_to_file(filename, content)
Save content to file. Used by node initial contact but can be used anywhere. :param str filename: name of file to save to :param str content: content to save :return: None :raises IOError: permissions issue saving, invalid directory, etc
3.056237
3.541775
0.862911
if isinstance(elements, list): e = [] for element in elements: try: e.append(element.href) except AttributeError: e.append(element) except smc.api.exceptions.ElementNotFound: if do_raise: rai...
def element_resolver(elements, do_raise=True)
Element resolver takes either a single class instance or a list of elements to resolve the href. It does not assume a specific interface, instead if it's a class, it just needs an 'href' attribute that should hold the http url for the resource. If a list is provided, a list is returned. If you want ...
2.421038
2.401475
1.008146
for key in dict2: if isinstance(dict2[key], dict): if key in dict1 and key in dict2: merge_dicts(dict1[key], dict2[key], append_lists) else: dict1[key] = dict2[key] # If the value is a list and the ``append_lists`` flag is set, # a...
def merge_dicts(dict1, dict2, append_lists=False)
Merge the second dict into the first Not intended to merge list of dicts. :param append_lists: If true, instead of clobbering a list with the new value, append all of the new values onto the original list.
2.026207
2.039432
0.993515
return s if isinstance(s, str) else s.encode(encoding, errors)
def unicode_to_bytes(s, encoding='utf-8', errors='replace')
Helper to convert unicode strings to bytes for data that needs to be written to on output stream (i.e. terminal) For Python 3 this should be called str_to_bytes :param str s: string to encode :param str encoding: utf-8 by default :param str errors: what to do when encoding fails :return: byte s...
3.287258
6.757245
0.486479
if compat.PY3: source = source.encode('utf-8') return base64.b64encode(source).decode('utf-8')
def b64encode(source)
Base64 encoding for python 2 and 3 :rtype: base64 content
2.427312
2.667452
0.909974
if compat.PY3: return str(s, 'utf-8') if isinstance(s, bytes) else s return s if isinstance(s, unicode) else s.decode(encoding, errors)
def bytes_to_unicode(s, encoding='utf-8', errors='replace')
Helper to convert byte string to unicode string for user based input :param str s: string to decode :param str encoding: utf-8 by default :param str errors: what to do when decoding fails :return: unicode utf-8 string
3.546348
3.314216
1.070041
instance = cls(href=href) meth = getattr(instance, 'create') return type( cls.__name__, (SubElementCollection,), {'create': meth})(href, cls)
def create_collection(href, cls)
This collection type inserts a ``create`` method into the collection. This will proxy to the sub elements create method while restricting access to other attributes that wouldn't be initialized yet. .. py:method:: create(...) Create method is inserted dynamically for the collection class type....
11.166595
8.121378
1.374963
instance = cls(href=href) meth = getattr(instance, 'create') return type( cls.__name__, (SubElementCollection,), { 'create': meth, 'create_rule_section': instance.create_rule_section})(href, cls)
def rule_collection(href, cls)
Rule collections insert a ``create`` and ``create_rule_section`` method into the collection. This collection type is returned when accessing rules through a reference, as:: policy = FirewallPolicy('mypolicy') policy.fw_ipv4_access_rules.create(....) policy.fw_ipv4_access_rules.create_ru...
8.822778
6.356008
1.388101
ignore_metachar = r'(.+)([/-].+)' match = re.search(ignore_metachar, str(val)) if match: left_half = match.group(1) return left_half return val
def _strip_metachars(val)
When a filter uses a / or - in the search, only the elements name and comment field is searched. This can cause issues if searching a network element, i.e. 1.1.1.0/24 where the /24 portion is not present in the name and only the elements ipv4_network attribute. If exact_match is not specified, strip off...
5.379428
4.937364
1.089534
if self and (index <= len(self) -1): return self._result_cache[index]
def get(self, index)
Get the element by index. If index is out of bounds for the internal list, None is returned. Indexes cannot be negative. :param int index: retrieve element by positive index in list :rtype: SubElement or None
9.596958
13.727666
0.699096
for element in self: if not case_sensitive: if value.lower() in element.name.lower(): return element elif value in element.name: return element
def get_contains(self, value, case_sensitive=True)
A partial match on the name field. Does an `in` comparsion to elements by the meta `name` field. Sub elements created by SMC will generally have a descriptive name that helps to identify their purpose. Returns only the first entry matched even if there are multiple. .. s...
2.866057
2.810408
1.019801
elements = [] for element in self: if not case_sensitive: if value.lower() in element.name.lower(): elements.append(element) elif value in element.name: elements.append(element) return elements
def get_all_contains(self, value, case_sensitive=True)
A partial match on the name field. Does an `in` comparsion to elements by the meta `name` field. Returns all elements that match the specified value. .. seealso:: :meth:`get_contains` for returning only a single item. :param str value: searchable string for contains mat...
2.280862
2.311469
0.986759
params = copy.deepcopy(self._params) if self._iexact: params.update(iexact=self._iexact) params.update(**kwargs) clone = self.__class__(**params) return clone
def _clone(self, **kwargs)
Create a clone of this collection. The only param in the initial collection is the filter context. Each chainable filter is added to the clone and returned to preserve previous iterators and their returned elements. :return: :class:`.ElementCollection`
3.904631
4.75483
0.821193
_filter = filter[0] exact_match = kw.pop('exact_match', False) case_sensitive = kw.pop('case_sensitive', True) if kw: _, value = next(iter(kw.items())) _filter = value iexact = kw # Only strip metachars from n...
def filter(self, *filter, **kw): # @ReservedAssignment iexact = None if filter
Filter results for specific element type. keyword arguments can be used to specify a match against the elements attribute directly. It's important to note that if the search filter contains a / or -, the SMC will only search the name and comment fields. Otherwise other key f...
5.922984
5.573577
1.06269
self._params.pop('limit', None) # Limit and batch are mutually exclusive it = iter(self) while True: chunk = list(islice(it, num)) if not chunk: return yield chunk
def batch(self, num)
Iterator returning results in batches. When making more general queries that might have larger results, specify a batch result that should be returned with each iteration. :param int num: number of results per iteration :return: iterator holding list of results
5.24334
5.009531
1.046673
if len(self): self._params.update(limit=1) if 'filter' not in self._params: return list(self)[0] else: # Filter may not return results result = list(self) if result: return result[0]
def first(self)
Returns the first object matched or None if there is no matching object. :: >>> iterator = Host.objects.iterator() >>> c = iterator.filter('kali') >>> if c.exists(): >>> print(c.count()) >>> print(c.first()) 7...
6.503325
6.646708
0.978428
if len(self): self._params.update(limit=1) if 'filter' not in self._params: return list(self)[-1] else: # Filter may not return results result = list(self) if result: return result[-1]
def last(self)
Returns the last object matched or None if there is no matching object. :: >>> iterator = Host.objects.iterator() >>> c = iterator.filter('kali') >>> if c.exists(): >>> print(c.last()) Host(name=kali-foo) :r...
6.385682
6.635545
0.962345
cls_name = '{0}Collection'.format(self._cls.__name__) collection_cls = type(str(cls_name), (ElementCollection,), {}) params = {'filter_context': self._cls.typeof} params.update(kwargs) return collection_cls(**params)
def iterator(self, **kwargs)
Return an iterator from the collection manager. The iterator can be re-used to chain together filters, each chaining event will be it's own unique element collection. :return: :class:`ElementCollection`
6.496195
5.555851
1.169253
if len(entry_point.split(',')) == 1: self._params.update( href=self._resource.get(entry_point)) return self else: self._params.update( filter_context=entry_point) return self
def entry_point(self, entry_point)
Provide an entry point for element types to search. :param str entry_point: valid entry point. Use `~object_types()` to find all available entry points.
5.907273
6.171498
0.957186
if context in CONTEXTS: self._params.update(filter_context=context) return self raise InvalidSearchFilter( 'Context filter %r was invalid. Available filters: %s' % (context, CONTEXTS))
def context_filter(self, context)
Provide a context filter to search. :param str context: Context filter by name
8.305091
8.847726
0.93867
self._params.update( href=self._resource.get('search_unused')) return self
def unused(self)
Return unused user-created elements. :rtype: list(Element)
31.231955
27.848799
1.121483
self._params.update( href=self._resource.get('search_duplicate')) return self
def duplicates(self)
Return duplicate user-created elements. :rtype: list(Element)
31.273108
31.320536
0.998486
# Return all elements from the root of the API nested under elements URI #element_uri = str( types = [element.rel for element in entry_point()] types.extend(list(CONTEXTS)) return types
def object_types()
Show all available 'entry points' available for searching. An entry point defines a uri that provides unfiltered access to all elements of the entry point type. :return: list of entry points by name :rtype: list(str)
38.652687
37.969868
1.017983
clone = self.copy() clone.format.field_format('id') for custom_field in ['field_ids', 'field_names']: clone.format.data.pop(custom_field, None) for list_of_results in clone.fetch_raw(**kw): for entry in list_of_results: yield Connection(*...
def fetch_as_element(self, **kw)
Fetch the results and return as a Connection element. The original query is not modified. :return: generator of elements :rtype: :class:`.Connection`
8.105954
7.230759
1.121038
OSPFKeyChain.create(name='secure-keychain', key_chain_entry=[{'key': 'fookey', 'key_id': 10, 'send_key': True}]) key_chain = OSPFKeyChain('secure-keychain') # obtain resource OSPFInterface...
def create_ospf_area_with_message_digest_auth()
If you require message-digest authentication for your OSPFArea, you must create an OSPF key chain configuration.
6.85543
6.069828
1.129427
OSPFDomainSetting.create(name='custom', abr_type='cisco') ospf_domain = OSPFDomainSetting('custom') # obtain resource ospf_profile = OSPFProfile.create(name='myospfprofile', domain_settings_ref=ospf_domain.href) print(ospf_profil...
def create_ospf_profile()
An OSPF Profile contains administrative distance and redistribution settings. An OSPF Profile is applied at the engine level. When creating an OSPF Profile, you must reference a OSPFDomainSetting. An OSPFDomainSetting holds the settings of the area border router (ABR) type, throttle timer settings, ...
7.257479
6.048991
1.199783
self.data['resolving'].update( timezone=tz, time_show_zone=True)
def timezone(self, tz)
Set timezone on the audit records. Timezone can be in formats: 'US/Eastern', 'PST', 'Europe/Helsinki' See SMC Log Viewer settings for more examples. :param str tz: timezone, i.e. CST
23.067902
31.138926
0.740806
if 'timezone' in kw and 'time_show_zone' not in kw: kw.update(time_show_zone=True) self.data['resolving'].update(**kw)
def set_resolving(self, **kw)
Certain log fields can be individually resolved. Use this method to set these fields. Valid keyword arguments: :param str timezone: string value to set timezone for audits :param bool time_show_zone: show the time zone in the audit. :param bool time_show_millis: show timezone in...
5.678726
4.989479
1.13814
for results in super(LogQuery, self).execute(): if 'records' in results and results['records']: yield results['records']
def fetch_raw(self)
Execute the query and return by batches. Optional keyword arguments are passed to Query.execute(). Whether this is real-time or stored logs is dependent on the value of ``fetch_type``. :return: generator of dict results
9.611034
6.373702
1.50792
clone = self.copy() clone.update_query(type='stored') if not clone.fetch_size or clone.fetch_size <= 0: clone.request['fetch'].update(quantity=200) fmt = formatter(clone) for result in clone.fetch_raw(): yield fmt.formatted(result)
def fetch_batch(self, formatter=TableFormat)
Fetch a batch of logs and return using the specified formatter. Formatter is class type defined in :py:mod:`smc_monitoring.models.formatters`. This fetch type will be a single shot fetch (this method forces ``fetch_type='stored'``). If ``fetch_size`` is not already set on the query, the...
8.527994
6.303613
1.352874
clone = self.copy() clone.update_query(type='current') fmt = formatter(clone) for result in clone.fetch_raw(): yield fmt.formatted(result)
def fetch_live(self, formatter=TableFormat)
View logs in real-time. If previous filters were already set on this query, they will be preserved on the original instance (this method forces ``fetch_type='current'``). :param formatter: Formatter type for data representation. Any type in :py:mod:`smc_monitoring.models.for...
9.289728
6.683435
1.389963
vss_def = {} if vss_def is None else vss_def json = { 'master_type': 'dcl2fw', 'name': name, 'vss_isc': vss_def } return ElementCreator(cls, json)
def create(cls, name, vss_def=None)
Create a VSS Container. This maps to the Service Manager within NSX. vss_def is optional and has the following definition: {"isc_ovf_appliance_model": 'virtual', "isc_ovf_appliance_version": '', "isc_ip_address": '192.168.4.84', # IP of manager, i.e. OSC ...
6.546647
7.840538
0.834974
resource = sub_collection( self.get_relation('vss_container_node'), VSSContainerNode) resource._load_from_engine(self, 'nodes') return resource
def nodes(self)
Return the nodes for this VSS Container :rtype: SubElementCollection(VSSContainerNode)
21.482176
12.247995
1.753934
result = self.make_request( href=fetch_entry_point('visible_virtual_engine_mapping'), params={'filter': self.name}) if result.get('mapping', []): return [Element.from_href(ve) for ve in result['mapping'][0].get('virtual_engine', [])] r...
def vss_contexts(self)
Return all virtual contexts for this VSS Container. :return list VSSContext
13.472934
13.73679
0.980792
for group in self.security_groups: if group.isc_name == name: group.delete()
def remove_security_group(self, name)
Remove a security group from container
6.042354
6.237148
0.968769
return SecurityGroup.create( name=name, isc_id=isc_id, vss_container=self, comment=comment)
def add_security_group(self, name, isc_id, comment=None)
Create a new security group. :param str name: NSX security group name :param str isc_id: NSX Security Group objectId i.e. (securitygroup-14) :raises CreateElementFailed: failed to create :rtype: SecurityGroup
5.16469
6.105907
0.845851
if 'add_context' in self.data.links: # SMC >=6.5 element = ElementCreator( VSSContext, href=self.get_relation('add_context'), json = { 'name': isc_name, 'vc_isc': { 'isc_name': is...
def add_context(self, isc_name, isc_policy_id, isc_traffic_tag)
Create the VSS Context within the VSSContainer :param str isc_name: ISC name, possibly append policy name?? :param str isc_policy_id: Policy ID in SMC (the 'key' attribute) :param str isc_traffic_tag: NSX groupId (serviceprofile-145) :raises CreateElementFailed: failed to create ...
5.007627
4.24907
1.178523
element = ElementCreator(cls, href=vss_container.get_relation('vss_container_node'), json={ 'name': name, 'vss_node_isc': vss_node_def, 'comment': comment }) vss_container._del_cache() # Removes references to li...
def create(cls, name, vss_container, vss_node_def, comment=None)
Create VSS node. This is the engines dvFilter management interface within the NSX agent. .. seealso:: `~.isc_settings` for documentation on the vss_node_def dict :param str name: name of node :param VSSContainer vss_container: container to nest this node :pa...
9.073779
9.471382
0.958021
container = element_resolver(vss_container) return ElementCreator(cls, href=container + '/vss_context', json = { 'vc_isc': { 'isc_name': isc_name, 'isc_policy_id': isc_policy_id, 'isc_traffic_tag...
def create(cls, isc_name, isc_policy_id, isc_traffic_tag, vss_container)
Create the VSS Context within the VSSContainer :param str name: ISC name, possibly append policy name?? :param str isc_policy_id: Policy ID in SMC (the 'key' attribute) :param str isc_traffic_tag: NSX groupId (serviceprofile-145) :param VSSContainer vss_container: VSS Container to get c...
4.730264
4.700922
1.006242
return Task.execute(self, 'remove_from_master_node', timeout=timeout, wait_for_finish=wait_for_finish, **kw)
def remove_from_master_node(self, wait_for_finish=False, timeout=20, **kw)
Remove this VSS Context from it's parent VSS Container. This is required before calling VSSContext.delete(). It preps the engine for removal. :param bool wait_for_finish: wait for the task to finish :param int timeout: how long to wait if delay :type: TaskOperationPoller
3.204582
3.580082
0.895114
return ElementCreator(cls, href=vss_container.get_relation('security_groups'), json = { 'name': name, 'isc_name': name, 'isc_id': isc_id, 'comment': comment or isc_id })
def create(cls, name, isc_id, vss_container, comment=None)
Create a new security group. Find a security group:: SecurityGroup.objects.filter(name) .. note:: The isc_id (securitygroup-10, etc) represents the internal NSX reference for the Security Composer group. This is placed in the comment field w...
6.516164
6.001104
1.085828
json = {'name': name, 'gateway_ref': element_resolver(gateway), 'ref': element_resolver(network), 'input_speed': input_speed, 'output_speed': output_speed, 'probe_address': probe_address, 'nsp_name': provide...
def create(cls, name, gateway, network, input_speed=None, output_speed=None, domain_server_address=None, provider_name=None, probe_address=None, standby_mode_period=3600, standby_mode_timeout=30, active_mode_period=5, active_mode_timeout=1, comment=None)
Create a new StaticNetlink to be used as a traffic handler. :param str name: name of netlink Element :param gateway_ref: gateway to map this netlink to. This can be an element or str href. :type gateway_ref: Router,Engine :param list ref: network/s associated with this netli...
2.597959
2.619265
0.991866
dns_address = kwargs.pop('domain_server_address', []) element, updated, created = super(StaticNetlink, cls).update_or_create( with_status=True, defer_update=True, **kwargs) if not created: if dns_address: new_entries = RankedDNSAddress([]) ...
def update_or_create(cls, with_status=False, **kwargs)
Update or create static netlink. DNS entry differences are not resolved, instead any entries provided will be the final state for this netlink. If the intent is to add/remove DNS entries you can use the :meth:`~domain_server_address` method to add or remove. :raises Crea...
5.709829
4.122064
1.385187
json = {'name': name, 'input_speed': input_speed, 'output_speed': output_speed, 'probe_address': probe_address, 'nsp_name': provider_name, 'comment': comment, 'standby_mode_period': standby_mode_period, ...
def create(cls, name, input_speed=None, learn_dns_automatically=True, output_speed=None, provider_name=None, probe_address=None, standby_mode_period=3600, standby_mode_timeout=30, active_mode_period=5, active_mode_timeout=1, comment=None)
Create a Dynamic Netlink. :param str name: name of netlink Element :param int input_speed: input speed in Kbps, used for ratio-based load-balancing :param int output_speed: output speed in Kbps, used for ratio-based load-balancing :param bool learn_dns_automatic...
1.878022
2.111379
0.889477
json = {'name': name, 'comment': comment, 'retries': retries, 'timeout': timeout, 'multilink_member': multilink_members, 'multilink_method': multilink_method} return ElementCreator(cls, json)
def create(cls, name, multilink_members, multilink_method='rtt', retries=2, timeout=3600, comment=None)
Create a new multilink configuration. Multilink requires at least one netlink for operation, although 2 or more are recommeneded. :param str name: name of multilink :param list multilink_members: the output of calling :func:`.multilink_member` to retrieve the proper formatti...
2.583231
3.139102
0.82292
multilink_members = [] for member in netlinks: m = {'ip_range': member.get('ip_range', '0.0.0.0'), 'netlink_role': member.get('netlink_role', 'active')} netlink = member.get('netlink') m.update(netlink_ref=netlink.href) if netlink...
def create_with_netlinks(cls, name, netlinks, **kwargs)
Create a multilink with a list of StaticNetlinks. To properly create the multilink using this method, pass a list of netlinks with the following dict structure:: netlinks = [{'netlink': StaticNetlink, 'ip_range': 1.1.1.1-1.1.1.2, 'ne...
3.957888
3.056273
1.295005
member_def = dict( netlink_ref=netlink.href, netlink_role=netlink_role, ip_range=ip_range if netlink.typeof == 'netlink' else '0.0.0.0') if netlink.typeof == 'netlink': # static netlink vs dynamic netlink member_def.update(network_ref=netlink.netw...
def create(cls, netlink, ip_range=None, netlink_role='active')
Create a multilink member. Multilink members are added to an Outbound Multilink configuration and define the ip range, static netlink to use, and the role. This element can be passed to the Multilink constructor to simplify creation of the outbound multilink. :param StaticNetlin...
4.53504
4.247404
1.06772
json = { 'name': name, 'tls_version': tls_version, 'use_only_subject_alt_name': use_only_subject_alt_name, 'accept_wildcard': accept_wildcard, 'check_revocation': check_revocation, 'tls_cryptography_suites': element_resolver(tls_cr...
def create(cls, name, tls_version, use_only_subject_alt_name=False, accept_wildcard=False, check_revocation=True, tls_cryptography_suites=None, crl_delay=0, ocsp_delay=0, ignore_network_issues=False, tls_trusted_ca_ref=None, comment=None)
Create a TLS Profile. By default the SMC will have a default NIST TLS Profile but it is also possible to create a custom profile to provide special TLS handling. :param str name: name of TLS Profile :param str tls_verison: supported tls verison, valid options are TLS...
2.098548
1.954054
1.073946
suite = from_suite or TLSCryptographySuite.objects.filter( 'NIST').first() return suite.data.get('tls_cryptography_suites')
def ciphers(from_suite=None)
This is a helper method that will return all of the cipher strings used in a specified TLSCryptographySuite or returns the system default NIST profile list of ciphers. This can be used as a helper to identify the ciphers to specify/add when creating a new TLSCryptographySuite. ...
13.747705
10.751277
1.278704
json = {'name': name, 'certificate': certificate if pem_as_string(certificate) else \ load_cert_chain(certificate)[0][1].decode('utf-8')} return ElementCreator(cls, json)
def create(cls, name, certificate)
Create a TLS CA. The certificate must be compatible with OpenSSL and be in PEM format. The certificate can be either a file with the Root CA, or a raw string starting with BEGIN CERTIFICATE, etc. When creating a TLS CA, you must also import the CA certificate. Once the CA is created, it ...
7.84288
8.500187
0.922671
json = { 'name': name, 'info': common_name, 'public_key_algorithm': public_key_algorithm, 'signature_algorithm': signature_algorithm, 'key_length': key_length, 'certificate_state': 'initial' } return ElementCreator(...
def create_csr(cls, name, common_name, public_key_algorithm='rsa', signature_algorithm='rsa_sha_512', key_length=4096)
Create a certificate signing request. :param str name: name of TLS Server Credential :param str rcommon_name: common name for certificate. An example would be: "CN=CommonName,O=Organization,OU=Unit,C=FR,ST=PACA,L=Nice". At minimum, a "CN" is required. :param str...
3.040817
3.641833
0.834969
tls = TLSServerCredential.create_csr(name=name, common_name=common_name, public_key_algorithm=public_key_algorithm, signature_algorithm=signature_algorithm, key_length=key_length) try: tls.self_sign() except ActionCommandFailed: tls.delete...
def create_self_signed(cls, name, common_name, public_key_algorithm='rsa', signature_algorithm='rsa_sha_512', key_length=4096)
Create a self signed certificate. This is a convenience method that first calls :meth:`~create_csr`, then calls :meth:`~self_sign` on the returned TLSServerCredential object. :param str name: name of TLS Server Credential :param str rcommon_name: common name for certificate. An ...
3.506058
2.510514
1.39655
tls = TLSServerCredential.create(name) try: tls.import_certificate(certificate) tls.import_private_key(private_key) if intermediate is not None: tls.import_intermediate_certificate(intermediate) except CertificateImportError: ...
def import_signed(cls, name, certificate, private_key, intermediate=None)
Import a signed certificate and private key to SMC, and optionally an intermediate certificate. The certificate and the associated private key must be compatible with OpenSSL and be in PEM format. The certificate and private key can be imported as a raw string, file path or file object. ...
3.154896
2.450673
1.287359
contents = load_cert_chain(certificate_file) for pem in list(contents): if b'PRIVATE KEY' in pem[0]: private_key = pem[1] contents.remove(pem) if not private_key: raise ValueError('Private key was not found in chain file a...
def import_from_chain(cls, name, certificate_file, private_key=None)
Import the server certificate, intermediate and optionally private key from a certificate chain file. The expected format of the chain file follows RFC 4346. In short, the server certificate should come first, followed by any intermediate certificates, optionally followed by the ...
3.218788
2.756566
1.16768
ca = ClientProtectionCA.create(name=name) try: ca.import_certificate(certificate) ca.import_private_key(private_key) except CertificateImportError: ca.delete() raise return ca
def import_signed(cls, name, certificate, private_key)
Import a signed certificate and private key as a client protection CA. This is a shortcut method to the 3 step process: * Create CA with name * Import certificate * Import private key Create the CA:: ClientProtectionCA.i...
4.101799
2.855033
1.436691
json = {'key_name': name, 'prefix': prefix, 'password': password, 'life_time': life_time, 'key_size': key_length, 'algorithm': public_key_algorithm} tls = ClientProtectionCA.create(name) try: ...
def create_self_signed(cls, name, prefix, password, public_key_algorithm='rsa', life_time=365, key_length=2048)
Create a self signed client protection CA. To prevent browser warnings during decryption, you must trust the signing certificate in the client browsers. :param str name: Name of this ex: "SG Root CA" Used as Key. Real common name will be derivated at creation time with a uniqueId. ...
5.119841
4.038281
1.267827
self.format = format self.request.update(format=self.format.data)
def update_format(self, format)
Update the format for this query. :param format: new format to use for this query :type format: :py:mod:`smc_monitoring.models.formats`
8.125709
7.081859
1.147398
filt = InFilter(*values) self.update_filter(filt) return filt
def add_in_filter(self, *values)
Add a filter using "IN" logic. This is typically the primary filter that will be used to find a match and generally combines other filters to get more granular. An example of usage would be searching for an IP address (or addresses) in a specific log field. Or looking for an IP address i...
7.149608
10.340254
0.691434
filt = AndFilter(*values) self.update_filter(filt) return filt
def add_and_filter(self, *values)
Add a filter using "AND" logic. This filter is useful when requiring multiple matches to evaluate to true. For example, searching for a specific IP address in the src field and another in the dst field. .. seealso:: :class:`smc_monitoring.models.filters.AndFilter` for examples. ...
8.071148
9.85777
0.81876
filt = OrFilter(*values) self.update_filter(filt) return filt
def add_or_filter(self, *values)
Add a filter using "OR" logic. This filter is useful when matching on one or more criteria. For example, searching for IP 1.1.1.1 and service TCP/443, or IP 1.1.1.10 and TCP/80. Either pair would produce a positive match. .. seealso:: :class:`smc_monitoring.models.filters.OrFilt...
7.838693
10.366938
0.756124
filt = NotFilter(*value) self.update_filter(filt) return filt
def add_not_filter(self, *value)
Add a filter using "NOT" logic. Typically this filter is used in conjunction with and AND or OR filters, but can be used by itself as well. This might be more useful as a standalone filter when displaying logs in real time and filtering out unwanted entry types. .. seealso:: :c...
6.783833
12.146771
0.558489
filt = DefinedFilter(*value) self.update_filter(filt) return filt
def add_defined_filter(self, *value)
Add a DefinedFilter expression to the query. This filter will be considered true if the :class:`smc.monitoring.values.Value` instance has a value. .. seealso:: :class:`smc_monitoring.models.filters.DefinedFilter` for examples. :param Value value: single value for the fi...
7.416402
13.648952
0.543368
request = { 'fetch': {'quantity': 0}, 'format': { 'type': 'detailed', 'field_ids': ids}, 'query': {} } query = Query(**kw) query.location = '/monitoring/log/socket' query.request = request for fi...
def resolve_field_ids(ids, **kw)
Retrieve the log field details based on the LogField constant IDs. This provides a helper to view the fields representation when using different field_formats. Each query class has a default set of field IDs that can easily be looked up to examine their fields and different label option...
7.928553
7.03791
1.126549
self.update_format(DetailedFormat()) for fields in self.execute(): if 'fields' in fields: return fields['fields']
def _get_field_schema(self)
Get a list of all of the default fields for this query type. If data is available in the monitor type, a list of field definitions will be returned ahead of the actual data, providing insight into the available fields. If no data is available in a monitor, this will block on recv(). ...
18.309132
15.563433
1.17642