sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
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. :param bool with_status: return with 3-tuple of (Element, modified, created) holding status :param bool overwrite_existing: if the access list exists but instead of an incremental update you want to overwrite with the newly defined entries, set this to True (default: False) :return: Element or 3-tuple with element and status """ 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'] = [ {'{}_entry'.format(element.typeof): entry} for entry in kw.get('entries')] modified = True else: if 'comment' in kw and kw['comment'] != element.comment: element.comment = kw['comment'] modified = True for entry in kw.get('entries', []): if cls._view(**entry) not in element: element.add_entry(**entry) modified = True if modified: element.update() if with_status: return element, modified, created return element
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. :param bool with_status: return with 3-tuple of (Element, modified, created) holding status :param bool overwrite_existing: if the access list exists but instead of an incremental update you want to overwrite with the newly defined entries, set this to True (default: False) :return: Element or 3-tuple with element and status
entailment
def update_status(self): """ Gets the current status of this task and returns a new task object. :raises TaskRunFailed: fail to update task status """ task = self.make_request( TaskRunFailed, href=self.href) return Task(task)
Gets the current status of this task and returns a new task object. :raises TaskRunFailed: fail to update task status
entailment
def execute(self, resource, **kw): """ Execute the task and return a TaskOperationPoller. :rtype: TaskOperationPoller """ 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 = kw.pop('wait_for_finish', True) return TaskOperationPoller( task=task, timeout=timeout, wait_for_finish=wait_for_finish, **kw)
Execute the task and return a TaskOperationPoller. :rtype: TaskOperationPoller
entailment
def download(self, resource, filename, **kw): """ Start and return a Download Task :rtype: DownloadTask(TaskOperationPoller) """ params = kw.pop('params', {}) task = self.make_request( TaskRunFailed, method='create', resource=resource, params=params) return DownloadTask( filename=filename, task=task)
Start and return a Download Task :rtype: DownloadTask(TaskOperationPoller)
entailment
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. """ if self._done is None or self._done.is_set(): raise ValueError('Task has already finished') if callable(callback): self.callbacks.append(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.
entailment
def wait(self, timeout=None): """ Blocking wait for task status. """ if self._thread is None: return self._thread.join(timeout=timeout)
Blocking wait for task status.
entailment
def last_message(self, timeout=5): """ Wait a specified amount of time and return the last message from the task :rtype: str """ if self._thread is not None: self._thread.join(timeout=timeout) return self._task.last_message
Wait a specified amount of time and return the last message from the task :rtype: str
entailment
def stop(self): """ Stop the running task """ if self._thread is not None and self._thread.isAlive(): self._done.set()
Stop the running task
entailment
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 meta :rtype: AccessControlList """ granted_element = element_resolver(granted_element) json = {'name': name, 'granted_element': granted_element} return ElementCreator(cls, json)
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 meta :rtype: AccessControlList
entailment
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 permissions :return: None """ elements = element_resolver(elements) self.data['granted_element'].extend(elements) self.update()
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 permissions :return: None
entailment
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 """ elements = element_resolver(elements) for element in elements: if element in self.granted_element: self.data['granted_element'].remove(element) self.update()
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
entailment
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 Domain) :rtype: Permission """ if not domain: domain = AdminDomain('Shared Domain') return Permission( granted_elements=elements, role_ref=role, granted_domain_ref=domain)
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 Domain) :rtype: Permission
entailment
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 """ import os.path path = os.path.abspath(filename) with open(path, "w") as text_file: text_file.write("{}".format(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
entailment
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 to suppress raising an exception and just return None or [] instead, set do_raise=False. :raises ElementNotFound: if this is of type Element, ElementLocator will attempt to retrieve meta if it doesn't already exist but the element was not found. """ 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: raise return e try: return elements.href except AttributeError: return elements except smc.api.exceptions.ElementNotFound: if do_raise: raise
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 to suppress raising an exception and just return None or [] instead, set do_raise=False. :raises ElementNotFound: if this is of type Element, ElementLocator will attempt to retrieve meta if it doesn't already exist but the element was not found.
entailment
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. """ 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, # append the new values onto the original list elif isinstance(dict2[key], list) and append_lists: # The value in dict1 must be a list in order to append new # values onto it. Don't add duplicates. if key in dict1 and isinstance(dict1[key], list): dict1[key].extend( [k for k in dict2[key] if k not in dict1[key]]) else: dict1[key] = dict2[key] else: dict1[key] = dict2[key]
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.
entailment
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 string utf-8 encoded """ return s if isinstance(s, str) else s.encode(encoding, errors)
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 string utf-8 encoded
entailment
def b64encode(source): """ Base64 encoding for python 2 and 3 :rtype: base64 content """ if compat.PY3: source = source.encode('utf-8') return base64.b64encode(source).decode('utf-8')
Base64 encoding for python 2 and 3 :rtype: base64 content
entailment
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 """ 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)
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
entailment
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. See the class types documentation, or use help(). :rtype: SubElementCollection """ instance = cls(href=href) meth = getattr(instance, 'create') return type( cls.__name__, (SubElementCollection,), {'create': meth})(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. See the class types documentation, or use help(). :rtype: SubElementCollection
entailment
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_rule_section(...) See the class types documentation, or use help():: print(help(policy.fw_ipv4_access_rules)) :rtype: SubElementCollection """ instance = cls(href=href) meth = getattr(instance, 'create') return type( cls.__name__, (SubElementCollection,), { 'create': meth, 'create_rule_section': instance.create_rule_section})(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_rule_section(...) See the class types documentation, or use help():: print(help(policy.fw_ipv4_access_rules)) :rtype: SubElementCollection
entailment
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 the /24 portion. Queries of this nature should instead use a kw filter of: ipv4_network='1.1.1.0/24'. """ ignore_metachar = r'(.+)([/-].+)' match = re.search(ignore_metachar, str(val)) if match: left_half = match.group(1) return left_half return 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 the /24 portion. Queries of this nature should instead use a kw filter of: ipv4_network='1.1.1.0/24'.
entailment
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 """ if self and (index <= len(self) -1): return self._result_cache[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
entailment
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. .. seealso:: :meth:`~get_all_contains` to return all matches :param str value: searchable string for contains match :param bool case_sensitive: whether the match should consider case (default: True) :rtype: SubElement or None """ for element in self: if not case_sensitive: if value.lower() in element.name.lower(): return element elif value in element.name: return element
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. .. seealso:: :meth:`~get_all_contains` to return all matches :param str value: searchable string for contains match :param bool case_sensitive: whether the match should consider case (default: True) :rtype: SubElement or None
entailment
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 match :param bool case_sensitive: whether the match should consider case (default: True) :return: element or empty list :rtype: list(SubElement) """ 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
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 match :param bool case_sensitive: whether the match should consider case (default: True) :return: element or empty list :rtype: list(SubElement)
entailment
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` """ params = copy.deepcopy(self._params) if self._iexact: params.update(iexact=self._iexact) params.update(**kwargs) clone = self.__class__(**params) return clone
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`
entailment
def filter(self, *filter, **kw): # @ReservedAssignment """ 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 fields of an element are searched. In addition, SMC searches are a 'contains' search meaning you may return more results than wanted. Use a key word argument to specify the elements attribute and value expected. :: >>> list(Router.objects.filter('10.10.10.1')) [Router(name=Router-110.10.10.10), Router(name=Router-10.10.10.10), Router(name=Router-10.10.10.1)] >>> list(Router.objects.filter(address='10.10.10.1')) [Router(name=Router-10.10.10.1)] :param str filter: any parameter to attempt to match on. For example, if this is a service, you could match on service name 'http' or ports of interest, '80'. :param bool exact_match: Can be passed as a keyword arg. Specifies whether the match needs to be exact or not (default: False) :param bool case_sensitive: Can be passed as a keyword arg. Specifies whether the match is case sensitive or not. (default: True) :param kw: keyword args can specify an attribute=value to use as an exact match against the elements attribute. :return: :class:`.ElementCollection` """ iexact = None if filter: _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 network and address range if not exact_match and self._params.get('filter_context', {})\ in ('network', 'address_range', 'network_elements'): _filter = _strip_metachars(_filter) return self._clone( filter=_filter, iexact=iexact, exact_match=exact_match, case_sensitive=case_sensitive)
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 fields of an element are searched. In addition, SMC searches are a 'contains' search meaning you may return more results than wanted. Use a key word argument to specify the elements attribute and value expected. :: >>> list(Router.objects.filter('10.10.10.1')) [Router(name=Router-110.10.10.10), Router(name=Router-10.10.10.10), Router(name=Router-10.10.10.1)] >>> list(Router.objects.filter(address='10.10.10.1')) [Router(name=Router-10.10.10.1)] :param str filter: any parameter to attempt to match on. For example, if this is a service, you could match on service name 'http' or ports of interest, '80'. :param bool exact_match: Can be passed as a keyword arg. Specifies whether the match needs to be exact or not (default: False) :param bool case_sensitive: Can be passed as a keyword arg. Specifies whether the match is case sensitive or not. (default: True) :param kw: keyword args can specify an attribute=value to use as an exact match against the elements attribute. :return: :class:`.ElementCollection`
entailment
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 """ 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
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
entailment
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 Host(name=kali67) If results are not needed and you only 1 result, this can be called from the CollectionManager:: >>> Host.objects.first() Host(name=SMC) :return: element or None """ 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]
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 Host(name=kali67) If results are not needed and you only 1 result, this can be called from the CollectionManager:: >>> Host.objects.first() Host(name=SMC) :return: element or None
entailment
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) :return: element or None """ 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]
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) :return: element or None
entailment
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` """ 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)
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`
entailment
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. """ 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
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.
entailment
def context_filter(self, context): """ Provide a context filter to search. :param str context: Context filter by name """ if context in CONTEXTS: self._params.update(filter_context=context) return self raise InvalidSearchFilter( 'Context filter %r was invalid. Available filters: %s' % (context, CONTEXTS))
Provide a context filter to search. :param str context: Context filter by name
entailment
def unused(self): """ Return unused user-created elements. :rtype: list(Element) """ self._params.update( href=self._resource.get('search_unused')) return self
Return unused user-created elements. :rtype: list(Element)
entailment
def duplicates(self): """ Return duplicate user-created elements. :rtype: list(Element) """ self._params.update( href=self._resource.get('search_duplicate')) return self
Return duplicate user-created elements. :rtype: list(Element)
entailment
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) """ # 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
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)
entailment
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` """ 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(**entry)
Fetch the results and return as a Connection element. The original query is not modified. :return: generator of elements :rtype: :class:`.Connection`
entailment
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. """ OSPFKeyChain.create(name='secure-keychain', key_chain_entry=[{'key': 'fookey', 'key_id': 10, 'send_key': True}]) """ An OSPF interface is applied to a physical interface at the engines routing node level. This configuration is done by an OSPFInterfaceSetting element. To apply the key-chain to this configuration, add the authentication_type of message-digest and reference to the key-chain """ key_chain = OSPFKeyChain('secure-keychain') # obtain resource OSPFInterfaceSetting.create(name='authenicated-ospf', authentication_type='message_digest', key_chain_ref=key_chain.href) """ Create the OSPFArea and assign the above created OSPFInterfaceSetting. In this example, use the default system OSPFInterfaceSetting called 'Default OSPFv2 Interface Settings' """ for profile in describe_ospfv2_interface_settings(): if profile.name.startswith('Default OSPF'): # Use the system default interface_profile = profile.href OSPFArea.create(name='area0', interface_settings_ref=interface_profile, area_id=0)
If you require message-digest authentication for your OSPFArea, you must create an OSPF key chain configuration.
entailment
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, and the max metric router link-state advertisement (LSA) settings. """ 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_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, and the max metric router link-state advertisement (LSA) settings.
entailment
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 """ self.data['resolving'].update( timezone=tz, time_show_zone=True)
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
entailment
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 milliseconds :param bool keys: resolve log field keys :param bool ip_elements: resolve IP's to SMC elements :param bool ip_dns: resolve IP addresses using DNS :param bool ip_locations: resolve locations """ if 'timezone' in kw and 'time_show_zone' not in kw: kw.update(time_show_zone=True) self.data['resolving'].update(**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 milliseconds :param bool keys: resolve log field keys :param bool ip_elements: resolve IP's to SMC elements :param bool ip_dns: resolve IP addresses using DNS :param bool ip_locations: resolve locations
entailment
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 """ for results in super(LogQuery, self).execute(): if 'records' in results and results['records']: yield results['records']
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
entailment
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 default fetch_size will be 200. :param formatter: Formatter type for data representation. Any type in :py:mod:`smc_monitoring.models.formatters`. :return: generator returning data in specified format """ 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)
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 default fetch_size will be 200. :param formatter: Formatter type for data representation. Any type in :py:mod:`smc_monitoring.models.formatters`. :return: generator returning data in specified format
entailment
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.formatters`. :return: generator of formatted results """ clone = self.copy() clone.update_query(type='current') fmt = formatter(clone) for result in clone.fetch_raw(): yield fmt.formatted(result)
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.formatters`. :return: generator of formatted results
entailment
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 "isc_vss_id": '', "isc_virtual_connector_name": 'smc-python'} :param str name: name of container :param dict vss_def: dict of optional settings :raises CreateElementFailed: failed creating with reason :rtype: VSSContainer """ vss_def = {} if vss_def is None else vss_def json = { 'master_type': 'dcl2fw', 'name': name, 'vss_isc': vss_def } return ElementCreator(cls, json)
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 "isc_vss_id": '', "isc_virtual_connector_name": 'smc-python'} :param str name: name of container :param dict vss_def: dict of optional settings :raises CreateElementFailed: failed creating with reason :rtype: VSSContainer
entailment
def nodes(self): """ Return the nodes for this VSS Container :rtype: SubElementCollection(VSSContainerNode) """ resource = sub_collection( self.get_relation('vss_container_node'), VSSContainerNode) resource._load_from_engine(self, 'nodes') return resource
Return the nodes for this VSS Container :rtype: SubElementCollection(VSSContainerNode)
entailment
def vss_contexts(self): """ Return all virtual contexts for this VSS Container. :return list VSSContext """ 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', [])] return []
Return all virtual contexts for this VSS Container. :return list VSSContext
entailment
def remove_security_group(self, name): """ Remove a security group from container """ for group in self.security_groups: if group.isc_name == name: group.delete()
Remove a security group from container
entailment
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 """ return SecurityGroup.create( name=name, isc_id=isc_id, vss_container=self, comment=comment)
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
entailment
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 :return: VSSContext """ 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': isc_name, 'isc_policy_id': isc_policy_id, 'isc_traffic_tag': isc_traffic_tag } }) else: # SMC < 6.5 element = VSSContext.create( isc_name=isc_name, isc_policy_id=isc_policy_id, isc_traffic_tag=isc_traffic_tag, vss_container=self) # Delete cache since the virtualResources node is attached to # the engine json self._del_cache() return element
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 :return: VSSContext
entailment
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 :param dict vss_node_def: node definition settings :raises CreateElementFailed: created failed with reason :rtype: VSSContainerNode """ 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 linked container return element
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 :param dict vss_node_def: node definition settings :raises CreateElementFailed: created failed with reason :rtype: VSSContainerNode
entailment
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 create context :raises CreateElementFailed :rtype: VSSContext """ 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': isc_traffic_tag } })
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 create context :raises CreateElementFailed :rtype: VSSContext
entailment
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 """ return Task.execute(self, 'remove_from_master_node', timeout=timeout, wait_for_finish=wait_for_finish, **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
entailment
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 which makes it a searchable field using search collections :param str name: name of group :param str isc_id: NSX Security Group objectId :param str isc_name: NSX Security Group name :param VSSContainer vss_container: VSS Container to add the security group to. :param str comment: comment, making this searchable :raises: CreateElementFailed :return SecurityGroup """ 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 })
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 which makes it a searchable field using search collections :param str name: name of group :param str isc_id: NSX Security Group objectId :param str isc_name: NSX Security Group name :param VSSContainer vss_container: VSS Container to add the security group to. :param str comment: comment, making this searchable :raises: CreateElementFailed :return SecurityGroup
entailment
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 netlink. :type ref: list(str,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 list domain_server_address: dns addresses for netlink. Engine DNS can override this field :type dns_addresses: list(str,Element) :param str provider_name: optional name to identify provider for this netlink :param list probe_address: list of IP addresses to use as probing addresses to validate connectivity :type probe_ip_address: list(str) :param int standby_mode_period: Specifies the probe period when standby mode is used (in seconds) :param int standby_mode_timeout: probe timeout in seconds :param int active_mode_period: Specifies the probe period when active mode is used (in seconds) :param int active_mode_timeout: probe timeout in seconds :raises ElementNotFound: if using type Element parameters that are not found. :raises CreateElementFailed: failure to create netlink with reason :rtype: StaticNetlink .. note:: To monitor the status of the network links, you must define at least one probe IP address. """ 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': provider_name, 'comment': comment, 'standby_mode_period': standby_mode_period, 'standby_mode_timeout': standby_mode_timeout, 'active_mode_period': active_mode_period, 'active_mode_timeout': active_mode_timeout} if domain_server_address: r = RankedDNSAddress([]) r.add(domain_server_address) json.update(domain_server_address=r.entries) return ElementCreator(cls, json)
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 netlink. :type ref: list(str,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 list domain_server_address: dns addresses for netlink. Engine DNS can override this field :type dns_addresses: list(str,Element) :param str provider_name: optional name to identify provider for this netlink :param list probe_address: list of IP addresses to use as probing addresses to validate connectivity :type probe_ip_address: list(str) :param int standby_mode_period: Specifies the probe period when standby mode is used (in seconds) :param int standby_mode_timeout: probe timeout in seconds :param int active_mode_period: Specifies the probe period when active mode is used (in seconds) :param int active_mode_timeout: probe timeout in seconds :raises ElementNotFound: if using type Element parameters that are not found. :raises CreateElementFailed: failure to create netlink with reason :rtype: StaticNetlink .. note:: To monitor the status of the network links, you must define at least one probe IP address.
entailment
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 CreateElementFailed: failed creating element :return: element instance by type or 3-tuple if with_status set """ 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([]) new_entries.add(dns_address) element.data.update(domain_server_address=new_entries.entries) updated = True if updated: element.update() if with_status: return element, updated, created return element
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 CreateElementFailed: failed creating element :return: element instance by type or 3-tuple if with_status set
entailment
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_automatically: whether to obtain DNS automatically from the DHCP interface :param str provider_name: optional name to identify provider for this netlink :param list probe_address: list of IP addresses to use as probing addresses to validate connectivity :type probe_ip_address: list(str) :param int standby_mode_period: Specifies the probe period when standby mode is used (in seconds) :param int standby_mode_timeout: probe timeout in seconds :param int active_mode_period: Specifies the probe period when active mode is used (in seconds) :param int active_mode_timeout: probe timeout in seconds :raises CreateElementFailed: failure to create netlink with reason :rtype: DynamicNetlink .. note:: To monitor the status of the network links, you must define at least one probe IP address. """ 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, 'standby_mode_timeout': standby_mode_timeout, 'active_mode_period': active_mode_period, 'active_mode_timeout': active_mode_timeout, 'learn_dns_server_automatically': learn_dns_automatically} return ElementCreator(cls, json)
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_automatically: whether to obtain DNS automatically from the DHCP interface :param str provider_name: optional name to identify provider for this netlink :param list probe_address: list of IP addresses to use as probing addresses to validate connectivity :type probe_ip_address: list(str) :param int standby_mode_period: Specifies the probe period when standby mode is used (in seconds) :param int standby_mode_timeout: probe timeout in seconds :param int active_mode_period: Specifies the probe period when active mode is used (in seconds) :param int active_mode_timeout: probe timeout in seconds :raises CreateElementFailed: failure to create netlink with reason :rtype: DynamicNetlink .. note:: To monitor the status of the network links, you must define at least one probe IP address.
entailment
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 formatting for this sub element. :param str multilink_method: 'rtt' or 'ratio'. If ratio is used, each netlink must have a probe IP address configured and also have input and output speed configured (default: 'rtt') :param int retries: number of keep alive retries before a destination link is considered unavailable (default: 2) :param int timeout: timeout between retries (default: 3600 seconds) :param str comment: comment for multilink (optional) :raises CreateElementFailed: failure to create multilink :rtype: Multilink """ json = {'name': name, 'comment': comment, 'retries': retries, 'timeout': timeout, 'multilink_member': multilink_members, 'multilink_method': multilink_method} return ElementCreator(cls, json)
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 formatting for this sub element. :param str multilink_method: 'rtt' or 'ratio'. If ratio is used, each netlink must have a probe IP address configured and also have input and output speed configured (default: 'rtt') :param int retries: number of keep alive retries before a destination link is considered unavailable (default: 2) :param int timeout: timeout between retries (default: 3600 seconds) :param str comment: comment for multilink (optional) :raises CreateElementFailed: failure to create multilink :rtype: Multilink
entailment
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, 'netlink_role': 'active'}] The `netlink_role` can be either `active` or `standby`. The remaining settings are resolved from the StaticNetlink. The IP range value must be an IP range within the StaticNetlink's specified network. Use kwargs to pass any additional arguments that are supported by the `create` constructor. A full example of creating a multilink using predefined netlinks:: multilink = Multilink.create_with_netlinks( name='mynewnetlink', netlinks=[{'netlink': StaticNetlink('netlink1'), 'ip_range': '1.1.1.2-1.1.1.3', 'netlink_role': 'active'}, {'netlink': StaticNetlink('netlink2'), 'ip_range': '2.1.1.2-2.1.1.3', 'netlink_role': 'standby'}]) :param StaticNetlink,DynamicNetlink netlink: StaticNetlink element :param str ip_range: ip range for source NAT on this netlink :param str netlink_role: the role for this netlink, `active` or `standby` :raises CreateElementFailed: failure to create multilink :rtype: Multilink """ 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.typeof == 'netlink': m.update(network_ref=netlink.data.get('ref')[0]) multilink_members.append(m) return cls.create(name, multilink_members, **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, 'netlink_role': 'active'}] The `netlink_role` can be either `active` or `standby`. The remaining settings are resolved from the StaticNetlink. The IP range value must be an IP range within the StaticNetlink's specified network. Use kwargs to pass any additional arguments that are supported by the `create` constructor. A full example of creating a multilink using predefined netlinks:: multilink = Multilink.create_with_netlinks( name='mynewnetlink', netlinks=[{'netlink': StaticNetlink('netlink1'), 'ip_range': '1.1.1.2-1.1.1.3', 'netlink_role': 'active'}, {'netlink': StaticNetlink('netlink2'), 'ip_range': '2.1.1.2-2.1.1.3', 'netlink_role': 'standby'}]) :param StaticNetlink,DynamicNetlink netlink: StaticNetlink element :param str ip_range: ip range for source NAT on this netlink :param str netlink_role: the role for this netlink, `active` or `standby` :raises CreateElementFailed: failure to create multilink :rtype: Multilink
entailment
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 StaticNetlink,DynamicNetlink netlink: static netlink element to use as member :param str ip_range: the IP range for source NAT for this member. The IP range should be part of the defined network range used by this netlink. Not required for dynamic netlink :param str netlink_role: role of this netlink, 'active' or 'standby' :raises ElementNotFound: Specified netlink could not be found :rtype: MultilinkMember """ 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.network[0].href) return cls(member_def)
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 StaticNetlink,DynamicNetlink netlink: static netlink element to use as member :param str ip_range: the IP range for source NAT for this member. The IP range should be part of the defined network range used by this netlink. Not required for dynamic netlink :param str netlink_role: role of this netlink, 'active' or 'standby' :raises ElementNotFound: Specified netlink could not be found :rtype: MultilinkMember
entailment
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 TLSv1.1, TLSv1.2, TLSv1.3 :param bool use_only_subject_alt_name: Use Only Subject Alt Name when the TLS identity is a DNS name :param bool accept_wildcard: Does server identity check accept wildcards :param bool check_revocation: Is certificate revocation checked :param str,TLSCryptographySuite tls_cryptography_suites: allowed cryptography suites for this profile. Uses NIST profile if not specified :param int crl_delay: Delay time (hours) for fetching CRL :param int ocsp_delay: Ignore OCSP failure for (hours) :param bool ignore_network_issues: Ignore revocation check failures due to network issues :param list tls_trusted_ca_ref: Trusted Certificate Authorities, empty list means trust any :param str comment: optional comment :raises CreateElementFailed: failed to create element with reason :raises ElementNotFound: specified element reference was not found :rtype: TLSProfile """ 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_cryptography_suites) or \ element_resolver(TLSCryptographySuite.objects.filter('NIST').first()), 'crl_delay': crl_delay, 'ocsp_delay': ocsp_delay, 'ignore_network_issues': ignore_network_issues, 'tls_trusted_ca_ref': element_resolver(tls_trusted_ca_ref) or [], 'comment': comment} return ElementCreator(cls, json)
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 TLSv1.1, TLSv1.2, TLSv1.3 :param bool use_only_subject_alt_name: Use Only Subject Alt Name when the TLS identity is a DNS name :param bool accept_wildcard: Does server identity check accept wildcards :param bool check_revocation: Is certificate revocation checked :param str,TLSCryptographySuite tls_cryptography_suites: allowed cryptography suites for this profile. Uses NIST profile if not specified :param int crl_delay: Delay time (hours) for fetching CRL :param int ocsp_delay: Ignore OCSP failure for (hours) :param bool ignore_network_issues: Ignore revocation check failures due to network issues :param list tls_trusted_ca_ref: Trusted Certificate Authorities, empty list means trust any :param str comment: optional comment :raises CreateElementFailed: failed to create element with reason :raises ElementNotFound: specified element reference was not found :rtype: TLSProfile
entailment
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. :rtype: dict """ suite = from_suite or TLSCryptographySuite.objects.filter( 'NIST').first() return suite.data.get('tls_cryptography_suites')
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. :rtype: dict
entailment
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 is possible to import a different certificate to map to the CA if necessary. :param str name: name of root CA :param str,file certificate: The root CA contents :raises CreateElementFailed: failed to create the root CA :raises ValueError: if loading from file and no certificates present :raises IOError: cannot find specified file for certificate :rtype: TLSCertificateAuthority """ json = {'name': name, 'certificate': certificate if pem_as_string(certificate) else \ load_cert_chain(certificate)[0][1].decode('utf-8')} return ElementCreator(cls, json)
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 is possible to import a different certificate to map to the CA if necessary. :param str name: name of root CA :param str,file certificate: The root CA contents :raises CreateElementFailed: failed to create the root CA :raises ValueError: if loading from file and no certificates present :raises IOError: cannot find specified file for certificate :rtype: TLSCertificateAuthority
entailment
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 public_key_algorithm: public key type to use. Valid values rsa, dsa, ecdsa. :param str signature_algorithm: signature algorithm. Valid values dsa_sha_1, dsa_sha_224, dsa_sha_256, rsa_md5, rsa_sha_1, rsa_sha_256, rsa_sha_384, rsa_sha_512, ecdsa_sha_1, ecdsa_sha_256, ecdsa_sha_384, ecdsa_sha_512. (Default: rsa_sha_512) :param int key_length: length of key. Key length depends on the key type. For example, RSA keys can be 1024, 2048, 3072, 4096. See SMC documentation for more details. :raises CreateElementFailed: failed to create CSR :rtype: TLSServerCredential """ 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(cls, json)
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 public_key_algorithm: public key type to use. Valid values rsa, dsa, ecdsa. :param str signature_algorithm: signature algorithm. Valid values dsa_sha_1, dsa_sha_224, dsa_sha_256, rsa_md5, rsa_sha_1, rsa_sha_256, rsa_sha_384, rsa_sha_512, ecdsa_sha_1, ecdsa_sha_256, ecdsa_sha_384, ecdsa_sha_512. (Default: rsa_sha_512) :param int key_length: length of key. Key length depends on the key type. For example, RSA keys can be 1024, 2048, 3072, 4096. See SMC documentation for more details. :raises CreateElementFailed: failed to create CSR :rtype: TLSServerCredential
entailment
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 example would be: "CN=CommonName,O=Organization,OU=Unit,C=FR,ST=PACA,L=Nice". At minimum, a "CN" is required. :param str public_key_algorithm: public key type to use. Valid values rsa, dsa, ecdsa. :param str signature_algorithm: signature algorithm. Valid values dsa_sha_1, dsa_sha_224, dsa_sha_256, rsa_md5, rsa_sha_1, rsa_sha_256, rsa_sha_384, rsa_sha_512, ecdsa_sha_1, ecdsa_sha_256, ecdsa_sha_384, ecdsa_sha_512. (Default: rsa_sha_512) :param int key_length: length of key. Key length depends on the key type. For example, RSA keys can be 1024, 2048, 3072, 4096. See SMC documentation for more details. :raises CreateElementFailed: failed to create CSR :raises ActionCommandFailed: Failure to self sign the certificate :rtype: TLSServerCredential """ 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() raise return tls
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 example would be: "CN=CommonName,O=Organization,OU=Unit,C=FR,ST=PACA,L=Nice". At minimum, a "CN" is required. :param str public_key_algorithm: public key type to use. Valid values rsa, dsa, ecdsa. :param str signature_algorithm: signature algorithm. Valid values dsa_sha_1, dsa_sha_224, dsa_sha_256, rsa_md5, rsa_sha_1, rsa_sha_256, rsa_sha_384, rsa_sha_512, ecdsa_sha_1, ecdsa_sha_256, ecdsa_sha_384, ecdsa_sha_512. (Default: rsa_sha_512) :param int key_length: length of key. Key length depends on the key type. For example, RSA keys can be 1024, 2048, 3072, 4096. See SMC documentation for more details. :raises CreateElementFailed: failed to create CSR :raises ActionCommandFailed: Failure to self sign the certificate :rtype: TLSServerCredential
entailment
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. If importing as a string, be sure the string has carriage returns after each line and the final `END CERTIFICATE` line. Import a certificate and private key:: >>> tls = TLSServerCredential.import_signed( name='server2.test.local', certificate='mydir/server.crt', private_key='mydir/server.key') >>> tls TLSServerCredential(name=server2.test.local) :param str name: name of TLSServerCredential :param str certificate: fully qualified to the certificate file, string or file object :param str private_key: fully qualified to the private key file, string or file object :param str intermediate: fully qualified to the intermediate file, string or file object :raises CertificateImportError: failure during import :raises CreateElementFailed: failed to create credential :raises IOError: failure to find certificate files specified :rtype: TLSServerCredential """ 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: tls.delete() raise return tls
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. If importing as a string, be sure the string has carriage returns after each line and the final `END CERTIFICATE` line. Import a certificate and private key:: >>> tls = TLSServerCredential.import_signed( name='server2.test.local', certificate='mydir/server.crt', private_key='mydir/server.key') >>> tls TLSServerCredential(name=server2.test.local) :param str name: name of TLSServerCredential :param str certificate: fully qualified to the certificate file, string or file object :param str private_key: fully qualified to the private key file, string or file object :param str intermediate: fully qualified to the intermediate file, string or file object :raises CertificateImportError: failure during import :raises CreateElementFailed: failed to create credential :raises IOError: failure to find certificate files specified :rtype: TLSServerCredential
entailment
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 root trusted authority. The private key can be anywhere in this order. See https://tools.ietf.org/html/rfc4346#section-7.4.2. .. note:: There is no validation done on the certificates, therefore the order is assumed to be true. In addition, the root certificate will not be imported and should be separately imported as a trusted root CA using :class:`~TLSCertificateAuthority.create` If the certificate chain file has only two entries, it is assumed to be the server certificate and root certificate (no intermediates). In which case only the certificate is imported. If the chain file has 3 or more entries (all certificates), it will import the first as the server certificate, 2nd as the intermediate and ignore the root cert. You can optionally provide a seperate location for a private key file if this is not within the chain file contents. .. warning:: A private key is required to create a valid TLS Server Credential. :param str name: name of TLS Server Credential :param str certificate_file: fully qualified path to chain file or file object :param str private_key: fully qualified path to chain file or file object :raises IOError: error occurred reading or finding specified file :raises ValueError: Format issues with chain file or empty :rtype: TLSServerCredential """ 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 and ' 'was not provided. The private key is required to create a ' 'TLS Server Credential.') if contents: if len(contents) == 1: certificate = contents[0][1] intermediate = None else: certificate = contents[0][1] intermediate = contents[1][1] else: raise ValueError('No certificates found in certificate chain file. Did you ' 'provide only a private key?') 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: tls.delete() raise return tls
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 root trusted authority. The private key can be anywhere in this order. See https://tools.ietf.org/html/rfc4346#section-7.4.2. .. note:: There is no validation done on the certificates, therefore the order is assumed to be true. In addition, the root certificate will not be imported and should be separately imported as a trusted root CA using :class:`~TLSCertificateAuthority.create` If the certificate chain file has only two entries, it is assumed to be the server certificate and root certificate (no intermediates). In which case only the certificate is imported. If the chain file has 3 or more entries (all certificates), it will import the first as the server certificate, 2nd as the intermediate and ignore the root cert. You can optionally provide a seperate location for a private key file if this is not within the chain file contents. .. warning:: A private key is required to create a valid TLS Server Credential. :param str name: name of TLS Server Credential :param str certificate_file: fully qualified path to chain file or file object :param str private_key: fully qualified path to chain file or file object :raises IOError: error occurred reading or finding specified file :raises ValueError: Format issues with chain file or empty :rtype: TLSServerCredential
entailment
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.import_signed( name='myclientca', certificate_file='/pathto/server.crt' private_key_file='/pathto/server.key') :param str name: name of client protection CA :param str certificate_file: fully qualified path or string of certificate :param str private_key_file: fully qualified path or string of private key :raises CertificateImportError: failure during import :raises IOError: failure to find certificate files specified :rtype: ClientProtectionCA """ ca = ClientProtectionCA.create(name=name) try: ca.import_certificate(certificate) ca.import_private_key(private_key) except CertificateImportError: ca.delete() raise return ca
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.import_signed( name='myclientca', certificate_file='/pathto/server.crt' private_key_file='/pathto/server.key') :param str name: name of client protection CA :param str certificate_file: fully qualified path or string of certificate :param str private_key_file: fully qualified path or string of private key :raises CertificateImportError: failure during import :raises IOError: failure to find certificate files specified :rtype: ClientProtectionCA
entailment
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. :param str prefix: prefix used for derivating file names :param str password: password for private key :param public_key_algorithm: public key algorithm, either rsa, dsa or ecdsa :param str,int life_time: lifetime in days for CA :param int key_length: length in bits, either 1024 or 2048 :raises CreateElementFailed: creating element failed :raises ActionCommandFailed: failed to self sign the certificate :rtype: ClientProtectionCA """ 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: tls.make_request( method='create', json=json, resource='generate_self_signed_cert') except ActionCommandFailed: tls.delete() raise return tls
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. :param str prefix: prefix used for derivating file names :param str password: password for private key :param public_key_algorithm: public key algorithm, either rsa, dsa or ecdsa :param str,int life_time: lifetime in days for CA :param int key_length: length in bits, either 1024 or 2048 :raises CreateElementFailed: creating element failed :raises ActionCommandFailed: failed to self sign the certificate :rtype: ClientProtectionCA
entailment
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` """ self.format = format self.request.update(format=self.format.data)
Update the format for this query. :param format: new format to use for this query :type format: :py:mod:`smc_monitoring.models.formats`
entailment
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 in multiple log fields. .. seealso:: :class:`smc_monitoring.models.filters.InFilter` for examples. :param values: optional constructor args for :class:`smc_monitoring.models.filters.InFilter` :rtype: InFilter """ filt = InFilter(*values) self.update_filter(filt) return filt
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 in multiple log fields. .. seealso:: :class:`smc_monitoring.models.filters.InFilter` for examples. :param values: optional constructor args for :class:`smc_monitoring.models.filters.InFilter` :rtype: InFilter
entailment
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. :param values: optional constructor args for :class:`smc_monitoring.models.filters.AndFilter`. Typically this is a list of InFilter expressions. :type: list(QueryFilter) :rtype: AndFilter """ filt = AndFilter(*values) self.update_filter(filt) return filt
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. :param values: optional constructor args for :class:`smc_monitoring.models.filters.AndFilter`. Typically this is a list of InFilter expressions. :type: list(QueryFilter) :rtype: AndFilter
entailment
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.OrFilter` for examples. :param values: optional constructor args for :class:`smc_monitoring.models.filters.OrFilter`. Typically this is a list of InFilter expressions. :type: list(QueryFilter) :rtype: OrFilter """ filt = OrFilter(*values) self.update_filter(filt) return filt
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.OrFilter` for examples. :param values: optional constructor args for :class:`smc_monitoring.models.filters.OrFilter`. Typically this is a list of InFilter expressions. :type: list(QueryFilter) :rtype: OrFilter
entailment
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:: :class:`smc_monitoring.models.filters.NotFilter` for examples. :param values: optional constructor args for :class:`smc_monitoring.models.filters.NotFilter`. Typically this is a list of InFilter expressions. :type: list(QueryFilter) :rtype: OrFilter """ filt = NotFilter(*value) self.update_filter(filt) return filt
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:: :class:`smc_monitoring.models.filters.NotFilter` for examples. :param values: optional constructor args for :class:`smc_monitoring.models.filters.NotFilter`. Typically this is a list of InFilter expressions. :type: list(QueryFilter) :rtype: OrFilter
entailment
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 filter. Value is of type :class:`smc_monitoring.models.values.Value`. :type: list(QueryFilter) :rtype: DefinedFilter """ filt = DefinedFilter(*value) self.update_filter(filt) return filt
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 filter. Value is of type :class:`smc_monitoring.models.values.Value`. :type: list(QueryFilter) :rtype: DefinedFilter
entailment
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 options. For example:: Query.resolve_field_ids(ConnectionQuery.field_ids) :param list ids: list of log field IDs. Use LogField constants to simplify search. :return: raw dict representation of log fields :rtype: list(dict) """ request = { 'fetch': {'quantity': 0}, 'format': { 'type': 'detailed', 'field_ids': ids}, 'query': {} } query = Query(**kw) query.location = '/monitoring/log/socket' query.request = request for fields in query.execute(): if 'fields' in fields: return fields['fields'] return []
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 options. For example:: Query.resolve_field_ids(ConnectionQuery.field_ids) :param list ids: list of log field IDs. Use LogField constants to simplify search. :return: raw dict representation of log fields :rtype: list(dict)
entailment
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(). :return: list of dictionary fields with the field schema """ self.update_format(DetailedFormat()) for fields in self.execute(): if 'fields' in fields: return fields['fields']
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(). :return: list of dictionary fields with the field schema
entailment
def execute(self): """ Execute the query with optional timeout. The response to the execute query is the raw payload received from the websocket and will contain multiple dict keys and values. It is more common to call query.fetch_XXX which will filter the return result based on the method. Each result set will have a max batch size of 200 records. This method will also continuously return results until terminated. To make a single bounded fetch, call :meth:`.fetch_batch` or :meth:`.fetch_raw`. :param int sock_timeout: event loop interval :return: raw dict returned from query :rtype: dict(list) """ with SMCSocketProtocol(self, **self.sockopt) as protocol: for result in protocol.receive(): yield result
Execute the query with optional timeout. The response to the execute query is the raw payload received from the websocket and will contain multiple dict keys and values. It is more common to call query.fetch_XXX which will filter the return result based on the method. Each result set will have a max batch size of 200 records. This method will also continuously return results until terminated. To make a single bounded fetch, call :meth:`.fetch_batch` or :meth:`.fetch_raw`. :param int sock_timeout: event loop interval :return: raw dict returned from query :rtype: dict(list)
entailment
def fetch_raw(self, **kw): """ Fetch the records for this query. This fetch type will return the results in raw dict format. It is possible to limit the number of receives on the socket that return results before exiting by providing max_recv. This fetch should be used if you want to return only the result records returned from the query in raw dict format. Any other dict key/values from the raw query are ignored. :param int max_recv: max number of socket receive calls before returning from this query. If you want to wait longer for results before returning, increase max_iterations (default: 0) :return: list of query results :rtype: list(dict) """ self.sockopt.update(kw) with SMCSocketProtocol(self, **self.sockopt) as protocol: for result in protocol.receive(): if 'records' in result and result['records'].get('added'): yield result['records']['added']
Fetch the records for this query. This fetch type will return the results in raw dict format. It is possible to limit the number of receives on the socket that return results before exiting by providing max_recv. This fetch should be used if you want to return only the result records returned from the query in raw dict format. Any other dict key/values from the raw query are ignored. :param int max_recv: max number of socket receive calls before returning from this query. If you want to wait longer for results before returning, increase max_iterations (default: 0) :return: list of query results :rtype: list(dict)
entailment
def fetch_batch(self, formatter=TableFormat, **kw): """ Fetch and return in the specified format. Output format is a formatter class in :py:mod:`smc_monitoring.models.formatters`. This fetch type will be a single shot fetch unless providing max_recv keyword with a value greater than the default of 1. Keyword arguments available are kw in :meth:`.fetch_raw`. :param formatter: Formatter type for data representation. Any type in :py:mod:`smc_monitoring.models.formatters`. :return: generator returning data in specified format .. note:: You can provide your own formatter class, see :py:mod:`smc_monitoring.models.formatters` for more info. """ fmt = formatter(self) if 'max_recv' not in kw: kw.update(max_recv=1) for result in self.fetch_raw(**kw): yield fmt.formatted(result)
Fetch and return in the specified format. Output format is a formatter class in :py:mod:`smc_monitoring.models.formatters`. This fetch type will be a single shot fetch unless providing max_recv keyword with a value greater than the default of 1. Keyword arguments available are kw in :meth:`.fetch_raw`. :param formatter: Formatter type for data representation. Any type in :py:mod:`smc_monitoring.models.formatters`. :return: generator returning data in specified format .. note:: You can provide your own formatter class, see :py:mod:`smc_monitoring.models.formatters` for more info.
entailment
def fetch_live(self, formatter=TableFormat): """ Fetch a live stream query. This is the equivalent of selecting the "Play" option for monitoring fields within the SMC UI. Data will be streamed back in real time. :param formatter: Formatter type for data representation. Any type in :py:mod:`smc_monitoring.models.formatters`. :return: generator yielding results in specified format """ fmt = formatter(self) for results in self.execute(): if 'records' in results and results['records'].get('added'): yield fmt.formatted(results['records']['added'])
Fetch a live stream query. This is the equivalent of selecting the "Play" option for monitoring fields within the SMC UI. Data will be streamed back in real time. :param formatter: Formatter type for data representation. Any type in :py:mod:`smc_monitoring.models.formatters`. :return: generator yielding results in specified format
entailment
def fetch_meta_by_name(name, filter_context=None, exact_match=True): """ Find the element based on name and optional filters. By default, the name provided uses the standard filter query. Additional filters can be used based on supported collections in the SMC API. :method: GET :param str name: element name, can use * as wildcard :param str filter_context: further filter request, i.e. 'host', 'group', 'single_fw', 'network_elements', 'services', 'services_and_applications' :param bool exact_match: Do an exact match by name, note this still can return multiple entries :rtype: SMCResult """ result = SMCRequest( params={'filter': name, 'filter_context': filter_context, 'exact_match': exact_match}).read() if not result.json: result.json = [] return result
Find the element based on name and optional filters. By default, the name provided uses the standard filter query. Additional filters can be used based on supported collections in the SMC API. :method: GET :param str name: element name, can use * as wildcard :param str filter_context: further filter request, i.e. 'host', 'group', 'single_fw', 'network_elements', 'services', 'services_and_applications' :param bool exact_match: Do an exact match by name, note this still can return multiple entries :rtype: SMCResult
entailment
def blacklist(self, src, dst, duration=3600, **kw): """ Add blacklist to all defined engines. Use the cidr netmask at the end of src and dst, such as: 1.1.1.1/32, etc. :param src: source of the entry :param dst: destination of blacklist entry :raises ActionCommandFailed: blacklist apply failed with reason :return: None .. seealso:: :class:`smc.core.engine.Engine.blacklist`. Applying a blacklist at the system level will be a global blacklist entry versus an engine specific entry. .. note:: If more advanced blacklist is required using source/destination ports and protocols (udp/tcp), use kw to provide these arguments. See :py:func:`smc.elements.other.prepare_blacklist` for more details. """ self.make_request( method='create', resource='blacklist', json=prepare_blacklist(src, dst, duration, **kw))
Add blacklist to all defined engines. Use the cidr netmask at the end of src and dst, such as: 1.1.1.1/32, etc. :param src: source of the entry :param dst: destination of blacklist entry :raises ActionCommandFailed: blacklist apply failed with reason :return: None .. seealso:: :class:`smc.core.engine.Engine.blacklist`. Applying a blacklist at the system level will be a global blacklist entry versus an engine specific entry. .. note:: If more advanced blacklist is required using source/destination ports and protocols (udp/tcp), use kw to provide these arguments. See :py:func:`smc.elements.other.prepare_blacklist` for more details.
entailment
def license_install(self, license_file): """ Install a new license. :param str license_file: fully qualified path to the license jar file. :raises: ActionCommandFailed :return: None """ self.make_request( method='update', resource='license_install', files={ 'license_file': open(license_file, 'rb') })
Install a new license. :param str license_file: fully qualified path to the license jar file. :raises: ActionCommandFailed :return: None
entailment
def visible_security_group_mapping(self, filter=None): # @ReservedAssignment """ Return all security groups assigned to VSS container types. This is only available on SMC >= 6.5. :param str filter: filter for searching by name :raises ActionCommandFailed: element not found on this version of SMC :raises ResourceNotFound: unsupported method on SMC < 6.5 :return: dict """ if 'visible_security_group_mapping' not in self.data.links: raise ResourceNotFound('This entry point is only supported on SMC >= 6.5') return self.make_request(resource='visible_security_group_mapping', params={'filter': filter})
Return all security groups assigned to VSS container types. This is only available on SMC >= 6.5. :param str filter: filter for searching by name :raises ActionCommandFailed: element not found on this version of SMC :raises ResourceNotFound: unsupported method on SMC < 6.5 :return: dict
entailment
def references_by_element(self, element_href): """ Return all references to element specified. :param str element_href: element reference :return: list of references where element is used :rtype: list(dict) """ result = self.make_request( method='create', resource='references_by_element', json={ 'value': element_href}) return result
Return all references to element specified. :param str element_href: element reference :return: list of references where element is used :rtype: list(dict)
entailment
def export_elements(self, filename='export_elements.zip', typeof='all'): """ Export elements from SMC. Valid types are: all (All Elements)|nw (Network Elements)|ips (IPS Elements)| sv (Services)|rb (Security Policies)|al (Alerts)| vpn (VPN Elements) :param type: type of element :param filename: Name of file for export :raises TaskRunFailed: failure during export with reason :rtype: DownloadTask """ valid_types = ['all', 'nw', 'ips', 'sv', 'rb', 'al', 'vpn'] if typeof not in valid_types: typeof = 'all' return Task.download(self, 'export_elements', filename, params={'recursive': True, 'type': typeof})
Export elements from SMC. Valid types are: all (All Elements)|nw (Network Elements)|ips (IPS Elements)| sv (Services)|rb (Security Policies)|al (Alerts)| vpn (VPN Elements) :param type: type of element :param filename: Name of file for export :raises TaskRunFailed: failure during export with reason :rtype: DownloadTask
entailment
def import_elements(self, import_file): """ Import elements into SMC. Specify the fully qualified path to the import file. :param str import_file: system level path to file :raises: ActionCommandFailed :return: None """ self.make_request( method='create', resource='import_elements', files={ 'import_file': open(import_file, 'rb') })
Import elements into SMC. Specify the fully qualified path to the import file. :param str import_file: system level path to file :raises: ActionCommandFailed :return: None
entailment
def update_protocol_agent(self, protocol_agent): """ Update this service to use the specified protocol agent. After adding the protocol agent to the service you must call `update` on the element to commit. :param str,ProtocolAgent protocol_agent: protocol agent element or href :return: None """ if not protocol_agent: for pa in ('paValues', 'protocol_agent_ref'): self.data.pop(pa, None) else: self.data.update(protocol_agent_ref=element_resolver(protocol_agent))
Update this service to use the specified protocol agent. After adding the protocol agent to the service you must call `update` on the element to commit. :param str,ProtocolAgent protocol_agent: protocol agent element or href :return: None
entailment
def _get_param_values(self, name): """ Return the parameter by name as stored on the protocol agent payload. This loads the data from the local cache versus having to query the SMC for each parameter. :param str name: name of param :rtype: dict """ for param in self.data.get('paParameters', []): for _pa_parameter, values in param.items(): if values.get('name') == name: return values
Return the parameter by name as stored on the protocol agent payload. This loads the data from the local cache versus having to query the SMC for each parameter. :param str name: name of param :rtype: dict
entailment
def parameters(self): """ Protocol agent parameters are settings specific to the protocol agent type. Each protocol agent will have parameter settings that are configurable when a service uses a given protocol agent. Parameters on the protocol agent are templates that define settings exposed in the service. These are read-only attributes. :rtype: list(ProtocolParameter) """ return [type('ProtocolParameter', (SubElement,), { 'data': ElementCache(data=self._get_param_values(param.get('name')))} )(**param) for param in self.make_request(resource='pa_parameters')]
Protocol agent parameters are settings specific to the protocol agent type. Each protocol agent will have parameter settings that are configurable when a service uses a given protocol agent. Parameters on the protocol agent are templates that define settings exposed in the service. These are read-only attributes. :rtype: list(ProtocolParameter)
entailment
def protocol_parameter(self): """ The protocol parameter defined from the base protocol agent. This is a read-only element that provides some additional context to the parameter setting. :rtype: ProtocolParameter """ for parameter in self.protocol_agent.parameters: if parameter.href in self.protocol_agent_values.get('parameter_ref', []): return parameter
The protocol parameter defined from the base protocol agent. This is a read-only element that provides some additional context to the parameter setting. :rtype: ProtocolParameter
entailment
def _update(self, **kwargs): """ Update the mutable field `value`. :rtype: bool """ if 'value' in kwargs and self.protocol_agent_values.get('value') != \ kwargs.get('value'): self.protocol_agent_values.update(value=kwargs['value']) return True return False
Update the mutable field `value`. :rtype: bool
entailment
def proxy_server(self): """ The ProxyServer element referenced in this protocol parameter, if any. :return: The proxy server element or None if one is not assigned :rtype: ProxyServer """ # TODO: Workaround for SMC 6.4.3 which only provides the inspected service # reference. We need to find the Proxy Server from this ref. if self._inspected_service_ref: for proxy in ProxyServer.objects.all(): if self._inspected_service_ref.startswith(proxy.href): return proxy
The ProxyServer element referenced in this protocol parameter, if any. :return: The proxy server element or None if one is not assigned :rtype: ProxyServer
entailment
def _update(self, **kwargs): """ Internal method to update the parameter dict stored in attribute protocol_agent_values. Allows masking of real attribute names to something more sane. :rtype: bool """ updated = False if 'proxy_server' in kwargs: proxy_server = kwargs.get('proxy_server') if not proxy_server and self._inspected_service_ref: self.protocol_agent_values.pop('inspected_service_ref', None) updated = True elif isinstance(proxy_server, ProxyServer): # Need the inspected service reference for the protocol enabled_services = {svc.name:svc.href for svc in proxy_server.inspected_services} if self.protocol_agent.name not in enabled_services: raise MissingDependency('The specified ProxyServer %r does not enable ' 'the required protocol %s' % (proxy_server.name, self.protocol_agent.name)) if self._inspected_service_ref != enabled_services.get(self.protocol_agent.name): self.protocol_agent_values['inspected_service_ref'] = enabled_services.get( self.protocol_agent.name) updated = True return updated
Internal method to update the parameter dict stored in attribute protocol_agent_values. Allows masking of real attribute names to something more sane. :rtype: bool
entailment
def update(self, name, **kwargs): """ Update protocol agent parameters based on the parameter name. Provide the relevant keyword pairs based on the parameter type. When update is called, a boolean is returned indicating whether the field was successfully updated or not. You should check the return value and call `update` on the service to commit to SMC. Example of updating a TCP Service using the HTTPS Protocol Agent to set an HTTPS Inspection Exception:: >>> service = TCPService('httpsservice') >>> service.protocol_agent ProtocolAgent(name=HTTPS) >>> for parameter in service.protocol_agent_values: ... parameter ... ProxyServiceValue(name=redir_cis,description=Redirect connections to Proxy Server,proxy_server=None) BooleanValue(name=http_enforce_safe_search,description=Enforce SafeSearch,value=0) StringValue(name=http_server_stream_by_user_agent,description=Optimized server stream fingerprinting,value=Yes) StringValue(name=http_url_logging,description=Logging of accessed URLs,value=Yes) TlsInspectionPolicyValue(name=tls_policy,description=HTTPS Inspection Exceptions,tls_policy=None) StringValue(name=tls_inspection,description=HTTPS decryption and inspection,value=No) ... >>> service.protocol_agent_values.update(name='tls_policy', tls_policy=HTTPSInspectionExceptions('myexceptions')) True :param str name: The name of the parameter to update :param dict kwargs: The keyword args to perform the update :raises ElementNotFound: Can be thrown when an element reference was passed but the element does not exist :raises MissingDependency: A dependency was missing preventing the update. This can happen when adding a ProxyServer for a protocol that isn't enabled """ for value in self.items: if value.name == name: return value._update(**kwargs) return False
Update protocol agent parameters based on the parameter name. Provide the relevant keyword pairs based on the parameter type. When update is called, a boolean is returned indicating whether the field was successfully updated or not. You should check the return value and call `update` on the service to commit to SMC. Example of updating a TCP Service using the HTTPS Protocol Agent to set an HTTPS Inspection Exception:: >>> service = TCPService('httpsservice') >>> service.protocol_agent ProtocolAgent(name=HTTPS) >>> for parameter in service.protocol_agent_values: ... parameter ... ProxyServiceValue(name=redir_cis,description=Redirect connections to Proxy Server,proxy_server=None) BooleanValue(name=http_enforce_safe_search,description=Enforce SafeSearch,value=0) StringValue(name=http_server_stream_by_user_agent,description=Optimized server stream fingerprinting,value=Yes) StringValue(name=http_url_logging,description=Logging of accessed URLs,value=Yes) TlsInspectionPolicyValue(name=tls_policy,description=HTTPS Inspection Exceptions,tls_policy=None) StringValue(name=tls_inspection,description=HTTPS decryption and inspection,value=No) ... >>> service.protocol_agent_values.update(name='tls_policy', tls_policy=HTTPSInspectionExceptions('myexceptions')) True :param str name: The name of the parameter to update :param dict kwargs: The keyword args to perform the update :raises ElementNotFound: Can be thrown when an element reference was passed but the element does not exist :raises MissingDependency: A dependency was missing preventing the update. This can happen when adding a ProxyServer for a protocol that isn't enabled
entailment
def add_access_list(self, accesslist, rank=None): """ Add an access list to the match condition. Valid access list types are IPAccessList (v4 and v6), IPPrefixList (v4 and v6), AS Path, CommunityAccessList, ExtendedCommunityAccessList. """ self.conditions.append( dict(access_list_ref=accesslist.href, type='element', rank=rank))
Add an access list to the match condition. Valid access list types are IPAccessList (v4 and v6), IPPrefixList (v4 and v6), AS Path, CommunityAccessList, ExtendedCommunityAccessList.
entailment
def add_metric(self, value, rank=None): """ Add a metric to this match condition :param int value: metric value """ self.conditions.append( dict(metric=value, type='metric', rank=rank))
Add a metric to this match condition :param int value: metric value
entailment
def add_next_hop(self, access_or_prefix_list, rank=None): """ Add a next hop condition. Next hop elements must be of type IPAccessList or IPPrefixList. :raises ElementNotFound: If element specified does not exist """ self.conditions.append(dict( next_hop_ref=access_or_prefix_list.href, type='next_hop', rank=rank))
Add a next hop condition. Next hop elements must be of type IPAccessList or IPPrefixList. :raises ElementNotFound: If element specified does not exist
entailment
def add_peer_address(self, ext_bgp_peer_or_fw, rank=None): """ Add a peer address. Peer address types are ExternalBGPPeer or Engine. :raises ElementNotFound: If element specified does not exist """ if ext_bgp_peer_or_fw.typeof == 'external_bgp_peer': ref = 'external_bgp_peer_address_ref' else: # engine ref = 'fwcluster_peer_address_ref' self.conditions.append( {ref: ext_bgp_peer_or_fw.href, 'rank': rank, 'type': 'peer_address'})
Add a peer address. Peer address types are ExternalBGPPeer or Engine. :raises ElementNotFound: If element specified does not exist
entailment
def remove_condition(self, rank): """ Remove a condition element using it's rank. You can find the rank and element for a match condition by iterating the match condition:: >>> rule1 = rm.route_map_rules.get(0) >>> for condition in rule1.match_condition: ... condition ... Condition(rank=1, element=ExternalBGPPeer(name=bgppeer)) Condition(rank=2, element=IPAccessList(name=myacl)) Condition(rank=3, element=Metric(value=20)) Then delete by rank. Call update on the rule after making the modification. :param int rank: rank of the condition to remove :raises UpdateElementFailed: failed to update rule :return: None """ self.conditions[:] = [r for r in self.conditions if r.get('rank') != rank]
Remove a condition element using it's rank. You can find the rank and element for a match condition by iterating the match condition:: >>> rule1 = rm.route_map_rules.get(0) >>> for condition in rule1.match_condition: ... condition ... Condition(rank=1, element=ExternalBGPPeer(name=bgppeer)) Condition(rank=2, element=IPAccessList(name=myacl)) Condition(rank=3, element=Metric(value=20)) Then delete by rank. Call update on the rule after making the modification. :param int rank: rank of the condition to remove :raises UpdateElementFailed: failed to update rule :return: None
entailment