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="Print additional info + resolved template", action="store_true", default=False)
parser.add_argument("--devel", help="Allow running from branch; don't refresh from origin", action="store_true",
default=False)
group = parser.add_mutually_exclusive_group()
group.add_argument("--changeset", help="create a changeset; cannot be combined with --commit",
action="store_true", default=False)
group.add_argument("--commit", help="Make changes in AWS (dry run if omitted); cannot be combined with --changeset",
action="store_true", default=False)
group.add_argument("--lint", help="Execute cfn-lint on the rendered template", action="store_true",
default=False)
parser.add_argument("--percent", help="Specifies an override to the percentage of instances in an Auto Scaling rolling update (e.g. 10 for 10%%)",
type=int, default=False)
parser.add_argument("--poll", help="Poll Cloudformation to check status of stack creation/updates",
action="store_true", default=False)
parsed_args = vars(parser.parse_args(args))
context = EFCFContext()
try:
context.env = parsed_args["env"]
context.template_file = parsed_args["template_file"]
except ValueError as e:
fail("Error in argument: {}".format(e.message))
context.changeset = parsed_args["changeset"]
context.commit = parsed_args["commit"]
context.devel = parsed_args["devel"]
context.lint = parsed_args["lint"]
context.percent = parsed_args["percent"]
context.poll_status = parsed_args["poll"]
context.verbose = parsed_args["verbose"]
# Set up service registry and policy template path which depends on it
context.service_registry = EFServiceRegistry(parsed_args["sr"])
return context | 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_REPO_BRANCH
CalledProcessError: if 'git rev-parse' command to find repo root could not be run | 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_info)
environment = EFConfig.VAGRANT_ENV
resolver = EFTemplateResolver(env=environment, profile=get_account_alias(environment),
region=EFConfig.DEFAULT_REGION, service=service)
while config_reader.next():
log_info("checking: {}".format(config_reader.current_key))
# if 'dest' for the current object contains an 'environments' list, check it
dest = config_reader.dest
if "environments" in dest:
if not resolver.resolved["ENV_SHORT"] in dest["environments"]:
log_info("Environment: {} not enabled for {}".format(
resolver.resolved["ENV_SHORT"], config_reader.current_key)
)
continue
# If 'dest' for the current object contains a user_group that hasn't been created in the environment yet and the
# flag is set to True to skip, log the error and move onto the next config file without blowing up.
if skip_on_user_group_error:
user, group = get_user_group(dest)
try:
getpwnam(user).pw_uid
except KeyError:
log_info("File specifies user {} that doesn't exist in environment. Skipping config file.".format(user))
continue
try:
getgrnam(group).gr_gid
except KeyError:
log_info("File specifies group {} that doesn't exist in environment. Skipping config file.".format(group))
continue
# Process the template_body - apply context + parameters
log_info("Resolving template")
resolver.load(config_reader.template, config_reader.parameters)
rendered_body = resolver.render()
if not resolver.resolved_ok():
critical("Couldn't resolve all symbols; template has leftover {{ or }}: {}".format(resolver.unresolved_symbols()))
# Write the rendered file
dir_path = normpath(dirname(dest["path"]))
# Resolved OK. try to write the template
log_info("make directories: {} {}".format(dir_path, dest["dir_perm"]))
try:
makedirs(dir_path, int(dest["dir_perm"], 8))
except OSError as error:
if error.errno != 17:
critical("Error making directories {}".format(repr(error)))
log_info("open: " + dest["path"] + ",w+")
try:
outfile = open(dest["path"], 'w+')
log_info("write")
outfile.write(rendered_body)
log_info("close")
outfile.close()
log_info("chmod file to: " + dest["file_perm"])
chmod(dest["path"], int(dest["file_perm"], 8))
user, group = get_user_group(dest)
uid = getpwnam(user).pw_uid
gid = getgrnam(group).gr_gid
log_info("chown last directory in path to: " + dest["user_group"])
chown(dir_path, uid, gid)
log_info("chown file to: " + dest["user_group"])
chown(dest["path"], uid, gid)
except Exception as error:
critical("Error writing file: " + dest["path"] + ": " + repr(error)) | 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>/parameters/<filename>.parameters.<yaml|yml|json>
For filesystem, full path becomes:
/vagrant/configs/<service>/templates/<filename>
/vagrant/configs/<service>/parameters/<filename>.parameters.<yaml|yml|json> | 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("Unknown type loading template; expected string or file: " + type(template))
# load parameters, if any
if parameters:
if isinstance(parameters, str):
try:
self.parameters = yaml.safe_load(parameters)
except ValueError as error:
fail("Exception loading parameters from string: ", error)
elif isinstance(parameters, file):
try:
self.parameters = yaml.safe_load(parameters)
parameters.close()
except ValueError as error:
fail("Exception loading parameters from file: {}".format(error), sys.exc_info())
elif isinstance(parameters, dict):
self.parameters = parameters
else:
fail("Unknown type loading parameters; expected string, file, or dict: " + type(parameters))
# sanity check the loaded parameters
if "params" not in self.parameters:
fail("'params' field not found in parameters")
# just the params, please
self.parameters = self.parameters["params"]
# are all the keys valid (must have legal characters)
for k in set().union(*(self.parameters[d].keys() for d in self.parameters.keys())):
invalid_char = re.search(ILLEGAL_PARAMETER_CHARS, k)
if invalid_char:
fail("illegal character: '" + invalid_char.group(0) + "' in parameter key: " + k) | 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'
Whether from a string or file, or already in a dictionary, parameters must follow the
logical format documented in the class docstring.
if 'parameters' is omitted, template resolution will proceed with AWS, credential, and
version lookups. | 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.resolved["ENV_SHORT"]]:
result = self.parameters[self.resolved["ENV_SHORT"]][symbol]
# This lookup is redundant when env_short == env, but it's also cheap
if self.resolved["ENV"] in self.parameters and symbol in self.parameters[self.resolved["ENV"]]:
result = self.parameters[self.resolved["ENV"]][symbol]
return result | 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 resolved in a pass, stop
# Gather all resolvable symbols in the template
template_symbols = set(re.findall(SYMBOL_PATTERN, self.template))
self.symbols.update(template_symbols) # include this pass's symbols in full set
# resolve and replace symbols
for symbol in template_symbols:
resolved_symbol = None
# Lookups in AWS, only if we have an EFAwsResolver
if symbol[:4] == "aws:" and EFTemplateResolver.__AWSR:
resolved_symbol = EFTemplateResolver.__AWSR.lookup(symbol[4:])
# Lookups in credentials
elif symbol[:12] == "credentials:":
pass #TODO
elif symbol[:9] == "efconfig:":
resolved_symbol = EFTemplateResolver.__EFCR.lookup(symbol[9:])
elif symbol[:8] == "version:":
resolved_symbol = EFTemplateResolver.__VR.lookup(symbol[8:])
if not resolved_symbol:
print("WARNING: Lookup failed for {{%s}} - placeholder value of 'NONE' used in rendered template" % symbol)
resolved_symbol = "NONE"
else:
# 1. context - these are already in the resolved table
# self.resolved[symbol] may have value=None; use has_key tell "resolved w/value=None" from "not resolved"
# these may be "global" symbols such like "ENV", "ACCOUNT", etc.
if symbol in self.resolved:
resolved_symbol = self.resolved[symbol]
# 2. parameters
if not resolved_symbol:
resolved_symbol = self.search_parameters(symbol)
# if symbol was resolved, replace it everywhere
if resolved_symbol is not None:
if isinstance(resolved_symbol, list):
self.template = self.template.replace("{{" + symbol + "}}", "\n".join(resolved_symbol))
else:
self.template = self.template.replace("{{" + symbol + "}}", resolved_symbol)
go_again = True
return self.template | 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 registry for versioned content such as an AMI ID
- 4. built-in context (such as "ENV")
- 5. parameters from a parameter file / dictionary of params | 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("--verbose", help="Output extra info", action="store_true", default=False)
parser.add_argument("--lint", help="Test configs for valid JSON/YAML syntax", action="store_true", default=False)
parser.add_argument("--silent", help="Suppress output of rendered template", action="store_true", default=False)
parsed = vars(parser.parse_args(args))
path_to_template = abspath(parsed["path_to_template"])
service = path_to_template.split('/')[-3]
return Context(
get_account_alias(parsed["env"]),
EFConfig.DEFAULT_REGION,
parsed["env"],
service,
path_to_template,
parsed["no_params"],
parsed["verbose"],
parsed["lint"],
parsed["silent"]
) | 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 template file: {} {}".format(context.template_path, repr(error)))
if context.no_params is False:
try:
with open(context.param_path, 'r') as f:
param_body = f.read()
f.close()
except IOError as error:
raise IOError("Error loading param file: {} {}".format(context.param_path, repr(error)))
dest = yaml.safe_load(param_body)["dest"]
# if 'dest' for the current object contains an 'environments' list, check it
if "environments" in dest:
if not resolver.resolved["ENV_SHORT"] in dest["environments"]:
print("Environment: {} not enabled for {}".format(resolver.resolved["ENV_SHORT"], context.template_path))
return
# Process the template_body - apply context + parameters
resolver.load(template_body, param_body)
else:
resolver.load(template_body)
rendered_body = resolver.render()
if not resolver.resolved_ok():
raise RuntimeError("Couldn't resolve all symbols; template has leftover {{ or }}: {}".format(resolver.unresolved_symbols()))
if context.lint:
if context.template_path.endswith(".json"):
try:
json.loads(rendered_body, strict=False)
print("JSON passed linting process.")
except ValueError as e:
fail("JSON failed linting process.", e)
elif context.template_path.endswith((".yml", ".yaml")):
conf = yamllint_config.YamlLintConfig(content='extends: relaxed')
lint_output = yamllinter.run(rendered_body, conf)
lint_level = 'error'
lint_errors = [issue for issue in lint_output if issue.level == lint_level]
if lint_errors:
split_body = rendered_body.splitlines()
for error in lint_errors:
print(error)
# printing line - 1 because lists start at 0, but files at 1
print("\t", split_body[error.line - 1])
fail("YAML failed linting process.")
if context.verbose:
print(context)
if context.no_params:
print('no_params flag set to true!')
print('Inline template resolution based on external symbol lookup only and no destination for file write.\n')
else:
dir_path = normpath(dirname(dest["path"]))
print("make directories: {} {}".format(dir_path, dest["dir_perm"]))
print("chmod file to: " + dest["file_perm"])
user, group = dest["user_group"].split(":")
print("chown last directory in path to user: {}, group: {}".format(user, group))
print("chown file to user: {}, group: {}\n".format(user, group))
print("template body:\n{}\nrendered body:\n{}\n".format(template_body, rendered_body))
elif context.silent:
print("Config template rendered successfully.")
else:
print(rendered_body) | 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))
# If a config path wasn't given, calculate it based on location of the script
if parsed_args["configpath"] is None:
script_dir = os.path.abspath(os.path.dirname(sys.argv[0]))
parsed_args["configpath"] = os.path.normpath("{}/{}".format(script_dir, CONFIGS_RELATIVE_PATH_FROM_SCRIPT_DIR))
else:
parsed_args["configpath"] = os.path.normpath(parsed_args["configpath"])
# If the path is a directory, all good. if it's a file, find the directory the file is in and check that instead
if os.path.isdir(parsed_args["configpath"]):
parsed_args["configdir"] = parsed_args["configpath"]
else:
parsed_args["configdir"] = os.path.dirname(parsed_args["configpath"])
return parsed_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, service. {}".format(envservice, e.message))
return self._s3_get(env, service, key) | 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_policy.json()['policy']['id']
self.refresh_all_alerts()
return policy_id | 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, else None | 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, name, type) if found, otherwise None | 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
:return: str value of attribute | 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_elements_by_type('host')
:param name: top level entry point name
:raises: `smc.api.exceptions.UnsupportedEntryPoint`
:return: list with json representation of name match, else None | 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_timer_max,
'certificate_cache_crl_validity': certificate_cache_crl_validity,
'mobike_after_sa_update': mobike_after_sa_update,
'mobike_before_sa_update': mobike_before_sa_update,
'mobike_no_rrc': mobike_no_rrc}
return ElementCreator(cls, json) | 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_sa_update=False,
mobike_no_rrc=True) | 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_timer_max: maximum length for retry (ms)
:param int certificate_cache_crl_validity: cert cache validity (seconds)
:param boolean mobike_after_sa_update: Whether the After SA flag is set
for Mobike Policy
:param boolean mobike_before_sa_update: Whether the Before SA flag is
set for Mobike Policy
:param boolean mobike_no_rrc: Whether the No RRC flag is set for
Mobike Policy
:raises CreateElementFailed: failed creating profile
:return: instance with meta
:rtype: GatewaySettings | 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_site:
if 'name' not in site:
raise ValueError('VPN sites are configured but missing '
'the name parameter.')
# Make sure VPN sites are resolvable before continuing
sites = [element_resolver(element, do_raise=True)
for element in site.get('site_element', [])]
site.update(site_element=sites)
updated = False
created = False
try:
extgw = ExternalGateway.get(name)
except ElementNotFound:
extgw = ExternalGateway.create(name, trust_all_cas)
created = True
if external_endpoint:
for endpoint in external_endpoint:
_, modified, was_created = ExternalEndpoint.update_or_create(
extgw, with_status=True, **endpoint)
if was_created or modified:
updated = True
if vpn_site:
for site in vpn_site:
_, modified, was_created = VPNSite.update_or_create(extgw,
name=site['name'], site_element=site.get('site_element'),
with_status=True)
if was_created or modified:
updated = True
if with_status:
return extgw, updated, created
return extgw | 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
pre-existing will not be deleted if not provided in the ``external_endpoint``
parameter, however existing elements will be updated as specified.
:param str name: name of external gateway
:param list(dict) external_endpoint: list of dict items with key/value
to satisfy ExternalEndpoint.create constructor
:param list(dict) vpn_site: list of dict items with key/value to satisfy
VPNSite.create constructor
:param bool with_status: If set to True, returns a 3-tuple of
(ExternalGateway, modified, created), where modified and created
is the boolean status for operations performed.
:raises ValueError: missing required argument/s for constructor argument
:rtype: ExternalGateway | 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}
if dynamic:
json.pop('address')
json.update(
ike_phase1_id_type=ike_phase1_id_type,
ike_phase1_id_value=ike_phase1_id_value)
return ElementCreator(
self.__class__,
href=self.href,
json=json) | 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
:param str address: address of remote host
:param bool enabled: True|False (default: True)
:param str balancing_mode: active
:param bool ipsec_vpn: True|False (default: True)
:param bool nat_t: True|False (default: False)
:param bool force_nat_t: True|False (default: False)
:param bool dynamic: is a dynamic VPN (default: False)
:param int ike_phase1_id_type: If using a dynamic endpoint, you must
set this value. Valid options: 0=DNS name, 1=Email, 2=DN, 3=IP Address
:param str ike_phase1_id_value: value of ike_phase1_id. Required if
ike_phase1_id_type and dynamic set.
:raises CreateElementFailed: create element with reason
:return: newly created element
:rtype: ExternalEndpoint | 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
if external_endpoint: # Check for changes
for name, value in kw.items(): # Check for differences before updating
if getattr(external_endpoint, name, None) != value:
external_endpoint.data[name] = value
updated = True
if updated:
external_endpoint.update()
else:
external_endpoint = external_gateway.external_endpoint.create(
name, **kw)
created = True
if with_status:
return external_endpoint, updated, created
return external_endpoint | 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.
:param ExternalGateway external_gateway: external gateway reference
:param str name: name of the ExternalEndpoint. This is only used as
a direct match if the endpoint is dynamic. Otherwise the address
field in the keyword arguments will be used as you cannot add
multiple external endpoints with the same IP address.
:param bool with_status: If set to True, returns a 3-tuple of
(ExternalEndpoint, modified, created), where modified and created
is the boolean status for operations performed.
:param dict kw: keyword arguments to satisfy ExternalEndpoint.create
constructor
:raises CreateElementFailed: Failed to create external endpoint with reason
:raises ElementNotFound: If specified ExternalGateway is not valid
:return: if with_status=True, return tuple(ExternalEndpoint, created). Otherwise
return only ExternalEndpoint. | 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
:rtype: str | 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 set(site_elements) != set(vpn_site.data.get('site_element', [])):
vpn_site.data['site_element'] = site_elements
vpn_site.update()
updated = True
else:
vpn_site = external_gateway.vpn_site.create(
name=name, site_element=site_elements)
created = True
if with_status:
return vpn_site, updated, created
return vpn_site | 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 external_gateway: The external gateway for
this VPN site
:param str name: name of the VPN site
:param list(str,Element) site_element: list of resolved Elements to
add to the VPN site
:param bool with_status: If set to True, returns a 3-tuple of
(VPNSite, modified, created), where modified and created
is the boolean status for operations performed.
:raises ElementNotFound: ExternalGateway or unresolved site_element | 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 versions.
if name is not None:
locations = [location for location in Search.objects.entry_point(
'location') if location.name == name]
if not locations:
return Location.create(name=name).href if not search_only \
else None
return locations[0].href | 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 will set it to the Default location.
:param bool search_only: only search for the location, if not found
do not create
:return str href: href of location if search_only is not False
:rtype: str or None | 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 default unless specific domain provided. Change is committed
at end of method call.
:param permission: permission/s to add to admin user
:type permission: list(Permission)
:raises UpdateElementFailed: failed updating admin user
:return: None | 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,
'engine_target': engines,
'local_admin': local_admin,
'superuser': superuser,
'can_use_api': can_use_api,
'comment': comment}
return ElementCreator(cls, json) | 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: allow sudo on engines
:param bool can_use_api: can log in to SMC API
:param bool console_superuser: can this user sudo via SSH/console
:param bool allowed_to_login_in_shared: can this user log in to the
shared domain
:param bool superuser: is a super administrator
:param bool enabled: is account enabled
:param list engine_target: engine to allow remote access to
:raises CreateElementFailed: failure creating element with reason
:return: instance with meta
:rtype: AdminUser | 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
:param bool enabled: enable client
:param bool superuser: is superuser account
:raises CreateElementFailed: failure creating element with reason
:return: instance with meta
:rtype: ApiClient | 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:
for num, server in enumerate(domain_server_address):
try:
domain_server = {'rank': num, 'ne_ref' : server.href}
except AttributeError:
domain_server = {'rank': num, 'value': server}
domain_server_list.append(domain_server)
# Set log server reference, if not explicitly provided
if not log_server_ref and node_type is not 'virtual_fw_node':
log_server_ref = LogServer.objects.first().href
base_cfg = {
'name': name,
'nodes': node_list,
'domain_server_address': domain_server_list,
'log_server_ref': log_server_ref,
'physicalInterfaces': physical_interfaces}
if enable_antivirus:
antivirus = {
'antivirus': {
'antivirus_enabled': True,
'antivirus_update': 'daily',
'virus_log_level': 'stored',
'virus_mirror': 'update.nai.com/Products/CommonUpdater'}}
base_cfg.update(antivirus)
if enable_gti:
gti = {'gti_settings': {
'file_reputation_context': 'gti_cloud_only'}}
base_cfg.update(gti)
if sidewinder_proxy_enabled:
base_cfg.update(sidewinder_proxy_enabled=True)
if default_nat:
base_cfg.update(default_nat=True)
if location_ref:
base_cfg.update(location_ref=location_helper(location_ref) \
if location_ref else None)
if snmp_agent:
snmp_agent_ref = SNMPAgent(snmp_agent.pop('snmp_agent_ref')).href
base_cfg.update(
snmp_agent_ref=snmp_agent_ref,
**snmp_agent)
if enable_ospf:
if not ospf_profile: # get default profile
ospf_profile = OSPFProfile('Default OSPFv2 Profile').href
ospf = {'dynamic_routing': {
'ospfv2': {
'enabled': True,
'ospfv2_profile_ref': ospf_profile}
}}
base_cfg.update(ospf)
base_cfg.update(comment=comment)
return base_cfg | 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,
default_nat=False, location_ref=None,
enable_ospf=None, ospf_profile=None, snmp_agent=None,
comment=None) | 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
:param str node_type: comes from class attribute of engine type
:param dict physical_interfaces: physical interface list of dict
:param int nodes: number of nodes for engine
:param str log_server_ref: href of log server
:param list domain_server_address: dns addresses | 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 UpdateElementFailed: failure to update element
:return: Location element or None | 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)
:return: nodes for this engine
:rtype: SubElementCollection(Node) | 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='permissions')
for acl in acls['granted_access_control_list']:
yield(acl_map(acl)) | 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)
AccessControlList(name=ALL Firewalls)
:raises UnsupportedEngineFeature: requires SMC version >= 6.1
:return: access control list permissions
:rtype: list(AccessControlList) | 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)
...
(Alias(name=$$ Interface ID 0.ip), [u'10.10.0.1'])
(Alias(name=$$ Interface ID 0.net), [u'10.10.0.0/24'])
(Alias(name=$$ Interface ID 1.ip), [u'10.10.10.1'])
:return: generator of aliases
:rtype: Alias | 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 Blacklist: pre-configured blacklist entries
.. note:: This method requires SMC version >= 6.4 | 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
need more granular controls over the blacklist such as filtering by
source and destination address, use the smc-python-monitoring
package directly.
Blacklist entries that are returned from this generator have a
delete() method that can be called to simplify removing entries.
A simple query would look like::
for bl_entry in engine.blacklist_show():
print(bl_entry)
:param kw: keyword arguments passed to blacklist query. Common setting
is to pass max_recv=20, which specifies how many "receive" batches
will be retrieved from the SMC for the query. At most, 200 results
can be returned in a single query. If max_recv=5, then 1000 results
can be returned if they exist. If less than 1000 events are available,
the call will be blocking until 5 receives has been reached.
:return: generator of results
:rtype: :class:`smc_monitoring.monitors.blacklist.BlacklistEntry` | 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 interface
:param str network: network address in cidr format
:raises EngineCommandFailed: invalid route, possibly no network
:return: None | 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.routing_monitoring:
... route
...
Route(route_network=u'0.0.0.0', route_netmask=0, route_gateway=u'10.0.0.1', route_type=u'Static', dst_if=1, src_if=-1)
...
:raises EngineCommandFailed: routes cannot be retrieved
:return: list of route elements
:rtype: SerializedIterable(Route) | 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 provide an updated cache after modification.
.. seealso:: :class:`smc.core.engine.interface.update_or_create`
:param PhysicalInterface,TunnelInterface interface: instance of
pre-created interface
:return: None | 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)
print('Percentage complete {}%'.format(poller.task.progress))
:param int timeout: timeout between queries
:raises TaskRunFailed: refresh failed, possibly locked policy
:rtype: TaskOperationPoller | 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: None | 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_site(name='wireless', site_elements=[net])
VPNSite(name=wireless)
>>> list(engine.vpn.sites)
[VPNSite(name=dingo - Primary Site), VPNSite(name=wireless)]
:param str name: name for VPN site
:param list site_elements: network elements for VPN site
:type site_elements: list(str,Element)
:raises ElementNotFound: if site element is not found
:raises UpdateElementFailed: failed to add vpn site
:rtype: VPNSite
.. note:: Update is immediate for this operation. | 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.
: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.
:param str,VPNCertificateCA signing_ca: by default will use the
internal RSA CA
:raises CertificateError: error generating certificate
:return: GatewayCertificate | 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}
return ElementCreator(self.__class__, json=json, href=self.href) | 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_master_nic: whether to show the master engine NIC ID's
in the virtual instance
:param int connection_limit: whether to limit number of connections for
this instance
:return: href of new virtual resource
:rtype: str | 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 '',
snmp_interface=interfaces) | 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 engine
:param list snmp_interface: list of interface IDs to enable SNMP
:raises ElementNotFound: unable to resolve snmp_agent
:raises InterfaceNotFound: specified interface by ID not found | 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, name, None) != _value:
self.engine.data[name] = _value
updated = True
if snmp_interface is not None:
_snmp_interface = getattr(self.engine, 'snmp_interface', [])
if not len(snmp_interface) and len(_snmp_interface):
self.engine.data.update(snmp_interface=[])
updated = True
elif len(snmp_interface):
if set(self._nicids) ^ set(map(str, snmp_interface)):
self.engine.data.update(
snmp_interface=self._iface_dict(snmp_interface))
updated = True
return updated | 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.engine.data.update(dns_relay_interface=intf.ndi_interfaces) | 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
:return: None | 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]
# Rerank to maintain order
for i, entry in enumerate(self.entries):
entry.update(rank='{}'.format(i)) | 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 firewall template: {}'.format(template))
json = {
'name': name,
'template': fw_template}
try:
return ElementCreator(cls, json)
except CreateElementFailed as err:
raise CreatePolicyFailed(err) | 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:
if getattr(item, key, None) == value:
return item
else:
raise ValueError('Missing argument. You must provide an '
'arg or kwarg to fetch an element from the collection.') | 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 iterated class.
For example, to get an element that has a attribute name of 'foo',
pass name='foo'.
:raises ValueError: An argument was missing
:return: the specified item, type is based on what is
returned by this iterable, may be None | 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'))
:param str,OSPFProfile ospf_profile: OSPFProfile element or str
href; if None, use default profile
:param str router_id: single IP address router ID
:raises ElementNotFound: OSPF profile not found
:return: None | 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
updated = True
return updated | 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_ref' in kwargs:
outbound_filters = kwargs.get('outbound_filters_ref')
json = {'name': name,
'area_id': area_id,
'area_type': area_type,
'comment': comment,
'inbound_filters_ref': element_resolver(inbound_filters),
'interface_settings_ref': interface_settings_ref,
'ospf_abr_substitute_container': ospf_abr_substitute_container,
'ospfv2_virtual_links_endpoints_container':
ospfv2_virtual_links_endpoints_container,
'outbound_filters_ref': element_resolver(outbound_filters),
'shortcut_capable_area': shortcut_capable_area}
return ElementCreator(cls, json) | 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, **kwargs) | 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_so_stubby\|totally_stubby\|
totally_not_so_stubby
:param list outbound_filters: reference to an IPAccessList and or IPPrefixList.
You can only have one outbound prefix or access list
:param list inbound_filters: reference to an IPAccessList and or IPPrefixList.
You can only have one outbound prefix or access list
:param shortcut_capable_area: True|False
:param list ospfv2_virtual_links_endpoints_container: virtual link endpoints
:param list ospf_abr_substitute_container: substitute types:
\|aggregate\|not_advertise\|substitute_with
:param str comment: optional comment
:raises CreateElementFailed: failed to create with reason
:rtype: OSPFArea | 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,
'hello_interval': hello_interval,
'hello_interval_type': hello_interval_type,
'mtu_mismatch_detection': mtu_mismatch_detection,
'retransmit_interval': retransmit_interval,
'router_priority': router_priority,
'transmit_delay': transmit_delay}
return ElementCreator(cls, json) | 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_chain_ref=None) | 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
:param bool mtu_mismatch_detection: True|False
:param int retransmit_interval: in seconds
:param int router_priority: set priority
:param int transmit_delay: in seconds
:param str authentication_type: \|password\|message_digest
:param str password: max 8 chars (required when
authentication_type='password')
:param str,Element key_chain_ref: OSPFKeyChain (required when
authentication_type='message_digest')
:raises CreateElementFailed: create failed with reason
:return: instance with meta
:rtype: OSPFInterfaceSetting | 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
:return: instance with meta
:rtype: OSPFKeyChain | 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_entry:
json.update(redistribution_entry=
_format_redist_entry(redistribution_entry))
domain_settings_ref = element_resolver(domain_settings_ref) or \
OSPFDomainSetting('Default OSPFv2 Domain Settings').href
json.update(domain_settings_ref=domain_settings_ref)
return ElementCreator(cls, json) | 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: kernel, static, connected, bgp,
and default_originate.
You can also provide a 'filter' key with either an IPAccessList or RouteMap
element to use for further access control on the redistributed route type.
If metric_type is not provided, external_1 (E1) will be used.
An example of a redistribution_entry would be::
{u'enabled': True,
u'metric': 123,
u'metric_type': u'external_2',
u'filter': RouteMap('myroutemap'),
u'type': u'static'}
:param str name: name of profile
:param str,OSPFDomainSetting domain_settings_ref: OSPFDomainSetting
element or href
:param int external_distance: route metric (E1-E2)
:param int inter_distance: routes learned from different areas (O IA)
:param int intra_distance: routes learned from same area (O)
:param list redistribution_entry: how to redistribute the OSPF routes.
:raises CreateElementFailed: create failed with reason
:rtype: OSPFProfile | 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,
'max_hold_time': max_hold_time,
'shutdown_max_metric_lsa': shutdown_max_metric_lsa,
'startup_max_metric_lsa': startup_max_metric_lsa}
return ElementCreator(cls, json) | 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
:param int initial_delay: in milliseconds
:param int initial_hold_type: in milliseconds
:param int max_hold_time: in milliseconds
:param int shutdown_max_metric_lsa: in seconds
:param int startup_max_metric_lsa: in seconds
:raises CreateElementFailed: create failed with reason
:return: instance with meta
:rtype: OSPFDomainSetting | 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)
The hook should be a callable and take two arguments, cls, json and
return the json after modification. For example::
def myhook(cls, json):
print("Called with class: %s" % cls)
if 'address' in json:
json['address'] = '2.2.2.2'
return json | 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', []):
_interface_id = None
if 'vlan_id' in if_def:
_interface_id = '{}.{}'.format(
interface_id, if_def['vlan_id'])
else:
_interface_id = interface_id
if _interface_id in interfaces and 'type' not in interface:
for node in if_def.get('nodes', []):
snmp_interface.append(
{'address': node.get('address'),
'nicid': _interface_id})
return snmp_interface | 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('type', None) == 'tunnel_interface':
tunnel_interface = TunnelInterface(**interface)
physical_interfaces.append(
{'tunnel_interface': tunnel_interface})
else:
interface.update(interface='single_node_interface')
interface = Layer3PhysicalInterface(primary_mgt=primary_mgt,
backup_mgt=backup_mgt, **interface)
physical_interfaces.append(
{'physical_interface': interface})
if snmp:
snmp_agent = dict(
snmp_agent_ref=snmp.get('snmp_agent', ''),
snmp_location=snmp.get('snmp_location', ''))
snmp_agent.update(
snmp_interface=add_snmp(
interfaces,
snmp.get('snmp_interface', [])))
try:
engine = super(Layer3Firewall, cls)._create(
name=name,
node_type='firewall_node',
physical_interfaces=physical_interfaces,
loopback_ndi=kw.get('loopback_ndi', []),
domain_server_address=domain_server_address,
log_server_ref=log_server_ref,
nodes=1, enable_gti=enable_gti,
enable_antivirus=enable_antivirus,
sidewinder_proxy_enabled=sidewinder_proxy_enabled,
default_nat=default_nat,
location_ref=location_ref,
enable_ospf=enable_ospf,
ospf_profile=ospf_profile,
snmp_agent=snmp_agent if snmp else None,
comment=comment)
return ElementCreator(cls, json=engine)
except (ElementNotFound, CreateElementFailed) as e:
raise CreateEngineFailed(e) | 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,
sidewinder_proxy_enabled=False, enable_ospf=False,
ospf_profile=None, comment=None, snmp=None, **kw) | 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::
interfaces=[
{'interface_id': 1},
{'interface_id': 2,
'interfaces':[{'nodes': [{'address': '2.2.2.2', 'network_value': '2.2.2.0/24'}]}],
'zone_ref': 'myzone'},
{'interface_id': 3,
'interfaces': [{'nodes': [{'address': '3.3.3.3', 'network_value': '3.3.3.0/24'}],
'vlan_id': 3,
'zone_ref': 'myzone'},
{'nodes': [{'address': '4.4.4.4', 'network_value': '4.4.4.0/24'}],
'vlan_id': 4}]},
{'interface_id': 4,
'interfaces': [{'vlan_id': 4,
'zone_ref': 'myzone'}]},
{'interface_id': 5,
'interfaces': [{'vlan_id': 5}]},
{'interface_id': 1000,
'interfaces': [{'nodes': [{'address': '10.10.10.1', 'network_value': '10.10.10.0/24'}]}],
'type': 'tunnel_interface'}] | 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': [{
'nodes': [{'address': mgmt_ip, 'network_value': mgmt_network, 'nodeid': 1,
'reverse_connection': reverse_connection}]
}]
}
interfaces.append(interface)
return Layer3Firewall.create_bulk(
name=name,
node_type='firewall_node',
interfaces=interfaces,
primary_mgt=mgmt_interface,
domain_server_address=domain_server_address,
log_server_ref=log_server_ref,
nodes=1, enable_gti=enable_gti,
enable_antivirus=enable_antivirus,
sidewinder_proxy_enabled=sidewinder_proxy_enabled,
default_nat=default_nat,
location_ref=location_ref,
enable_ospf=enable_ospf,
ospf_profile=ospf_profile, snmp=snmp,
comment=comment, **kw) | 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,
location_ref=None, enable_ospf=False,
sidewinder_proxy_enabled=False,
ospf_profile=None, snmp=None, comment=None, **kw) | 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.
Valid interface types:
- physical_interface (default if not specified)
- tunnel_interface
If providing all engine interfaces in a single operation, see :py:meth:`~create_bulk`
for the proper format.
:param str name: name of firewall engine
:param str mgmt_ip: ip address of management interface
:param str mgmt_network: management network in cidr format
:param str log_server_ref: (optional) href to log_server instance for fw
:param int mgmt_interface: (optional) interface for management from SMC to fw
:param list domain_server_address: (optional) DNS server addresses
:param str zone_ref: zone name, str href or zone name for management interface
(created if not found)
:param bool reverse_connection: should the NGFW be the mgmt initiator (used when behind NAT)
:param bool default_nat: (optional) Whether to enable default NAT for outbound
:param bool enable_antivirus: (optional) Enable antivirus (required DNS)
:param bool enable_gti: (optional) Enable GTI
:param bool sidewinder_proxy_enabled: Enable Sidewinder proxy functionality
:param str location_ref: location href or not for engine if needed to contact SMC
behind NAT (created if not found)
:param bool enable_ospf: whether to turn OSPF on within engine
:param str ospf_profile: optional OSPF profile to use on engine, by ref
:param kw: optional keyword arguments specifying additional interfaces
:raises CreateEngineFailed: Failure to create with reason
:return: :py:class:`smc.core.engine.Engine` | 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': [{
'nodes': [{'dynamic': True, 'dynamic_index': dynamic_index, 'nodeid': 1,
'reverse_connection': reverse_connection,
'automatic_default_route': automatic_default_route}]
}]
}
interfaces.append(interface)
loopback = LoopbackInterface.create(
address=loopback_ndi,
nodeid=1,
auth_request=True,
rank=1)
return Layer3Firewall.create_bulk(
name=name,
node_type='firewall_node',
primary_mgt=interface_id,
interfaces=interfaces,
loopback_ndi=[loopback.data],
domain_server_address=domain_server_address,
log_server_ref=log_server_ref,
nodes=1, enable_gti=enable_gti,
enable_antivirus=enable_antivirus,
sidewinder_proxy_enabled=sidewinder_proxy_enabled,
default_nat=default_nat,
location_ref=location_ref,
comment=comment, **kw) | 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=None,
log_server_ref=None,
zone_ref=None,
enable_gti=False,
enable_antivirus=False,
sidewinder_proxy_enabled=False,
default_nat=False, comment=None, **kw) | 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_connection: specifies the dynamic interface should initiate connections
to management (default: True)
:param bool automatic_default_route: allow SMC to create a dynamic netlink for the default
route (default: True)
:param list domain_server_address: list of IP addresses for engine DNS
:param str loopback_ndi: IP address for a loopback NDI. When creating a dynamic engine, the
`auth_request` must be set to a different interface, so loopback is created
:param str location_ref: location by name for the engine
:param str log_server_ref: log server reference, will use the | 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.