code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
with tf.variable_scope("l2_distance"):
return tf.norm(preds - labels, ord=2) | def l2_distance(labels, preds) | Compute the l2_distance.
:param labels: A float tensor of shape [batch_size, ..., X] representing the labels.
:param preds: A float tensor of shape [batch_size, ..., X] representing the predictions.
:return: A float tensor of shape [batch_size, ...] representing the l2 distance. | 3.491715 | 4.635918 | 0.753187 |
with tf.variable_scope("cross_entropy"):
return tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=logits) | def cross_entropy(labels, logits) | Calculate the cross_entropy.
:param labels: A float tensor of shape [batch_size, ..., num_classes] representing the label class probabilities.
:param logits: A float tensor of shape [batch_size, ..., num_classes] representing the logits.
:return: A tensor representing the cross entropy. | 1.969525 | 2.249102 | 0.875694 |
parser = argparse.ArgumentParser()
parser.add_argument("template_file", help="/path/to/template_file.json")
parser.add_argument("env", help=", ".join(EFConfig.ENV_LIST))
parser.add_argument("--sr", help="optional /path/to/service_registry_file.json", default=None)
parser.add_argument("--verbose", help="Pri... | def handle_args_and_set_context(args) | Args:
args: the command line args, probably passed from main() as sys.argv[1:]
Returns:
a populated EFCFContext object (extends EFContext)
Raises:
IOError: if service registry file can't be found or can't be opened
RuntimeError: if repo or branch isn't as spec'd in ef_config.EF_REPO and ef_config.EF... | 3.487656 | 3.301311 | 1.056446 |
if WHERE == "ec2":
config_reader = EFInstanceinitConfigReader("s3", service, log_info, RESOURCES["s3"])
resolver = EFTemplateResolver()
elif WHERE == "virtualbox-kvm":
config_path = "{}/{}".format(VIRTUALBOX_CONFIG_ROOT, service)
config_reader = EFInstanceinitConfigReader("file", config_path, log... | def merge_files(service, skip_on_user_group_error=False) | Given a prefix, find all templates below; merge with parameters; write to "dest"
Args:
service: "<service>", "all", or "ssh"
skip_on_user_group_error: True or False
For S3, full path becomes:
s3://ellation-cx-global-configs/<service>/templates/<filename>
s3://ellation-cx-global-configs/<service>/pa... | 4.188222 | 4.091979 | 1.02352 |
try:
return http_get_metadata(metadata_key)
except IOError as error:
fail("Exception in http_get_metadata {} {}".format(metadata_key, repr(error))) | def get_metadata_or_fail(metadata_key) | Call get_metadata; halt with fail() if it raises an exception | 6.04371 | 4.856209 | 1.244533 |
# load template
if isinstance(template, str):
self.template = template
elif isinstance(template, file):
try:
self.template = template.read()
template.close()
except IOError as error:
fail("Exception loading template from file: ", error)
else:
fail("Un... | def load(self, template, parameters=None) | 'template'
Loads template text from a 'string' or 'file' type
Template text contains {{TOKEN}} symbols to be replaced
'parameters'
parameters contains environment-specific sections as discussed in the class documentation.
the 'parameters' arg can be None, a 'string', 'file', or 'dictionary'
Wh... | 2.73658 | 2.756848 | 0.992648 |
if not self.parameters:
return None
# Hierarchically lookup the key
result = None
if "default" in self.parameters and symbol in self.parameters["default"]:
result = self.parameters["default"][symbol]
if self.resolved["ENV_SHORT"] in self.parameters and symbol in self.parameters[self... | def search_parameters(self, symbol) | Hierarchically searches for 'symbol' in the parameters blob if there is one (would have
been retrieved by 'load()'). Order is: default, <env_short>, <env>
Returns
Hierarchically resolved value for 'symbol', or None if a match is not found or there are no parameters | 3.263814 | 2.548312 | 1.280775 |
# Ensure that our symbols are clean and are not from a previous template that was rendered
self.symbols = set()
# Until all symbols are resolved or it is determined that some cannot be resolved, repeat:
go_again = True
while go_again:
go_again = False # if at least one symbol isn't resol... | def render(self) | Find {{}} tokens; resolve then replace them as described elsewhere
Resolution is multi-pass: tokens may be nested to form parts of other tokens.
Token search steps when resolving symbols
- 1. lookups of AWS resource identifiers, such as a security group ID
- 2. secure credentials
- 3. version... | 5.562776 | 5.085365 | 1.093879 |
n_left = len(re.findall("{{", self.template))
n_right = len(re.findall("}}", self.template))
return n_left, n_right | def count_braces(self) | returns a count of "{{" and "}}" in the template, as (N_left_braces, N_right_braces)
Useful to check after resolve() has run, to infer that template has an error since no {{ or }}
should be present in the template after resolve() | 2.888636 | 2.11463 | 1.366024 |
left_braces, right_braces = self.count_braces()
return len(self.unresolved_symbols()) == left_braces == right_braces == 0 | def resolved_ok(self) | Shortcut to testing unresolved_symbols and count_braces separately.
Returns false if there are unresolved symbols or {{ or }} braces remaining, true otherwise | 6.374851 | 3.319357 | 1.920508 |
parser = argparse.ArgumentParser()
parser.add_argument("env", help="environment")
parser.add_argument("path_to_template", help="path to the config template to process")
parser.add_argument("--no_params", help="disable loading values from params file", action="store_true", default=False)
parser.add_argument... | def handle_args_and_set_context(args) | Args:
args: the command line args, probably passed from main() as sys.argv[1:]
Returns:
a populated Context object based on CLI args | 3.373768 | 3.257105 | 1.035818 |
resolver = EFTemplateResolver(
profile=context.profile,
region=context.region,
env=context.env,
service=context.service
)
try:
with open(context.template_path, 'r') as f:
template_body = f.read()
f.close()
except IOError as error:
raise IOError("Error loading temp... | def merge_files(context) | Given a context containing path to template, env, and service:
merge config into template and output the result to stdout
Args:
context: a populated context object | 4.632159 | 4.62905 | 1.000672 |
parser = argparse.ArgumentParser()
parser.add_argument("configpath", default=None, nargs="?",
help="/path/to/configs (always a directory; if omitted, all /configs are checked")
parser.add_argument("--verbose", action="store_true", default=False)
parsed_args = vars(parser.parse_args(args... | def handle_args(args) | Handle command line arguments
Raises:
Exception if the config path wasn't explicitly state and dead reckoning based on script location fails | 2.897354 | 2.75029 | 1.053472 |
json_fh = open(json_filespec)
config_dict = json.load(json_fh)
json_fh.close()
return config_dict | def load_json(json_filespec) | Loads JSON from a config file
Args:
json_filespec: path/to/file.json
Returns:
a dict made from the JSON read, if successful
Raises:
IOError if the file could not be opened
ValueError if the JSON could not be read successfully
RuntimeError if something else went wrong | 2.457844 | 3.272066 | 0.75116 |
# get search key and env/service from token
try:
key, envservice = token.split(",")
except ValueError:
return None
# get env, service from value
try:
env, service = envservice.split("/")
except ValueError as e:
raise RuntimeError("Request:{} can't resolve to env, ser... | def lookup(self, token) | Return key version if found, None otherwise
Lookup should look like this:
pattern:
<key>,<env>/<service>
example:
ami-id,staging/core | 7.424408 | 5.400601 | 1.374737 |
if next((policy for policy in self.all_alerts if policy['name'] == policy_name), False):
return True | def alert_policy_exists(self, policy_name) | Check to see if an alert policy exists in NewRelic. Return True if so, False if not | 6.00703 | 4.839032 | 1.24137 |
policy_data = { 'policy': { 'incident_preference': 'PER_POLICY', 'name': policy_name } }
create_policy = requests.post(
'https://api.newrelic.com/v2/alerts_policies.json',
headers=self.auth_header,
data=json.dumps(policy_data))
create_policy.raise_for_status()
policy_id = create_p... | def create_alert_policy(self, policy_name) | Creates an alert policy in NewRelic | 2.778511 | 2.561507 | 1.084717 |
if name:
element = fetch_meta_by_name(name)
if element.href:
return element.href | def element_href(name) | Get specified element href by element name
:param name: name of element
:return: string href location of object, else None | 6.763309 | 7.647533 | 0.884378 |
if name:
element = fetch_json_by_name(name)
if element.json:
return element.json | def element_as_json(name) | Get specified element json data by name
:param name: name of element
:return: json data representing element, else None | 6.490926 | 7.164589 | 0.905973 |
if name:
element_href = element_href_use_filter(name, _filter)
if element_href:
return element_by_href_as_json(element_href) | def element_as_json_with_filter(name, _filter) | Get specified element json data by name with filter.
Filter can be any valid element type.
:param name: name of element
:param _filter: element filter, host, network, tcp_service,
network_elements, services, services_and_applications, etc
:return: json data representing element, els... | 4.910301 | 5.884686 | 0.83442 |
if name:
element = fetch_meta_by_name(name)
if element.json:
return element.json | def element_info_as_json(name) | Get specified element META data based on search query
This is the base level search that returns basic object info
with the following attributes:
* href: link to element
* name: name of element
* type: type of element
:param str name: name of element
:return: list dict with meta (href, nam... | 6.91018 | 8.194766 | 0.843243 |
if name and _filter:
element = fetch_meta_by_name(name, filter_context=_filter)
if element.json:
return element.json | def element_info_as_json_with_filter(name, _filter) | Top level json meta data (href, name, type) for element
:param str name: name of element
:param str _filter: filter of entry point
:return: list dict with metadata, otherwise None | 7.38677 | 8.313592 | 0.888517 |
if name:
element = fetch_meta_by_name(name, exact_match=False)
return element.json | def element_href_use_wildcard(name) | Get element href using a wildcard rather than matching only on the name
field. This will likely return multiple results.
:param name: name of element
:return: list of matched elements | 11.315964 | 14.688308 | 0.770406 |
if name and _filter:
element = fetch_meta_by_name(name, filter_context=_filter)
if element.json:
return element.json.pop().get('href') | def element_href_use_filter(name, _filter) | Get element href using filter
Filter should be a valid entry point value, ie host, router, network,
single_fw, etc
:param name: name of element
:param _filter: filter type, unknown filter will result in no matches
:return: element href (if found), else None | 8.310038 | 9.346057 | 0.889149 |
if href:
element = fetch_json_by_href(href, params=params)
if element:
return element.json | def element_by_href_as_json(href, params=None) | Get specified element by href
:param href: link to object
:param params: optional search query parameters
:return: json data representing element, else None | 4.464075 | 5.173853 | 0.862814 |
if href:
element = fetch_json_by_href(href)
if element.json:
return element.json.get('name') | def element_name_by_href(href) | The element href is known, possibly from a reference in an
elements json. You want to retrieve the name of this element.
:param str href: href of element
:return: str name of element, or None | 5.302312 | 5.780988 | 0.917198 |
if href:
element = fetch_json_by_href(href)
if element.json:
for entries in element.json.get('link'):
if entries.get('rel') == 'self':
typeof = entries.get('type')
return (element.json.get('name'),
typeof) | def element_name_and_type_by_href(href) | Retrieve the element name and type of element based on the href.
You may have a href that is within another element reference and
want more information on that reference.
:param str href: href of element
:return: tuple (name, type) | 4.64129 | 5.165236 | 0.898563 |
if href:
element = fetch_json_by_href(href)
if element.json:
return element.json.get(attr_name) | def element_attribute_by_href(href, attr_name) | The element href is known and you want to retrieve a specific
attribute from that element.
For example, if you want a specific attribute by it's name::
search.element_attribute_by_href(href_to_resource, 'name')
:param str href: href of element
:param str attr_name: name of attribute
:retu... | 4.848578 | 6.994676 | 0.693181 |
if href:
element = fetch_json_by_href(href, params=params)
if element:
return element | def element_by_href_as_smcresult(href, params=None) | Get specified element returned as an SMCResult object
:param href: href direct link to object
:return: :py:class:`smc.api.web.SMCResult` with etag, href and
element field holding json, else None | 5.50478 | 5.549052 | 0.992022 |
if name:
element = fetch_meta_by_name(name, filter_context=_filter)
if element.msg:
return element
if element.json:
return element_by_href_as_smcresult(element.json.pop().get('href')) | def element_as_smcresult_use_filter(name, _filter) | Return SMCResult object and use search filter to
find object
:param name: name of element to find
:param _filter: filter to use, i.e. tcp_service, host, etc
:return: :py:class:`smc.api.web.SMCResult` | 8.724389 | 9.687289 | 0.900602 |
if filter:
return [{k: element_href_use_filter(k, filter)
for k in list_to_find}]
return [{k: element_href(k) for k in list_to_find}]
except TypeError:
logger.error("{} is not iterable".format(list_to_find)) | def element_href_by_batch(list_to_find, filter=None): # @ReservedAssignment
try | Find batch of entries by name. Reduces number of find calls from
calling class.
:param list list_to_find: list of names to find
:param filter: optional filter, i.e. 'tcp_service', 'host', etc
:return: list: {name: href, name: href}, href may be None if not found | 4.435015 | 5.154692 | 0.860384 |
if name:
entry = element_entry_point(name)
if entry: # in case an invalid entry point is specified
result = element_by_href_as_json(entry)
return result | def all_elements_by_type(name) | Get specified elements based on the entry point verb from SMC api
To get the entry points available, you can get these from the session::
session.cache.entry_points
Execution will get the entry point for the element type, then get all
elements that match.
For example::
search.all_ele... | 12.628458 | 11.065336 | 1.141263 |
result = fetch_meta_by_name(name)
if result.href:
result = fetch_json_by_href(result.href)
return result | def fetch_json_by_name(name) | Fetch json based on the element name
First gets the href based on a search by name, then makes a
second query to obtain the element json
:method: GET
:param str name: element name
:return: :py:class:`smc.api.web.SMCResult` | 4.279315 | 4.447605 | 0.962162 |
result = SMCRequest(href=href, params=params).read()
if result:
result.href = href
return result | def fetch_json_by_href(href, params=None) | Fetch json for element by using href. Params should be key/value
pairs. For example {'filter': 'myfilter'}
:method: GET
:param str href: href of the element
:params dict params: optional search query parameters
:return: :py:class:`smc.api.web.SMCResult` | 10.596251 | 10.118547 | 1.047211 |
json = {'name': name,
'negotiation_expiration': negotiation_expiration,
'negotiation_retry_timer': negotiation_retry_timer,
'negotiation_retry_max_number': negotiation_retry_max_number,
'negotiation_retry_timer_max': negotiation_retry_time... | def create(cls, name, negotiation_expiration=200000,
negotiation_retry_timer=500,
negotiation_retry_max_number=32,
negotiation_retry_timer_max=7000,
certificate_cache_crl_validity=90000,
mobike_after_sa_update=False,
mobike_before... | Create a new gateway setting profile.
:param str name: name of profile
:param int negotiation_expiration: expire after (ms)
:param int negotiation_retry_timer: retry time length (ms)
:param int negotiation_retry_max_num: max number of retries allowed
:param int negotiation_retry... | 1.338459 | 1.412613 | 0.947506 |
json = {'name': name,
'trust_all_cas': trust_all_cas}
return ElementCreator(cls, json) | def create(cls, name, trust_all_cas=True) | Create new External Gateway
:param str name: name of test_external gateway
:param bool trust_all_cas: whether to trust all internal CA's
(default: True)
:return: instance with meta
:rtype: ExternalGateway | 4.984605 | 7.074297 | 0.704608 |
if external_endpoint:
for endpoint in external_endpoint:
if 'name' not in endpoint:
raise ValueError('External endpoints are configured '
'but missing the name parameter.')
if vpn_site:
for site in vpn_... | def update_or_create(cls, name, external_endpoint=None, vpn_site=None,
trust_all_cas=True, with_status=False) | Update or create an ExternalGateway. The ``external_endpoint`` and
``vpn_site`` parameters are expected to be a list of dicts with key/value
pairs to satisfy the respective elements create constructor. VPN Sites will
represent the final state of the VPN site list. ExternalEndpoint that are
... | 2.631876 | 2.433223 | 1.081642 |
json = {'name': name,
'address': address,
'balancing_mode': balancing_mode,
'dynamic': dynamic,
'enabled': enabled,
'nat_t': nat_t,
'force_nat_t': force_nat_t,
'ipsec_vpn': ipsec_vpn}
... | def create(self, name, address=None, enabled=True, balancing_mode='active',
ipsec_vpn=True, nat_t=False, force_nat_t=False, dynamic=False,
ike_phase1_id_type=None, ike_phase1_id_value=None) | Create an test_external endpoint. Define common settings for that
specify the address, enabled, nat_t, name, etc. You can also omit
the IP address if the endpoint is dynamic. In that case, you must
also specify the ike_phase1 settings.
:param str name: name of test_external endpoint
... | 2.076949 | 2.16284 | 0.960288 |
if 'address' in kw:
external_endpoint = external_gateway.external_endpoint.get_contains(
'({})'.format(kw['address']))
else:
external_endpoint = external_gateway.external_endpoint.get_contains(name)
updated = False
created = False... | def update_or_create(cls, external_gateway, name, with_status=False, **kw) | Update or create external endpoints for the specified external gateway.
An ExternalEndpoint is considered unique based on the IP address for the
endpoint (you cannot add two external endpoints with the same IP). If the
external endpoint is dynamic, then the name is the unique identifier.
... | 3.066066 | 2.737177 | 1.120156 |
if self.enabled:
self.data['enabled'] = False
else:
self.data['enabled'] = True
self.update() | def enable_disable(self) | Enable or disable this endpoint. If enabled, it will be disabled
and vice versa.
:return: None | 3.306275 | 3.756078 | 0.880247 |
if self.force_nat_t:
self.data['force_nat_t'] = False
else:
self.data['force_nat_t'] = True
self.update() | def enable_disable_force_nat_t(self) | Enable or disable NAT-T on this endpoint. If enabled, it will be
disabled and vice versa.
:return: None | 2.728189 | 3.037204 | 0.898257 |
site_element = element_resolver(site_element)
json = {
'name': name,
'site_element': site_element}
return ElementCreator(
self.__class__,
href=self.href,
json=json) | def create(self, name, site_element) | Create a VPN site for an internal or external gateway
:param str name: name of site
:param list site_element: list of protected networks/hosts
:type site_element: list[str,Element]
:raises CreateElementFailed: create element failed with reason
:return: href of new element
... | 5.945971 | 6.495111 | 0.915453 |
site_element = [] if not site_element else site_element
site_elements = [element_resolver(element) for element in site_element]
vpn_site = external_gateway.vpn_site.get_exact(name)
updated = False
created = False
if vpn_site: # If difference, reset
if... | def update_or_create(cls, external_gateway, name, site_element=None,
with_status=False) | Update or create a VPN Site elements or modify an existing VPN
site based on value of provided site_element list. The resultant
VPN site end result will be what is provided in the site_element
argument (can also be an empty list to clear existing).
:param ExternalGateway externa... | 2.77451 | 2.587284 | 1.072364 |
element = element_resolver(element)
self.data['site_element'].extend(element)
self.update() | def add_site_element(self, element) | Add a site element or list of elements to this VPN.
:param list element: list of Elements or href's of vpn site
elements
:type element: list(str,Network)
:raises UpdateElementFailed: fails due to reason
:return: None | 10.113594 | 11.280329 | 0.896569 |
try:
return name.href
except AttributeError:
if name and name.startswith('http'):
return name
except ElementNotFound:
return Location.create(name=name.name).href if not \
search_only else None
# Get all locations; tmp to support earlier 6.x ... | def location_helper(name, search_only=False) | Location finder by name. If location doesn't exist, create it
and return the href
:param str,Element name: location to resolve. If the location is
by name, it will be retrieved or created, if href, returned
and if Location, href returned. If None, settings an elements
location to None w... | 6.436845 | 5.635964 | 1.142102 |
if zone is None:
return None
elif isinstance(zone, Zone):
return zone.href
elif zone.startswith('http'):
return zone
return Zone.get_or_create(name=zone).href | def zone_helper(zone) | Zone finder by name. If zone doesn't exist, create it and
return the href
:param str zone: name of zone (if href, will be returned as is)
:return str href: href of zone | 4.431212 | 3.528002 | 1.256012 |
if interface is None:
return LogicalInterface.get_or_create(name='default_eth').href
elif isinstance(interface, LogicalInterface):
return interface.href
elif interface.startswith('http'):
return interface
return LogicalInterface.get_or_create(name=interface).href | def logical_intf_helper(interface) | Logical Interface finder by name. Create if it doesn't exist.
This is useful when adding logical interfaces to for inline
or capture interfaces.
:param interface: logical interface name
:return str href: href of logical interface | 3.705532 | 3.852886 | 0.961755 |
self.make_request(
ModificationFailed,
method='update',
resource='change_password',
params={'password': password}) | def change_password(self, password) | Change user password. Change is committed immediately.
:param str password: new password
:return: None | 12.052385 | 13.118166 | 0.918755 |
if 'permissions' not in self.data:
self.data['superuser'] = False
self.data['permissions'] = {'permission':[]}
for p in permission:
self.data['permissions']['permission'].append(p.data)
self.update() | def add_permission(self, permission) | Add a permission to this Admin User. A role defines permissions that
can be enabled or disabled. Elements define the target for permission
operations and can be either Access Control Lists, Engines or Policy
elements. Domain specifies where the access is granted. The Shared
Domain is def... | 3.871985 | 3.845765 | 1.006818 |
if 'permissions' in self.data:
_permissions = self.data['permissions']['permission']
return [Permission(**perm) for perm in _permissions]
return [] | def permissions(self) | Return each permission role mapping for this Admin User. A permission
role will have 3 fields:
* Domain
* Role (Viewer, Operator, etc)
* Elements (Engines, Policies, or ACLs)
:return: permissions as list
:rtype: list(Permission) | 4.275603 | 4.316031 | 0.990633 |
engines = [] if engine_target is None else engine_target
json = {'name': name,
'enabled': enabled,
'allow_sudo': allow_sudo,
'console_superuser': console_superuser,
'allowed_to_login_in_shared': allowed_to_login_in_shared,
... | def create(cls, name, local_admin=False, allow_sudo=False,
superuser=False, enabled=True, engine_target=None,
can_use_api=True, console_superuser=False,
allowed_to_login_in_shared=True, comment=None) | Create an admin user account.
.. versionadded:: 0.6.2
Added can_use_api, console_superuser, and allowed_to_login_in_shared.
Requires SMC >= SMC 6.4
:param str name: name of account
:param bool local_admin: is a local admin only
:param bool allow_sudo: al... | 2.145232 | 2.078004 | 1.032352 |
self.make_request(
ModificationFailed,
method='update',
resource='change_engine_password',
params={'password': password}) | def change_engine_password(self, password) | Change Engine password for engines on allowed
list.
:param str password: password for engine level
:raises ModificationFailed: failed setting password on engine
:return: None | 10.56808 | 7.990368 | 1.322602 |
json = {
'enabled': enabled,
'name': name,
'superuser': superuser}
return ElementCreator(cls, json) | def create(cls, name, enabled=True, superuser=True) | Create a new API Client. Once client is created,
you can create a new password by::
>>> client = ApiClient.create('myclient')
>>> print(client)
ApiClient(name=myclient)
>>> client.change_password('mynewpassword')
:param str name: name of client
:... | 5.69744 | 8.771563 | 0.649535 |
node_list = []
for nodeid in range(1, nodes + 1): # start at nodeid=1
node_list.append(Node._create(
name,
node_type,
nodeid,
loopback_ndi))
domain_server_list = []
if domain_server_address:
... | def _create(cls, name, node_type,
physical_interfaces,
nodes=1, loopback_ndi=None,
log_server_ref=None,
domain_server_address=None,
enable_antivirus=False, enable_gti=False,
sidewinder_proxy_enabled=False,
de... | Create will return the engine configuration as a dict that is a
representation of the engine. The creating class will also add
engine specific requirements before constructing the request
and sending to SMC (which will serialize the dict to json).
:param name: name of engine
:pa... | 3.072125 | 3.159911 | 0.972219 |
for node in self.nodes:
node.rename(name)
self.update(name=name)
self.vpn.rename(name) | def rename(self, name) | Rename the firewall engine, nodes, and internal gateway (VPN gw)
:return: None | 6.135555 | 5.036386 | 1.218246 |
location = Element.from_href(self.location_ref)
if location and location.name == 'Default':
return None
return location | def location(self) | The location for this engine. May be None if no specific
location has been assigned.
:param value: location to assign engine. Can be name, str href,
or Location element. If name, it will be automatically created
if a Location with the same name doesn't exist.
:raises Upd... | 14.082579 | 12.737799 | 1.105574 |
resource = sub_collection(
self.get_relation(
'nodes'),
Node)
resource._load_from_engine(self, 'nodes')
return resource | def nodes(self) | Return a list of child nodes of this engine. This can be
used to iterate to obtain access to node level operations
::
>>> print(list(engine.nodes))
[Node(name=myfirewall node 1)]
>>> engine.nodes.get(0)
Node(name=myfirewall node 1)
... | 22.603924 | 21.103561 | 1.071095 |
acl_list = list(AccessControlList.objects.all())
def acl_map(elem_href):
for elem in acl_list:
if elem.href == elem_href:
return elem
acls = self.make_request(
UnsupportedEngineFeature,
resource='permission... | def permissions(self) | Retrieve the permissions for this engine instance.
::
>>> from smc.core.engine import Engine
>>> engine = Engine('myfirewall')
>>> for x in engine.permissions:
... print(x)
...
AccessControlList(name=ALL Elements)
AccessCont... | 8.421853 | 7.271702 | 1.158168 |
if 'pending_changes' in self.data.links:
return PendingChanges(self)
raise UnsupportedEngineFeature(
'Pending changes is an unsupported feature on this engine: {}'
.format(self.type)) | def pending_changes(self) | Pending changes provides insight into changes on an engine that are
pending approval or disapproval. Feature requires SMC >= v6.2.
:raises UnsupportedEngineFeature: SMC version >= 6.2 is required to
support pending changes
:rtype: PendingChanges | 8.90092 | 4.965413 | 1.792584 |
alias_list = list(Alias.objects.all())
for alias in self.make_request(resource='alias_resolving'):
yield Alias._from_engine(alias, alias_list) | def alias_resolving(self) | Alias definitions with resolved values as defined on this engine.
Aliases can be used in rules to simplify multiple object creation
::
fw = Engine('myfirewall')
for alias in fw.alias_resolving():
print(alias, alias.resolved_value)
...
(Ali... | 10.526839 | 9.163198 | 1.148817 |
self.make_request(
EngineCommandFailed,
method='create',
resource='blacklist',
json=blacklist.entries) | def blacklist_bulk(self, blacklist) | Add blacklist entries to the engine node in bulk. For blacklist to work,
you must also create a rule with action "Apply Blacklist".
First create your blacklist entries using :class:`smc.elements.other.Blacklist`
then provide the blacklist to this method.
:param blacklist Blackli... | 25.98064 | 26.126776 | 0.994407 |
try:
from smc_monitoring.monitors.blacklist import BlacklistQuery
except ImportError:
pass
else:
query = BlacklistQuery(self.name)
for record in query.fetch_as_element(**kw):
yield record | def blacklist_show(self, **kw) | .. versionadded:: 0.5.6
Requires pip install smc-python-monitoring
Blacklist show requires that you install the smc-python-monitoring
package. To obtain blacklist entries from the engine you need to
use this extension to plumb the websocket to the session. If you
nee... | 6.172287 | 4.463288 | 1.382901 |
self.make_request(
EngineCommandFailed,
method='create',
resource='add_route',
params={'gateway': gateway,
'network': network}) | def add_route(self, gateway, network) | Add a route to engine. Specify gateway and network.
If this is the default gateway, use a network address of
0.0.0.0/0.
.. note: This will fail if the gateway provided does not have a
corresponding interface on the network.
:param str gateway: gateway of an existing in... | 10.688096 | 6.985972 | 1.529937 |
try:
result = self.make_request(
EngineCommandFailed,
resource='routing_monitoring')
return Route(result)
except SMCConnectionError:
raise EngineCommandFailed('Timed out waiting for routes') | def routing_monitoring(self) | Return route table for the engine, including
gateway, networks and type of route (dynamic, static).
Calling this can take a few seconds to retrieve routes
from the engine.
Find all routes for engine resource::
>>> engine = Engine('sg_vm')
>>> for route in engine... | 15.811993 | 9.859081 | 1.6038 |
resource = create_collection(
self.get_relation(
'virtual_resources',
UnsupportedEngineFeature),
VirtualResource)
resource._load_from_engine(self, 'virtualResources')
return resource | def virtual_resource(self) | Available on a Master Engine only.
To get all virtual resources call::
engine.virtual_resource.all()
:raises UnsupportedEngineFeature: master engine only
:rtype: CreateCollection(VirtualResource) | 16.131969 | 11.079629 | 1.456003 |
self.make_request(
EngineCommandFailed,
method='create',
href=self.get_relation(interface.typeof),
json=interface)
self._del_cache() | def add_interface(self, interface) | Add interface is a lower level option to adding interfaces directly
to the engine. The interface is expected to be an instance of
Layer3PhysicalInterface, Layer2PhysicalInterface, TunnelInterface,
or ClusterInterface. The engines instance cache is flushed after
this call is made to provi... | 27.940578 | 25.274118 | 1.105502 |
return Task.execute(self, 'refresh',
timeout=timeout, wait_for_finish=wait_for_finish, **kw) | def refresh(self, timeout=3, wait_for_finish=False, **kw) | Refresh existing policy on specified device. This is an asynchronous
call that will return a 'follower' link that can be queried to
determine the status of the task.
::
poller = engine.refresh()
while not poller.done():
poller.wait(5)
prin... | 3.75216 | 5.018571 | 0.747655 |
try:
self.make_request(
EngineCommandFailed,
resource='generate_snapshot',
filename=filename)
except IOError as e:
raise EngineCommandFailed(
'Generate snapshot failed: {}'.format(e)) | def generate_snapshot(self, filename='snapshot.zip') | Generate and retrieve a policy snapshot from the engine
This is blocking as file is downloaded
:param str filename: name of file to save file to, including directory
path
:raises EngineCommandFailed: snapshot failed, possibly invalid filename
specified
:return: N... | 8.955883 | 6.077822 | 1.473535 |
site_elements = site_elements if site_elements else []
return self.sites.create(
name, site_elements) | def add_site(self, name, site_elements=None) | Add a VPN site with site elements to this engine.
VPN sites identify the sites with protected networks
to be included in the VPN.
Add a network and new VPN site::
>>> net = Network.get_or_create(name='wireless', ipv4_network='192.168.5.0/24')
>>> engine.vpn.add_s... | 4.270037 | 8.129217 | 0.52527 |
return GatewayCertificate._create(self, common_name, public_key_algorithm,
signature_algorithm, key_length, signing_ca) | def generate_certificate(self, common_name, public_key_algorithm='rsa',
signature_algorithm='rsa_sha_512', key_length=2048,
signing_ca=None) | Generate an internal gateway certificate used for VPN on this engine.
Certificate request should be an instance of VPNCertificate.
:param: str common_name: common name for certificate
:param str public_key_algorithm: public key type to use. Valid values
rsa, dsa, ecdsa.
:par... | 3.42475 | 3.688551 | 0.928481 |
allocated_domain = domain_helper(domain)
json = {'name': name,
'connection_limit': connection_limit,
'show_master_nic': show_master_nic,
'vfw_id': vfw_id,
'comment': comment,
'allocated_domain_ref': allocated_domain... | def create(self, name, vfw_id, domain='Shared Domain',
show_master_nic=False, connection_limit=0, comment=None) | Create a new virtual resource. Called through engine
reference::
engine.virtual_resource.create(....)
:param str name: name of virtual resource
:param int vfw_id: virtual fw identifier
:param str domain: name of domain to install, (default Shared)
:param bool show_m... | 3.587667 | 4.360937 | 0.822683 |
agent = element_resolver(snmp_agent)
snmp_interface = [] if not snmp_interface else snmp_interface
interfaces = self._iface_dict(snmp_interface)
self.engine.data.update(
snmp_agent_ref=agent,
snmp_location=snmp_location if snmp_location else '',
... | def enable(self, snmp_agent, snmp_location=None, snmp_interface=None) | Enable SNMP on the engine. Specify a list of interfaces
by ID to enable only on those interfaces. Only interfaces
that have NDI's are supported.
:param str,Element snmp_agent: the SNMP agent reference for this engine
:param str snmp_location: the SNMP location identifier for the... | 5.373052 | 4.496572 | 1.194922 |
updated = False
if 'snmp_agent' in kwargs:
kwargs.update(snmp_agent_ref=kwargs.pop('snmp_agent'))
snmp_interface = kwargs.pop('snmp_interface', None)
for name, value in kwargs.items():
_value = element_resolver(value)
if getattr(self.engine, n... | def update_configuration(self, **kwargs) | Update the SNMP configuration using any kwargs supported in the
`enable` constructor. Return whether a change was made. You must call
update on the engine to commit any changes.
:param dict kwargs: keyword arguments supported by enable constructor
:rtype: bool | 3.410241 | 3.236501 | 1.053682 |
nics = set([nic.get('nicid') for nic in \
getattr(self.engine, 'snmp_interface', [])])
return [self.engine.interface.get(nic) for nic in nics] | def interface(self) | Return a list of physical interfaces that the SNMP
agent is bound to.
:rtype: list(PhysicalInterface) | 8.087037 | 7.458963 | 1.084204 |
if not dns_relay_profile: # Use default
href = DNSRelayProfile('Cache Only').href
else:
href = element_resolver(dns_relay_profile)
intf = self.engine.interface.get(interface_id)
self.engine.data.update(dns_relay_profile_ref=href)
self.e... | def enable(self, interface_id, dns_relay_profile=None) | Enable the DNS Relay service on this engine.
:param int interface_id: interface id to enable relay
:param str,DNSRelayProfile dns_relay_profile: DNSRelayProfile element
or str href
:raises EngineCommandFailed: interface not found
:raises ElementNotFound: profile not found
... | 7.596998 | 6.62424 | 1.146848 |
self.engine.data.update(dns_relay_interface=[])
self.engine.data.pop('dns_relay_profile_ref', None) | def disable(self) | Disable DNS Relay on this engine
:return: None | 16.957819 | 10.08882 | 1.680853 |
removables = []
for value in values:
if value in self:
removables.append(value)
if removables:
self.entries[:] = [entry._asdict() for entry in self
if entry.value not in removables and not entry.element in removables]
... | def remove(self, values) | Remove DNS entries from this ranked DNS list. A DNS entry can be either
a raw IP Address, or an element of type :class:`smc.elements.network.Host`
or :class:`smc.elements.servers.DNSServer`.
:param list values: list of IP addresses, Host and/or DNSServer elements.
:return: None | 5.595829 | 5.845032 | 0.957365 |
if hasattr(policy, 'href'):
if not isinstance(policy, InterfacePolicy):
raise LoadPolicyFailed('Invalid policy type specified. The policy'
'type must be InterfacePolicy')
self.update(l2_interface_policy_ref=element_resolver(policy... | def enable(self, policy) | Set a layer 2 interface policy.
:param str,Element policy: an InterfacePolicy or str href
:raises LoadPolicyFailed: Invalid policy specified
:raises ElementNotFound: InterfacePolicy not found
:return: None | 14.540562 | 7.356109 | 1.976665 |
try:
if cls.typeof == 'ips_template_policy' and template is None:
fw_template = None
else:
fw_template = IPSTemplatePolicy(template).href
except ElementNotFound:
raise LoadPolicyFailed(
'Cannot find specified fi... | def create(cls, name, template='High-Security IPS Template') | Create an IPS Policy
:param str name: Name of policy
:param str template: name of template
:raises CreatePolicyFailed: policy failed to create
:return: IPSPolicy | 5.810293 | 5.398745 | 1.07623 |
if self:
if args:
index = args[0]
if index <= len(self) -1:
return self[args[0]]
return None
elif kwargs:
key, value = kwargs.popitem()
for item in self.items:
... | def get(self, *args, **kwargs) | Get an element from the iterable by an arg or kwarg.
Args can be a single positional argument that is an index
value to retrieve. If the specified index is out of range,
None is returned. Otherwise use kwargs to provide a key/value.
The key is expected to be a valid attribute of the ite... | 4.083601 | 3.545632 | 1.151727 |
location = list(IPList.objects.filter(name))
if location:
iplist = location[0]
return iplist.upload(filename=filename) | def upload_as_zip(name, filename) | Upload an IPList as a zip file. Useful when IPList is very large.
This is the default upload format for IPLists.
:param str name: name of IPList
:param str filename: name of zip file to upload, full path
:return: None | 9.282898 | 6.925201 | 1.340452 |
location = list(IPList.objects.filter(name))
if location:
iplist = location[0]
return iplist.upload(filename=filename, as_type='txt') | def upload_as_text(name, filename) | Upload the IPList as text from a file.
:param str name: name of IPList
:param str filename: name of text file to upload
:return: None | 9.055918 | 7.496628 | 1.207999 |
location = list(IPList.objects.filter(name))
if location:
iplist = location[0]
return iplist.upload(json=mylist, as_type='json') | def upload_as_json(name, mylist) | Upload the IPList as json payload.
:param str name: name of IPList
:param list: list of IPList entries
:return: None | 9.226109 | 7.913745 | 1.165833 |
location = list(IPList.objects.filter(name))
if location:
iplist = location[0]
return iplist.download(filename=filename) | def download_as_zip(name, filename) | Download IPList with zip compression. Recommended for IPLists
of larger sizes. This is the default format for downloading
IPLists.
:param str name: name of IPList
:param str filename: name of filename for IPList | 9.167411 | 8.750958 | 1.047589 |
location = list(IPList.objects.filter(name))
if location:
iplist = location[0]
return iplist.download(filename=filename, as_type='txt') | def download_as_text(name, filename) | Download IPList as text to specified filename.
:param str name: name of IPList
:param str filename: name of file for IPList download | 8.657899 | 8.751185 | 0.98934 |
location = list(IPList.objects.filter(name))
if location:
iplist = location[0]
return iplist.download(as_type='json') | def download_as_json(name) | Download IPList as json. This would allow for easily
manipulation of the IPList, but generally recommended only for
smaller lists
:param str name: name of IPList
:return: None | 10.536965 | 8.486397 | 1.24163 |
iplist = IPList.create(name=name, iplist=iplist)
return iplist | def create_iplist_with_data(name, iplist) | Create an IPList with initial list contents.
:param str name: name of IPList
:param list iplist: list of IPList IP's, networks, etc
:return: href of list location | 3.237847 | 6.145429 | 0.526871 |
ospf_profile = element_resolver(ospf_profile) if ospf_profile \
else OSPFProfile('Default OSPFv2 Profile').href
self.data.update(
enabled=True,
ospfv2_profile_ref=ospf_profile,
router_id=router_id) | def enable(self, ospf_profile=None, router_id=None) | Enable OSPF on this engine. For master engines, enable
OSPF on the virtual firewall.
Once enabled on the engine, add an OSPF area to an interface::
engine.dynamic_routing.ospf.enable()
interface = engine.routing.get(0)
interface.add_ospf_area(OSPFArea('myarea'))
... | 5.190251 | 5.268388 | 0.985169 |
updated = False
if 'ospf_profile' in kwargs:
kwargs.update(ospfv2_profile_ref=kwargs.pop('ospf_profile'))
for name, value in kwargs.items():
_value = element_resolver(value)
if self.data.get(name) != _value:
self.data[name] = _value
... | def update_configuration(self, **kwargs) | Update the OSPF configuration using kwargs that match the
`enable` constructor.
:param dict kwargs: keyword arguments matching enable constructor.
:return: whether change was made
:rtype: bool | 3.851666 | 3.673464 | 1.048511 |
interface_settings_ref = element_resolver(interface_settings_ref) or \
OSPFInterfaceSetting('Default OSPFv2 Interface Settings').href
if 'inbound_filters_ref' in kwargs:
inbound_filters = kwargs.get('inbound_filters_ref')
if 'outbound_filters_re... | def create(cls, name, interface_settings_ref=None, area_id=1,
area_type='normal', outbound_filters=None,
inbound_filters=None, shortcut_capable_area=False,
ospfv2_virtual_links_endpoints_container=None,
ospf_abr_substitute_container=None, comment=None, **kwarg... | Create a new OSPF Area
:param str name: name of OSPFArea configuration
:param str,OSPFInterfaceSetting interface_settings_ref: an OSPFInterfaceSetting
element or href. If None, uses the default system profile
:param str name: area id
:param str area_type: \|normal\|stub\|not... | 2.035613 | 1.937359 | 1.050716 |
json = {'name': name,
'authentication_type': authentication_type,
'password': password,
'key_chain_ref': element_resolver(key_chain_ref),
'dead_interval': dead_interval,
'dead_multiplier': dead_multiplier,
'... | def create(cls, name, dead_interval=40, hello_interval=10,
hello_interval_type='normal', dead_multiplier=1,
mtu_mismatch_detection=True, retransmit_interval=5,
router_priority=1, transmit_delay=1,
authentication_type=None, password=None,
key_cha... | Create custom OSPF interface settings profile
:param str name: name of interface settings
:param int dead_interval: in seconds
:param str hello_interval: in seconds
:param str hello_interval_type: \|normal\|fast_hello
:param int dead_multipler: fast hello packet multipler
... | 1.663355 | 1.756829 | 0.946794 |
key_chain_entry = key_chain_entry or []
json = {'name': name,
'ospfv2_key_chain_entry': key_chain_entry}
return ElementCreator(cls, json) | def create(cls, name, key_chain_entry) | Create a key chain with list of keys
Key_chain_entry format is::
[{'key': 'xxxx', 'key_id': 1-255, 'send_key': True|False}]
:param str name: Name of key chain
:param list key_chain_entry: list of key chain entries
:raises CreateElementFailed: create failed with reason
... | 5.337407 | 5.869153 | 0.9094 |
json = {'name': name,
'external_distance': external_distance,
'inter_distance': inter_distance,
'intra_distance': intra_distance,
'default_metric': default_metric,
'comment': comment}
if redistribution_entr... | def create(cls, name, domain_settings_ref=None, external_distance=110,
inter_distance=110, intra_distance=110, redistribution_entry=None,
default_metric=None, comment=None) | Create an OSPF Profile.
If providing a list of redistribution entries, provide in the following
dict format:
{'enabled': boolean, 'metric_type': 'external_1' or 'external_2',
'metric': 2, 'type': 'kernel'}
Valid types for redistribution entries are: k... | 3.154064 | 2.759446 | 1.143007 |
json = {'name': name,
'abr_type': abr_type,
'auto_cost_bandwidth': auto_cost_bandwidth,
'deprecated_algorithm': deprecated_algorithm,
'initial_delay': initial_delay,
'initial_hold_time': initial_hold_time,
'... | def create(cls, name, abr_type='cisco', auto_cost_bandwidth=100,
deprecated_algorithm=False, initial_delay=200,
initial_hold_time=1000, max_hold_time=10000,
shutdown_max_metric_lsa=0, startup_max_metric_lsa=0) | Create custom Domain Settings
Domain settings are referenced by an OSPFProfile
:param str name: name of custom domain settings
:param str abr_type: cisco|shortcut|standard
:param int auto_cost_bandwidth: Mbits/s
:param bool deprecated_algorithm: RFC 1518 compatibility
:... | 1.384249 | 1.5253 | 0.907526 |
@functools.wraps(function)
def run(cls, json, **kwargs):
if hasattr(cls, '_create_hook'):
json = cls._create_hook(json)
return function(cls, json, **kwargs)
return run | def create_hook(function) | Provide a pre-filter to the create function that provides the ability
to modify the element json before submitting to the SMC. To register
a create hook, set on the class or top level Element class to enable
this on any descendent of Element::
Element._create_hook = classmethod(myhook)
... | 3.141532 | 2.632295 | 1.193457 |
@functools.wraps(function)
def wrapper(*exception, **kwargs):
result = function(**kwargs)
if exception:
result.exception = exception[0]
return result
return wrapper | def exception(function) | If exception was specified for prepared_request,
inject this into SMCRequest so it can be used for
return if needed. | 3.517857 | 3.240525 | 1.085582 |
snmp_interface = []
if interfaces: # Not providing interfaces will enable SNMP on all NDIs
interfaces = map(str, interfaces)
for interface in data:
interface_id = str(interface.get('interface_id'))
for if_def in interface.get('interfaces', []):
_inter... | def add_snmp(data, interfaces) | Format data for adding SNMP to an engine.
:param list data: list of interfaces as provided by kw
:param list interfaces: interfaces to enable SNMP by id | 3.58042 | 3.607158 | 0.992587 |
physical_interfaces = []
for interface in interfaces:
if 'interface_id' not in interface:
raise CreateEngineFailed('Interface definitions must contain the interface_id '
'field. Failed to create engine: %s' % name)
if interface.get('ty... | def create_bulk(cls, name, interfaces=None,
primary_mgt=None, backup_mgt=None,
log_server_ref=None,
domain_server_address=None,
location_ref=None, default_nat=False,
enable_antivirus=False, enable_gti=False,
... | Create a Layer 3 Firewall providing all of the interface configuration.
This method provides a way to fully create the engine and all interfaces
at once versus using :py:meth:`~create` and creating each individual
interface after the engine exists.
Example interfaces format::
... | 3.101679 | 2.802663 | 1.10669 |
interfaces = kw.pop('interfaces', [])
# Add the primary interface to the interface list
interface = {'interface_id': mgmt_interface,
'interface': 'single_node_interface',
'zone_ref': zone_ref,
'interfaces': [{
... | def create(cls, name, mgmt_ip, mgmt_network,
mgmt_interface=0,
log_server_ref=None,
default_nat=False,
reverse_connection=False,
domain_server_address=None, zone_ref=None,
enable_antivirus=False, enable_gti=False,
l... | Create a single layer 3 firewall with management interface and DNS.
Provide the `interfaces` keyword argument if adding multiple additional interfaces.
Interfaces can be one of any valid interface for a layer 3 firewall. Unless the
interface type is specified, physical_interface is assumed.
... | 3.059905 | 3.00359 | 1.018749 |
interfaces = kw.pop('interfaces', [])
# Add the primary interface to the interface list
interface = {'interface_id': interface_id,
'interface': 'single_node_interface',
'zone_ref': zone_ref,
'interfaces': [{
... | def create_dynamic(cls, name, interface_id,
dynamic_index=1,
reverse_connection=True,
automatic_default_route=True,
domain_server_address=None,
loopback_ndi='127.0.0.1',
location_ref... | Create a single layer 3 firewall with only a single DHCP interface. Useful
when creating virtualized FW's such as in Microsoft Azure.
:param str name: name of engine
:param str,int interface_id: interface ID used for dynamic interface and management
:param bool reverse_connectio... | 3.294287 | 3.346801 | 0.984309 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.