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