repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
gabstopper/smc-python
smc/examples/ip_lists.py
create_iplist_with_data
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 """ iplist = IPList.create(name=name, iplist=iplist) return iplist
python
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 """ iplist = IPList.create(name=name, iplist=iplist) return iplist
[ "def", "create_iplist_with_data", "(", "name", ",", "iplist", ")", ":", "iplist", "=", "IPList", ".", "create", "(", "name", "=", "name", ",", "iplist", "=", "iplist", ")", "return", "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
[ "Create", "an", "IPList", "with", "initial", "list", "contents", "." ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/examples/ip_lists.py#L139-L148
train
38,700
gabstopper/smc-python
smc/routing/ospf.py
OSPF.enable
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 """ 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)
python
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 """ 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", ")", ":", "ospf_profile", "=", "element_resolver", "(", "ospf_profile", ")", "if", "ospf_profile", "else", "OSPFProfile", "(", "'Default OSPFv2 Profile'", ")", ".", ...
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
[ "Enable", "OSPF", "on", "this", "engine", ".", "For", "master", "engines", "enable", "OSPF", "on", "the", "virtual", "firewall", "." ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/routing/ospf.py#L100-L123
train
38,701
gabstopper/smc-python
smc/routing/ospf.py
OSPFArea.create
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 """ 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)
python
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 """ 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", "=", "...
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
[ "Create", "a", "new", "OSPF", "Area" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/routing/ospf.py#L210-L257
train
38,702
gabstopper/smc-python
smc/routing/ospf.py
OSPFInterfaceSetting.create
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 """ 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)
python
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 """ 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", ...
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
[ "Create", "custom", "OSPF", "interface", "settings", "profile" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/routing/ospf.py#L297-L337
train
38,703
gabstopper/smc-python
smc/routing/ospf.py
OSPFKeyChain.create
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 """ key_chain_entry = key_chain_entry or [] json = {'name': name, 'ospfv2_key_chain_entry': key_chain_entry} return ElementCreator(cls, json)
python
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 """ 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", ")", ":", "key_chain_entry", "=", "key_chain_entry", "or", "[", "]", "json", "=", "{", "'name'", ":", "name", ",", "'ospfv2_key_chain_entry'", ":", "key_chain_entry", "}", "return", "ElementCrea...
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
[ "Create", "a", "key", "chain", "with", "list", "of", "keys" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/routing/ospf.py#L359-L377
train
38,704
gabstopper/smc-python
smc/routing/ospf.py
OSPFDomainSetting.create
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 """ 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)
python
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 """ 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", "=", ...
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
[ "Create", "custom", "Domain", "Settings" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/routing/ospf.py#L519-L551
train
38,705
gabstopper/smc-python
smc/base/decorators.py
exception
def exception(function): """ If exception was specified for prepared_request, inject this into SMCRequest so it can be used for return if needed. """ @functools.wraps(function) def wrapper(*exception, **kwargs): result = function(**kwargs) if exception: result.exception = exception[0] return result return wrapper
python
def exception(function): """ If exception was specified for prepared_request, inject this into SMCRequest so it can be used for return if needed. """ @functools.wraps(function) def wrapper(*exception, **kwargs): result = function(**kwargs) if exception: result.exception = exception[0] return result return wrapper
[ "def", "exception", "(", "function", ")", ":", "@", "functools", ".", "wraps", "(", "function", ")", "def", "wrapper", "(", "*", "exception", ",", "*", "*", "kwargs", ")", ":", "result", "=", "function", "(", "*", "*", "kwargs", ")", "if", "exception...
If exception was specified for prepared_request, inject this into SMCRequest so it can be used for return if needed.
[ "If", "exception", "was", "specified", "for", "prepared_request", "inject", "this", "into", "SMCRequest", "so", "it", "can", "be", "used", "for", "return", "if", "needed", "." ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/base/decorators.py#L107-L119
train
38,706
gabstopper/smc-python
smc/core/engines.py
Layer2Firewall.create
def create(cls, name, mgmt_ip, mgmt_network, mgmt_interface=0, inline_interface='1-2', logical_interface='default_eth', log_server_ref=None, domain_server_address=None, zone_ref=None, enable_antivirus=False, enable_gti=False, comment=None): """ Create a single layer 2 firewall with management interface and inline pair :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 int mgmt_interface: (optional) interface for management from SMC to fw :param str inline_interface: interfaces to use for first inline pair :param str logical_interface: name, str href or LogicalInterface (created if it doesn't exist) :param str log_server_ref: (optional) href to log_server instance :param list domain_server_address: (optional) DNS server addresses :param str zone_ref: zone name, str href or Zone for management interface (created if not found) :param bool enable_antivirus: (optional) Enable antivirus (required DNS) :param bool enable_gti: (optional) Enable GTI :raises CreateEngineFailed: Failure to create with reason :return: :py:class:`smc.core.engine.Engine` """ interfaces = [] interface_id, second_interface_id = inline_interface.split('-') l2 = {'interface_id': interface_id, 'interface': 'inline_interface', 'second_interface_id': second_interface_id, 'logical_interface_ref': logical_interface} interfaces.append( {'physical_interface': Layer2PhysicalInterface(**l2)}) layer3 = {'interface_id': mgmt_interface, 'zone_ref': zone_ref, 'interfaces': [{'nodes': [ {'address': mgmt_ip, 'network_value': mgmt_network, 'nodeid': 1}]}] } interfaces.append( {'physical_interface': Layer3PhysicalInterface(primary_mgt=mgmt_interface, **layer3)}) engine = super(Layer2Firewall, cls)._create( name=name, node_type='fwlayer2_node', physical_interfaces=interfaces, domain_server_address=domain_server_address, log_server_ref=log_server_ref, nodes=1, enable_gti=enable_gti, enable_antivirus=enable_antivirus, comment=comment) try: return ElementCreator(cls, json=engine) except CreateElementFailed as e: raise CreateEngineFailed(e)
python
def create(cls, name, mgmt_ip, mgmt_network, mgmt_interface=0, inline_interface='1-2', logical_interface='default_eth', log_server_ref=None, domain_server_address=None, zone_ref=None, enable_antivirus=False, enable_gti=False, comment=None): """ Create a single layer 2 firewall with management interface and inline pair :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 int mgmt_interface: (optional) interface for management from SMC to fw :param str inline_interface: interfaces to use for first inline pair :param str logical_interface: name, str href or LogicalInterface (created if it doesn't exist) :param str log_server_ref: (optional) href to log_server instance :param list domain_server_address: (optional) DNS server addresses :param str zone_ref: zone name, str href or Zone for management interface (created if not found) :param bool enable_antivirus: (optional) Enable antivirus (required DNS) :param bool enable_gti: (optional) Enable GTI :raises CreateEngineFailed: Failure to create with reason :return: :py:class:`smc.core.engine.Engine` """ interfaces = [] interface_id, second_interface_id = inline_interface.split('-') l2 = {'interface_id': interface_id, 'interface': 'inline_interface', 'second_interface_id': second_interface_id, 'logical_interface_ref': logical_interface} interfaces.append( {'physical_interface': Layer2PhysicalInterface(**l2)}) layer3 = {'interface_id': mgmt_interface, 'zone_ref': zone_ref, 'interfaces': [{'nodes': [ {'address': mgmt_ip, 'network_value': mgmt_network, 'nodeid': 1}]}] } interfaces.append( {'physical_interface': Layer3PhysicalInterface(primary_mgt=mgmt_interface, **layer3)}) engine = super(Layer2Firewall, cls)._create( name=name, node_type='fwlayer2_node', physical_interfaces=interfaces, domain_server_address=domain_server_address, log_server_ref=log_server_ref, nodes=1, enable_gti=enable_gti, enable_antivirus=enable_antivirus, comment=comment) try: return ElementCreator(cls, json=engine) except CreateElementFailed as e: raise CreateEngineFailed(e)
[ "def", "create", "(", "cls", ",", "name", ",", "mgmt_ip", ",", "mgmt_network", ",", "mgmt_interface", "=", "0", ",", "inline_interface", "=", "'1-2'", ",", "logical_interface", "=", "'default_eth'", ",", "log_server_ref", "=", "None", ",", "domain_server_address...
Create a single layer 2 firewall with management interface and inline pair :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 int mgmt_interface: (optional) interface for management from SMC to fw :param str inline_interface: interfaces to use for first inline pair :param str logical_interface: name, str href or LogicalInterface (created if it doesn't exist) :param str log_server_ref: (optional) href to log_server instance :param list domain_server_address: (optional) DNS server addresses :param str zone_ref: zone name, str href or Zone for management interface (created if not found) :param bool enable_antivirus: (optional) Enable antivirus (required DNS) :param bool enable_gti: (optional) Enable GTI :raises CreateEngineFailed: Failure to create with reason :return: :py:class:`smc.core.engine.Engine`
[ "Create", "a", "single", "layer", "2", "firewall", "with", "management", "interface", "and", "inline", "pair" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/engines.py#L258-L317
train
38,707
gabstopper/smc-python
smc/core/engines.py
MasterEngine.create
def create(cls, name, master_type, mgmt_ip, mgmt_network, mgmt_interface=0, log_server_ref=None, zone_ref=None, domain_server_address=None, enable_gti=False, enable_antivirus=False, comment=None): """ Create a Master Engine with management interface :param str name: name of master engine engine :param str master_type: firewall| :param str mgmt_ip: ip address for management interface :param str mgmt_network: full netmask for management :param str mgmt_interface: interface to use for mgmt (default: 0) :param str log_server_ref: (optional) href to log_server instance :param list domain_server_address: (optional) DNS server addresses :param bool enable_antivirus: (optional) Enable antivirus (required DNS) :param bool enable_gti: (optional) Enable GTI :raises CreateEngineFailed: Failure to create with reason :return: :py:class:`smc.core.engine.Engine` """ interface = {'interface_id': mgmt_interface, 'interfaces': [{'nodes': [{'address': mgmt_ip, 'network_value': mgmt_network}]}], 'zone_ref': zone_ref, 'comment': comment} interface = Layer3PhysicalInterface(primary_mgt=mgmt_interface, primary_heartbeat=mgmt_interface, **interface) engine = super(MasterEngine, cls)._create( name=name, node_type='master_node', physical_interfaces=[{'physical_interface':interface}], domain_server_address=domain_server_address, log_server_ref=log_server_ref, nodes=1, enable_gti=enable_gti, enable_antivirus=enable_antivirus, comment=comment) engine.update(master_type=master_type, cluster_mode='standby') try: return ElementCreator(cls, json=engine) except CreateElementFailed as e: raise CreateEngineFailed(e)
python
def create(cls, name, master_type, mgmt_ip, mgmt_network, mgmt_interface=0, log_server_ref=None, zone_ref=None, domain_server_address=None, enable_gti=False, enable_antivirus=False, comment=None): """ Create a Master Engine with management interface :param str name: name of master engine engine :param str master_type: firewall| :param str mgmt_ip: ip address for management interface :param str mgmt_network: full netmask for management :param str mgmt_interface: interface to use for mgmt (default: 0) :param str log_server_ref: (optional) href to log_server instance :param list domain_server_address: (optional) DNS server addresses :param bool enable_antivirus: (optional) Enable antivirus (required DNS) :param bool enable_gti: (optional) Enable GTI :raises CreateEngineFailed: Failure to create with reason :return: :py:class:`smc.core.engine.Engine` """ interface = {'interface_id': mgmt_interface, 'interfaces': [{'nodes': [{'address': mgmt_ip, 'network_value': mgmt_network}]}], 'zone_ref': zone_ref, 'comment': comment} interface = Layer3PhysicalInterface(primary_mgt=mgmt_interface, primary_heartbeat=mgmt_interface, **interface) engine = super(MasterEngine, cls)._create( name=name, node_type='master_node', physical_interfaces=[{'physical_interface':interface}], domain_server_address=domain_server_address, log_server_ref=log_server_ref, nodes=1, enable_gti=enable_gti, enable_antivirus=enable_antivirus, comment=comment) engine.update(master_type=master_type, cluster_mode='standby') try: return ElementCreator(cls, json=engine) except CreateElementFailed as e: raise CreateEngineFailed(e)
[ "def", "create", "(", "cls", ",", "name", ",", "master_type", ",", "mgmt_ip", ",", "mgmt_network", ",", "mgmt_interface", "=", "0", ",", "log_server_ref", "=", "None", ",", "zone_ref", "=", "None", ",", "domain_server_address", "=", "None", ",", "enable_gti"...
Create a Master Engine with management interface :param str name: name of master engine engine :param str master_type: firewall| :param str mgmt_ip: ip address for management interface :param str mgmt_network: full netmask for management :param str mgmt_interface: interface to use for mgmt (default: 0) :param str log_server_ref: (optional) href to log_server instance :param list domain_server_address: (optional) DNS server addresses :param bool enable_antivirus: (optional) Enable antivirus (required DNS) :param bool enable_gti: (optional) Enable GTI :raises CreateEngineFailed: Failure to create with reason :return: :py:class:`smc.core.engine.Engine`
[ "Create", "a", "Master", "Engine", "with", "management", "interface" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/engines.py#L705-L749
train
38,708
gabstopper/smc-python
smc/core/engines.py
MasterEngineCluster.create
def create(cls, name, master_type, macaddress, nodes, mgmt_interface=0, log_server_ref=None, domain_server_address=None, enable_gti=False, enable_antivirus=False, comment=None, **kw): """ Create Master Engine Cluster :param str name: name of master engine engine :param str master_type: firewall| :param str mgmt_ip: ip address for management interface :param str mgmt_netmask: full netmask for management :param str mgmt_interface: interface to use for mgmt (default: 0) :param list nodes: address/network_value/nodeid combination for cluster nodes :param str log_server_ref: (optional) href to log_server instance :param list domain_server_address: (optional) DNS server addresses :param bool enable_antivirus: (optional) Enable antivirus (required DNS) :param bool enable_gti: (optional) Enable GTI :raises CreateEngineFailed: Failure to create with reason :return: :py:class:`smc.core.engine.Engine` Example nodes parameter input:: [{'address':'5.5.5.2', 'network_value':'5.5.5.0/24', 'nodeid':1}, {'address':'5.5.5.3', 'network_value':'5.5.5.0/24', 'nodeid':2}, {'address':'5.5.5.4', 'network_value':'5.5.5.0/24', 'nodeid':3}] """ primary_mgt = primary_heartbeat = mgmt_interface interface = {'interface_id': mgmt_interface, 'interfaces': [{ 'nodes': nodes }], 'macaddress': macaddress, } interface = Layer3PhysicalInterface(primary_mgt=primary_mgt, primary_heartbeat=primary_heartbeat, **interface) engine = super(MasterEngineCluster, cls)._create( name=name, node_type='master_node', physical_interfaces=[{'physical_interface': interface}], domain_server_address=domain_server_address, log_server_ref=log_server_ref, nodes=len(nodes), enable_gti=enable_gti, enable_antivirus=enable_antivirus, comment=comment) engine.update(master_type=master_type, cluster_mode='standby') try: return ElementCreator(cls, json=engine) except CreateElementFailed as e: raise CreateEngineFailed(e)
python
def create(cls, name, master_type, macaddress, nodes, mgmt_interface=0, log_server_ref=None, domain_server_address=None, enable_gti=False, enable_antivirus=False, comment=None, **kw): """ Create Master Engine Cluster :param str name: name of master engine engine :param str master_type: firewall| :param str mgmt_ip: ip address for management interface :param str mgmt_netmask: full netmask for management :param str mgmt_interface: interface to use for mgmt (default: 0) :param list nodes: address/network_value/nodeid combination for cluster nodes :param str log_server_ref: (optional) href to log_server instance :param list domain_server_address: (optional) DNS server addresses :param bool enable_antivirus: (optional) Enable antivirus (required DNS) :param bool enable_gti: (optional) Enable GTI :raises CreateEngineFailed: Failure to create with reason :return: :py:class:`smc.core.engine.Engine` Example nodes parameter input:: [{'address':'5.5.5.2', 'network_value':'5.5.5.0/24', 'nodeid':1}, {'address':'5.5.5.3', 'network_value':'5.5.5.0/24', 'nodeid':2}, {'address':'5.5.5.4', 'network_value':'5.5.5.0/24', 'nodeid':3}] """ primary_mgt = primary_heartbeat = mgmt_interface interface = {'interface_id': mgmt_interface, 'interfaces': [{ 'nodes': nodes }], 'macaddress': macaddress, } interface = Layer3PhysicalInterface(primary_mgt=primary_mgt, primary_heartbeat=primary_heartbeat, **interface) engine = super(MasterEngineCluster, cls)._create( name=name, node_type='master_node', physical_interfaces=[{'physical_interface': interface}], domain_server_address=domain_server_address, log_server_ref=log_server_ref, nodes=len(nodes), enable_gti=enable_gti, enable_antivirus=enable_antivirus, comment=comment) engine.update(master_type=master_type, cluster_mode='standby') try: return ElementCreator(cls, json=engine) except CreateElementFailed as e: raise CreateEngineFailed(e)
[ "def", "create", "(", "cls", ",", "name", ",", "master_type", ",", "macaddress", ",", "nodes", ",", "mgmt_interface", "=", "0", ",", "log_server_ref", "=", "None", ",", "domain_server_address", "=", "None", ",", "enable_gti", "=", "False", ",", "enable_antiv...
Create Master Engine Cluster :param str name: name of master engine engine :param str master_type: firewall| :param str mgmt_ip: ip address for management interface :param str mgmt_netmask: full netmask for management :param str mgmt_interface: interface to use for mgmt (default: 0) :param list nodes: address/network_value/nodeid combination for cluster nodes :param str log_server_ref: (optional) href to log_server instance :param list domain_server_address: (optional) DNS server addresses :param bool enable_antivirus: (optional) Enable antivirus (required DNS) :param bool enable_gti: (optional) Enable GTI :raises CreateEngineFailed: Failure to create with reason :return: :py:class:`smc.core.engine.Engine` Example nodes parameter input:: [{'address':'5.5.5.2', 'network_value':'5.5.5.0/24', 'nodeid':1}, {'address':'5.5.5.3', 'network_value':'5.5.5.0/24', 'nodeid':2}, {'address':'5.5.5.4', 'network_value':'5.5.5.0/24', 'nodeid':3}]
[ "Create", "Master", "Engine", "Cluster" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/engines.py#L761-L821
train
38,709
gabstopper/smc-python
smc/core/collection.py
get_all_loopbacks
def get_all_loopbacks(engine): """ Get all loopback interfaces for a given engine """ data = [] if 'fw_cluster' in engine.type: for cvi in engine.data.get('loopback_cluster_virtual_interface', []): data.append( LoopbackClusterInterface(cvi, engine)) for node in engine.nodes: for lb in node.data.get('loopback_node_dedicated_interface', []): data.append(LoopbackInterface(lb, engine)) return data
python
def get_all_loopbacks(engine): """ Get all loopback interfaces for a given engine """ data = [] if 'fw_cluster' in engine.type: for cvi in engine.data.get('loopback_cluster_virtual_interface', []): data.append( LoopbackClusterInterface(cvi, engine)) for node in engine.nodes: for lb in node.data.get('loopback_node_dedicated_interface', []): data.append(LoopbackInterface(lb, engine)) return data
[ "def", "get_all_loopbacks", "(", "engine", ")", ":", "data", "=", "[", "]", "if", "'fw_cluster'", "in", "engine", ".", "type", ":", "for", "cvi", "in", "engine", ".", "data", ".", "get", "(", "'loopback_cluster_virtual_interface'", ",", "[", "]", ")", ":...
Get all loopback interfaces for a given engine
[ "Get", "all", "loopback", "interfaces", "for", "a", "given", "engine" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/collection.py#L107-L119
train
38,710
gabstopper/smc-python
smc/core/collection.py
PhysicalInterfaceCollection.add
def add(self, interface_id, virtual_mapping=None, virtual_resource_name=None, zone_ref=None, comment=None): """ Add single physical interface with interface_id. Use other methods to fully add an interface configuration based on engine type. Virtual mapping and resource are only used in Virtual Engines. :param str,int interface_id: interface identifier :param int virtual_mapping: virtual firewall id mapping See :class:`smc.core.engine.VirtualResource.vfw_id` :param str virtual_resource_name: virtual resource name See :class:`smc.core.engine.VirtualResource.name` :raises EngineCommandFailed: failure creating interface :return: None """ interface = Layer3PhysicalInterface(engine=self._engine, interface_id=interface_id, zone_ref=zone_ref, comment=comment, virtual_resource_name=virtual_resource_name, virtual_mapping=virtual_mapping) return self._engine.add_interface(interface)
python
def add(self, interface_id, virtual_mapping=None, virtual_resource_name=None, zone_ref=None, comment=None): """ Add single physical interface with interface_id. Use other methods to fully add an interface configuration based on engine type. Virtual mapping and resource are only used in Virtual Engines. :param str,int interface_id: interface identifier :param int virtual_mapping: virtual firewall id mapping See :class:`smc.core.engine.VirtualResource.vfw_id` :param str virtual_resource_name: virtual resource name See :class:`smc.core.engine.VirtualResource.name` :raises EngineCommandFailed: failure creating interface :return: None """ interface = Layer3PhysicalInterface(engine=self._engine, interface_id=interface_id, zone_ref=zone_ref, comment=comment, virtual_resource_name=virtual_resource_name, virtual_mapping=virtual_mapping) return self._engine.add_interface(interface)
[ "def", "add", "(", "self", ",", "interface_id", ",", "virtual_mapping", "=", "None", ",", "virtual_resource_name", "=", "None", ",", "zone_ref", "=", "None", ",", "comment", "=", "None", ")", ":", "interface", "=", "Layer3PhysicalInterface", "(", "engine", "...
Add single physical interface with interface_id. Use other methods to fully add an interface configuration based on engine type. Virtual mapping and resource are only used in Virtual Engines. :param str,int interface_id: interface identifier :param int virtual_mapping: virtual firewall id mapping See :class:`smc.core.engine.VirtualResource.vfw_id` :param str virtual_resource_name: virtual resource name See :class:`smc.core.engine.VirtualResource.name` :raises EngineCommandFailed: failure creating interface :return: None
[ "Add", "single", "physical", "interface", "with", "interface_id", ".", "Use", "other", "methods", "to", "fully", "add", "an", "interface", "configuration", "based", "on", "engine", "type", ".", "Virtual", "mapping", "and", "resource", "are", "only", "used", "i...
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/collection.py#L377-L397
train
38,711
gabstopper/smc-python
smc/core/collection.py
PhysicalInterfaceCollection.add_layer3_vlan_cluster_interface
def add_layer3_vlan_cluster_interface(self, interface_id, vlan_id, nodes=None, cluster_virtual=None, network_value=None, macaddress=None, cvi_mode='packetdispatch', zone_ref=None, comment=None, **kw): """ Add IP addresses to VLANs on a firewall cluster. The minimum params required are ``interface_id`` and ``vlan_id``. To create a VLAN interface with a CVI, specify ``cluster_virtual``, ``cluster_mask`` and ``macaddress``. To create a VLAN with only NDI, specify ``nodes`` parameter. Nodes data structure is expected to be in this format:: nodes=[{'address':'5.5.5.2', 'network_value':'5.5.5.0/24', 'nodeid':1}, {'address':'5.5.5.3', 'network_value':'5.5.5.0/24', 'nodeid':2}] :param str,int interface_id: interface id to assign VLAN. :param str,int vlan_id: vlan identifier :param list nodes: optional addresses for node interfaces (NDI's). For a cluster, each node will require an address specified using the nodes format. :param str cluster_virtual: cluster virtual ip address (optional). If specified, cluster_mask parameter is required :param str network_value: Specifies the network address, i.e. if cluster virtual is 1.1.1.1, cluster mask could be 1.1.1.0/24. :param str macaddress: (optional) if used will provide the mapping from node interfaces to participate in load balancing. :param str cvi_mode: cvi mode for cluster interface (default: packetdispatch) :param zone_ref: zone to assign, can be name, str href or Zone :param dict kw: keyword arguments are passed to top level of VLAN interface, not the base level physical interface. This is useful if you want to pass in a configuration that enables the DHCP server on a VLAN for example. :raises EngineCommandFailed: failure creating interface :return: None .. note:: If the ``interface_id`` specified already exists, it is still possible to add additional VLANs and interface addresses. """ interfaces = {'nodes': nodes if nodes else [], 'cluster_virtual': cluster_virtual, 'network_value': network_value} interfaces.update(**kw) _interface = {'interface_id': interface_id, 'interfaces': [interfaces], 'macaddress': macaddress, 'cvi_mode': cvi_mode if macaddress else 'none', 'zone_ref': zone_ref, 'comment': comment} try: interface = self._engine.interface.get(interface_id) vlan = interface.vlan_interface.get(vlan_id) # Interface exists, so we need to update but check if VLAN already exists if vlan is None: interfaces.update(vlan_id=vlan_id) interface._add_interface(**_interface) else: for k in ('macaddress', 'cvi_mode'): _interface.pop(k) _interface.update(interface_id='{}.{}'.format(interface_id, vlan_id)) vlan._add_interface(**_interface) return interface.update() except InterfaceNotFound: interfaces.update(vlan_id=vlan_id) interface = ClusterPhysicalInterface(**_interface) return self._engine.add_interface(interface)
python
def add_layer3_vlan_cluster_interface(self, interface_id, vlan_id, nodes=None, cluster_virtual=None, network_value=None, macaddress=None, cvi_mode='packetdispatch', zone_ref=None, comment=None, **kw): """ Add IP addresses to VLANs on a firewall cluster. The minimum params required are ``interface_id`` and ``vlan_id``. To create a VLAN interface with a CVI, specify ``cluster_virtual``, ``cluster_mask`` and ``macaddress``. To create a VLAN with only NDI, specify ``nodes`` parameter. Nodes data structure is expected to be in this format:: nodes=[{'address':'5.5.5.2', 'network_value':'5.5.5.0/24', 'nodeid':1}, {'address':'5.5.5.3', 'network_value':'5.5.5.0/24', 'nodeid':2}] :param str,int interface_id: interface id to assign VLAN. :param str,int vlan_id: vlan identifier :param list nodes: optional addresses for node interfaces (NDI's). For a cluster, each node will require an address specified using the nodes format. :param str cluster_virtual: cluster virtual ip address (optional). If specified, cluster_mask parameter is required :param str network_value: Specifies the network address, i.e. if cluster virtual is 1.1.1.1, cluster mask could be 1.1.1.0/24. :param str macaddress: (optional) if used will provide the mapping from node interfaces to participate in load balancing. :param str cvi_mode: cvi mode for cluster interface (default: packetdispatch) :param zone_ref: zone to assign, can be name, str href or Zone :param dict kw: keyword arguments are passed to top level of VLAN interface, not the base level physical interface. This is useful if you want to pass in a configuration that enables the DHCP server on a VLAN for example. :raises EngineCommandFailed: failure creating interface :return: None .. note:: If the ``interface_id`` specified already exists, it is still possible to add additional VLANs and interface addresses. """ interfaces = {'nodes': nodes if nodes else [], 'cluster_virtual': cluster_virtual, 'network_value': network_value} interfaces.update(**kw) _interface = {'interface_id': interface_id, 'interfaces': [interfaces], 'macaddress': macaddress, 'cvi_mode': cvi_mode if macaddress else 'none', 'zone_ref': zone_ref, 'comment': comment} try: interface = self._engine.interface.get(interface_id) vlan = interface.vlan_interface.get(vlan_id) # Interface exists, so we need to update but check if VLAN already exists if vlan is None: interfaces.update(vlan_id=vlan_id) interface._add_interface(**_interface) else: for k in ('macaddress', 'cvi_mode'): _interface.pop(k) _interface.update(interface_id='{}.{}'.format(interface_id, vlan_id)) vlan._add_interface(**_interface) return interface.update() except InterfaceNotFound: interfaces.update(vlan_id=vlan_id) interface = ClusterPhysicalInterface(**_interface) return self._engine.add_interface(interface)
[ "def", "add_layer3_vlan_cluster_interface", "(", "self", ",", "interface_id", ",", "vlan_id", ",", "nodes", "=", "None", ",", "cluster_virtual", "=", "None", ",", "network_value", "=", "None", ",", "macaddress", "=", "None", ",", "cvi_mode", "=", "'packetdispatc...
Add IP addresses to VLANs on a firewall cluster. The minimum params required are ``interface_id`` and ``vlan_id``. To create a VLAN interface with a CVI, specify ``cluster_virtual``, ``cluster_mask`` and ``macaddress``. To create a VLAN with only NDI, specify ``nodes`` parameter. Nodes data structure is expected to be in this format:: nodes=[{'address':'5.5.5.2', 'network_value':'5.5.5.0/24', 'nodeid':1}, {'address':'5.5.5.3', 'network_value':'5.5.5.0/24', 'nodeid':2}] :param str,int interface_id: interface id to assign VLAN. :param str,int vlan_id: vlan identifier :param list nodes: optional addresses for node interfaces (NDI's). For a cluster, each node will require an address specified using the nodes format. :param str cluster_virtual: cluster virtual ip address (optional). If specified, cluster_mask parameter is required :param str network_value: Specifies the network address, i.e. if cluster virtual is 1.1.1.1, cluster mask could be 1.1.1.0/24. :param str macaddress: (optional) if used will provide the mapping from node interfaces to participate in load balancing. :param str cvi_mode: cvi mode for cluster interface (default: packetdispatch) :param zone_ref: zone to assign, can be name, str href or Zone :param dict kw: keyword arguments are passed to top level of VLAN interface, not the base level physical interface. This is useful if you want to pass in a configuration that enables the DHCP server on a VLAN for example. :raises EngineCommandFailed: failure creating interface :return: None .. note:: If the ``interface_id`` specified already exists, it is still possible to add additional VLANs and interface addresses.
[ "Add", "IP", "addresses", "to", "VLANs", "on", "a", "firewall", "cluster", ".", "The", "minimum", "params", "required", "are", "interface_id", "and", "vlan_id", ".", "To", "create", "a", "VLAN", "interface", "with", "a", "CVI", "specify", "cluster_virtual", ...
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/collection.py#L601-L665
train
38,712
gabstopper/smc-python
smc/core/collection.py
PhysicalInterfaceCollection.add_dhcp_interface
def add_dhcp_interface(self, interface_id, dynamic_index, zone_ref=None, vlan_id=None, comment=None): """ Add a DHCP interface on a single FW :param int interface_id: interface id :param int dynamic_index: index number for dhcp interface :param bool primary_mgt: whether to make this primary mgt :param str zone_ref: zone reference, can be name, href or Zone :raises EngineCommandFailed: failure creating interface :return: None See :class:`~DHCPInterface` for more information """ _interface = {'interface_id': interface_id, 'interfaces': [{'nodes': [ {'dynamic': True, 'dynamic_index': dynamic_index}], 'vlan_id': vlan_id}], 'comment': comment, 'zone_ref': zone_ref} if 'single_fw' in self._engine.type: _interface.update(interface='single_node_interface') try: interface = self._engine.interface.get(interface_id) vlan = interface.vlan_interface.get(vlan_id) # Interface exists, so we need to update but check if VLAN already exists if vlan is None: interface._add_interface(**_interface) interface.update() except InterfaceNotFound: interface = Layer3PhysicalInterface(**_interface) return self._engine.add_interface(interface)
python
def add_dhcp_interface(self, interface_id, dynamic_index, zone_ref=None, vlan_id=None, comment=None): """ Add a DHCP interface on a single FW :param int interface_id: interface id :param int dynamic_index: index number for dhcp interface :param bool primary_mgt: whether to make this primary mgt :param str zone_ref: zone reference, can be name, href or Zone :raises EngineCommandFailed: failure creating interface :return: None See :class:`~DHCPInterface` for more information """ _interface = {'interface_id': interface_id, 'interfaces': [{'nodes': [ {'dynamic': True, 'dynamic_index': dynamic_index}], 'vlan_id': vlan_id}], 'comment': comment, 'zone_ref': zone_ref} if 'single_fw' in self._engine.type: _interface.update(interface='single_node_interface') try: interface = self._engine.interface.get(interface_id) vlan = interface.vlan_interface.get(vlan_id) # Interface exists, so we need to update but check if VLAN already exists if vlan is None: interface._add_interface(**_interface) interface.update() except InterfaceNotFound: interface = Layer3PhysicalInterface(**_interface) return self._engine.add_interface(interface)
[ "def", "add_dhcp_interface", "(", "self", ",", "interface_id", ",", "dynamic_index", ",", "zone_ref", "=", "None", ",", "vlan_id", "=", "None", ",", "comment", "=", "None", ")", ":", "_interface", "=", "{", "'interface_id'", ":", "interface_id", ",", "'inter...
Add a DHCP interface on a single FW :param int interface_id: interface id :param int dynamic_index: index number for dhcp interface :param bool primary_mgt: whether to make this primary mgt :param str zone_ref: zone reference, can be name, href or Zone :raises EngineCommandFailed: failure creating interface :return: None See :class:`~DHCPInterface` for more information
[ "Add", "a", "DHCP", "interface", "on", "a", "single", "FW" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/collection.py#L794-L825
train
38,713
gabstopper/smc-python
smc/core/collection.py
PhysicalInterfaceCollection.add_cluster_interface_on_master_engine
def add_cluster_interface_on_master_engine(self, interface_id, macaddress, nodes, zone_ref=None, vlan_id=None, comment=None): """ Add a cluster address specific to a master engine. Master engine clusters will not use "CVI" interfaces like normal layer 3 FW clusters, instead each node has a unique address and share a common macaddress. Adding multiple addresses to an interface is not supported with this method. :param str,int interface_id: interface id to use :param str macaddress: mac address to use on interface :param list nodes: interface node list :param bool is_mgmt: is this a management interface :param zone_ref: zone to use, by name, str href or Zone :param vlan_id: optional VLAN id if this should be a VLAN interface :raises EngineCommandFailed: failure creating interface :return: None """ _interface = {'interface_id': interface_id, 'macaddress': macaddress, 'interfaces': [{'nodes': nodes if nodes else [], 'vlan_id': vlan_id}], 'zone_ref': zone_ref, 'comment': comment} try: interface = self._engine.interface.get(interface_id) vlan = interface.vlan_interface.get(vlan_id) # Interface exists, so we need to update but check if VLAN already exists if vlan is None: interface._add_interface(**_interface) interface.update() except InterfaceNotFound: interface = Layer3PhysicalInterface(**_interface) return self._engine.add_interface(interface)
python
def add_cluster_interface_on_master_engine(self, interface_id, macaddress, nodes, zone_ref=None, vlan_id=None, comment=None): """ Add a cluster address specific to a master engine. Master engine clusters will not use "CVI" interfaces like normal layer 3 FW clusters, instead each node has a unique address and share a common macaddress. Adding multiple addresses to an interface is not supported with this method. :param str,int interface_id: interface id to use :param str macaddress: mac address to use on interface :param list nodes: interface node list :param bool is_mgmt: is this a management interface :param zone_ref: zone to use, by name, str href or Zone :param vlan_id: optional VLAN id if this should be a VLAN interface :raises EngineCommandFailed: failure creating interface :return: None """ _interface = {'interface_id': interface_id, 'macaddress': macaddress, 'interfaces': [{'nodes': nodes if nodes else [], 'vlan_id': vlan_id}], 'zone_ref': zone_ref, 'comment': comment} try: interface = self._engine.interface.get(interface_id) vlan = interface.vlan_interface.get(vlan_id) # Interface exists, so we need to update but check if VLAN already exists if vlan is None: interface._add_interface(**_interface) interface.update() except InterfaceNotFound: interface = Layer3PhysicalInterface(**_interface) return self._engine.add_interface(interface)
[ "def", "add_cluster_interface_on_master_engine", "(", "self", ",", "interface_id", ",", "macaddress", ",", "nodes", ",", "zone_ref", "=", "None", ",", "vlan_id", "=", "None", ",", "comment", "=", "None", ")", ":", "_interface", "=", "{", "'interface_id'", ":",...
Add a cluster address specific to a master engine. Master engine clusters will not use "CVI" interfaces like normal layer 3 FW clusters, instead each node has a unique address and share a common macaddress. Adding multiple addresses to an interface is not supported with this method. :param str,int interface_id: interface id to use :param str macaddress: mac address to use on interface :param list nodes: interface node list :param bool is_mgmt: is this a management interface :param zone_ref: zone to use, by name, str href or Zone :param vlan_id: optional VLAN id if this should be a VLAN interface :raises EngineCommandFailed: failure creating interface :return: None
[ "Add", "a", "cluster", "address", "specific", "to", "a", "master", "engine", ".", "Master", "engine", "clusters", "will", "not", "use", "CVI", "interfaces", "like", "normal", "layer", "3", "FW", "clusters", "instead", "each", "node", "has", "a", "unique", ...
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/collection.py#L827-L859
train
38,714
gabstopper/smc-python
smc/core/collection.py
VirtualPhysicalInterfaceCollection.add_tunnel_interface
def add_tunnel_interface(self, interface_id, address, network_value, zone_ref=None, comment=None): """ Creates a tunnel interface for a virtual engine. :param str,int interface_id: the tunnel id for the interface, used as nicid also :param str address: ip address of interface :param str network_value: network cidr for interface; format: 1.1.1.0/24 :param str zone_ref: zone reference for interface can be name, href or Zone :raises EngineCommandFailed: failure during creation :return: None """ interfaces = [{'nodes': [{'address': address, 'network_value': network_value}]}] interface = {'interface_id': interface_id, 'interfaces': interfaces, 'zone_ref': zone_ref, 'comment': comment} tunnel_interface = TunnelInterface(**interface) self._engine.add_interface(tunnel_interface)
python
def add_tunnel_interface(self, interface_id, address, network_value, zone_ref=None, comment=None): """ Creates a tunnel interface for a virtual engine. :param str,int interface_id: the tunnel id for the interface, used as nicid also :param str address: ip address of interface :param str network_value: network cidr for interface; format: 1.1.1.0/24 :param str zone_ref: zone reference for interface can be name, href or Zone :raises EngineCommandFailed: failure during creation :return: None """ interfaces = [{'nodes': [{'address': address, 'network_value': network_value}]}] interface = {'interface_id': interface_id, 'interfaces': interfaces, 'zone_ref': zone_ref, 'comment': comment} tunnel_interface = TunnelInterface(**interface) self._engine.add_interface(tunnel_interface)
[ "def", "add_tunnel_interface", "(", "self", ",", "interface_id", ",", "address", ",", "network_value", ",", "zone_ref", "=", "None", ",", "comment", "=", "None", ")", ":", "interfaces", "=", "[", "{", "'nodes'", ":", "[", "{", "'address'", ":", "address", ...
Creates a tunnel interface for a virtual engine. :param str,int interface_id: the tunnel id for the interface, used as nicid also :param str address: ip address of interface :param str network_value: network cidr for interface; format: 1.1.1.0/24 :param str zone_ref: zone reference for interface can be name, href or Zone :raises EngineCommandFailed: failure during creation :return: None
[ "Creates", "a", "tunnel", "interface", "for", "a", "virtual", "engine", "." ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/collection.py#L903-L919
train
38,715
gabstopper/smc-python
smc/api/configloader.py
transform_login
def transform_login(config): """ Parse login data as dict. Called from load_from_file and also can be used when collecting information from other sources as well. :param dict data: data representing the valid key/value pairs from smcrc :return: dict dict of settings that can be sent into session.login """ verify = True if config.pop('smc_ssl', None): scheme = 'https' verify = config.pop('ssl_cert_file', None) if config.pop('verify_ssl', None): # Get cert path to verify if not verify: # Setting omitted or already False verify = False else: verify = False else: scheme = 'http' config.pop('verify_ssl', None) config.pop('ssl_cert_file', None) verify = False transformed = {} url = '{}://{}:{}'.format( scheme, config.pop('smc_address', None), config.pop('smc_port', None)) timeout = config.pop('timeout', None) if timeout: try: timeout = int(timeout) except ValueError: timeout = None api_version = config.pop('api_version', None) if api_version: try: float(api_version) except ValueError: api_version = None transformed.update( url=url, api_key=config.pop('smc_apikey', None), api_version=api_version, verify=verify, timeout=timeout, domain=config.pop('domain', None)) if config: transformed.update(kwargs=config) # Any remaining args return transformed
python
def transform_login(config): """ Parse login data as dict. Called from load_from_file and also can be used when collecting information from other sources as well. :param dict data: data representing the valid key/value pairs from smcrc :return: dict dict of settings that can be sent into session.login """ verify = True if config.pop('smc_ssl', None): scheme = 'https' verify = config.pop('ssl_cert_file', None) if config.pop('verify_ssl', None): # Get cert path to verify if not verify: # Setting omitted or already False verify = False else: verify = False else: scheme = 'http' config.pop('verify_ssl', None) config.pop('ssl_cert_file', None) verify = False transformed = {} url = '{}://{}:{}'.format( scheme, config.pop('smc_address', None), config.pop('smc_port', None)) timeout = config.pop('timeout', None) if timeout: try: timeout = int(timeout) except ValueError: timeout = None api_version = config.pop('api_version', None) if api_version: try: float(api_version) except ValueError: api_version = None transformed.update( url=url, api_key=config.pop('smc_apikey', None), api_version=api_version, verify=verify, timeout=timeout, domain=config.pop('domain', None)) if config: transformed.update(kwargs=config) # Any remaining args return transformed
[ "def", "transform_login", "(", "config", ")", ":", "verify", "=", "True", "if", "config", ".", "pop", "(", "'smc_ssl'", ",", "None", ")", ":", "scheme", "=", "'https'", "verify", "=", "config", ".", "pop", "(", "'ssl_cert_file'", ",", "None", ")", "if"...
Parse login data as dict. Called from load_from_file and also can be used when collecting information from other sources as well. :param dict data: data representing the valid key/value pairs from smcrc :return: dict dict of settings that can be sent into session.login
[ "Parse", "login", "data", "as", "dict", ".", "Called", "from", "load_from_file", "and", "also", "can", "be", "used", "when", "collecting", "information", "from", "other", "sources", "as", "well", "." ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/api/configloader.py#L191-L249
train
38,716
gabstopper/smc-python
smc/administration/updates.py
PackageMixin.download
def download(self, timeout=5, wait_for_finish=False): """ Download Package or Engine Update :param int timeout: timeout between queries :raises TaskRunFailed: failure during task status :rtype: TaskOperationPoller """ return Task.execute(self, 'download', timeout=timeout, wait_for_finish=wait_for_finish)
python
def download(self, timeout=5, wait_for_finish=False): """ Download Package or Engine Update :param int timeout: timeout between queries :raises TaskRunFailed: failure during task status :rtype: TaskOperationPoller """ return Task.execute(self, 'download', timeout=timeout, wait_for_finish=wait_for_finish)
[ "def", "download", "(", "self", ",", "timeout", "=", "5", ",", "wait_for_finish", "=", "False", ")", ":", "return", "Task", ".", "execute", "(", "self", ",", "'download'", ",", "timeout", "=", "timeout", ",", "wait_for_finish", "=", "wait_for_finish", ")" ...
Download Package or Engine Update :param int timeout: timeout between queries :raises TaskRunFailed: failure during task status :rtype: TaskOperationPoller
[ "Download", "Package", "or", "Engine", "Update" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/administration/updates.py#L15-L24
train
38,717
gabstopper/smc-python
smc/administration/updates.py
PackageMixin.activate
def activate(self, resource=None, timeout=3, wait_for_finish=False): """ Activate this package on the SMC :param list resource: node href's to activate on. Resource is only required for software upgrades :param int timeout: timeout between queries :raises TaskRunFailed: failure during activation (downloading, etc) :rtype: TaskOperationPoller """ return Task.execute(self, 'activate', json={'resource': resource}, timeout=timeout, wait_for_finish=wait_for_finish)
python
def activate(self, resource=None, timeout=3, wait_for_finish=False): """ Activate this package on the SMC :param list resource: node href's to activate on. Resource is only required for software upgrades :param int timeout: timeout between queries :raises TaskRunFailed: failure during activation (downloading, etc) :rtype: TaskOperationPoller """ return Task.execute(self, 'activate', json={'resource': resource}, timeout=timeout, wait_for_finish=wait_for_finish)
[ "def", "activate", "(", "self", ",", "resource", "=", "None", ",", "timeout", "=", "3", ",", "wait_for_finish", "=", "False", ")", ":", "return", "Task", ".", "execute", "(", "self", ",", "'activate'", ",", "json", "=", "{", "'resource'", ":", "resourc...
Activate this package on the SMC :param list resource: node href's to activate on. Resource is only required for software upgrades :param int timeout: timeout between queries :raises TaskRunFailed: failure during activation (downloading, etc) :rtype: TaskOperationPoller
[ "Activate", "this", "package", "on", "the", "SMC" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/administration/updates.py#L26-L37
train
38,718
gabstopper/smc-python
smc/elements/profiles.py
SandboxService.create
def create(cls, name, sandbox_data_center, portal_username=None, comment=None): """ Create a Sandbox Service element """ json = { 'name': name, 'sandbox_data_center': element_resolver(sandbox_data_center), 'portal_username': portal_username if portal_username else '', 'comment': comment} return ElementCreator(cls, json)
python
def create(cls, name, sandbox_data_center, portal_username=None, comment=None): """ Create a Sandbox Service element """ json = { 'name': name, 'sandbox_data_center': element_resolver(sandbox_data_center), 'portal_username': portal_username if portal_username else '', 'comment': comment} return ElementCreator(cls, json)
[ "def", "create", "(", "cls", ",", "name", ",", "sandbox_data_center", ",", "portal_username", "=", "None", ",", "comment", "=", "None", ")", ":", "json", "=", "{", "'name'", ":", "name", ",", "'sandbox_data_center'", ":", "element_resolver", "(", "sandbox_da...
Create a Sandbox Service element
[ "Create", "a", "Sandbox", "Service", "element" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/elements/profiles.py#L259-L268
train
38,719
gabstopper/smc-python
smc/api/session.py
available_api_versions
def available_api_versions(base_url, timeout=10, verify=True): """ Get all available API versions for this SMC :return version numbers :rtype: list """ try: r = requests.get('%s/api' % base_url, timeout=timeout, verify=verify) # no session required if r.status_code == 200: j = json.loads(r.text) versions = [] for version in j['version']: versions.append(version['rel']) return versions raise SMCConnectionError( 'Invalid status received while getting entry points from SMC. ' 'Status code received %s. Reason: %s' % (r.status_code, r.reason)) except requests.exceptions.RequestException as e: raise SMCConnectionError(e)
python
def available_api_versions(base_url, timeout=10, verify=True): """ Get all available API versions for this SMC :return version numbers :rtype: list """ try: r = requests.get('%s/api' % base_url, timeout=timeout, verify=verify) # no session required if r.status_code == 200: j = json.loads(r.text) versions = [] for version in j['version']: versions.append(version['rel']) return versions raise SMCConnectionError( 'Invalid status received while getting entry points from SMC. ' 'Status code received %s. Reason: %s' % (r.status_code, r.reason)) except requests.exceptions.RequestException as e: raise SMCConnectionError(e)
[ "def", "available_api_versions", "(", "base_url", ",", "timeout", "=", "10", ",", "verify", "=", "True", ")", ":", "try", ":", "r", "=", "requests", ".", "get", "(", "'%s/api'", "%", "base_url", ",", "timeout", "=", "timeout", ",", "verify", "=", "veri...
Get all available API versions for this SMC :return version numbers :rtype: list
[ "Get", "all", "available", "API", "versions", "for", "this", "SMC" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/api/session.py#L765-L788
train
38,720
gabstopper/smc-python
smc/api/session.py
get_api_version
def get_api_version(base_url, api_version=None, timeout=10, verify=True): """ Get the API version specified or resolve the latest version :return api version :rtype: float """ versions = available_api_versions(base_url, timeout, verify) newest_version = max([float(i) for i in versions]) if api_version is None: # Use latest api_version = newest_version else: if api_version not in versions: api_version = newest_version return api_version
python
def get_api_version(base_url, api_version=None, timeout=10, verify=True): """ Get the API version specified or resolve the latest version :return api version :rtype: float """ versions = available_api_versions(base_url, timeout, verify) newest_version = max([float(i) for i in versions]) if api_version is None: # Use latest api_version = newest_version else: if api_version not in versions: api_version = newest_version return api_version
[ "def", "get_api_version", "(", "base_url", ",", "api_version", "=", "None", ",", "timeout", "=", "10", ",", "verify", "=", "True", ")", ":", "versions", "=", "available_api_versions", "(", "base_url", ",", "timeout", ",", "verify", ")", "newest_version", "="...
Get the API version specified or resolve the latest version :return api version :rtype: float
[ "Get", "the", "API", "version", "specified", "or", "resolve", "the", "latest", "version" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/api/session.py#L791-L807
train
38,721
gabstopper/smc-python
smc/api/session.py
SessionManager._register
def _register(self, session): """ Register a session """ if session.session_id: self._sessions[session.name] = session
python
def _register(self, session): """ Register a session """ if session.session_id: self._sessions[session.name] = session
[ "def", "_register", "(", "self", ",", "session", ")", ":", "if", "session", ".", "session_id", ":", "self", ".", "_sessions", "[", "session", ".", "name", "]", "=", "session" ]
Register a session
[ "Register", "a", "session" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/api/session.py#L195-L200
train
38,722
gabstopper/smc-python
smc/api/session.py
SessionManager._deregister
def _deregister(self, session): """ Deregister a session. """ if session in self: self._sessions.pop(self._get_session_key(session), None)
python
def _deregister(self, session): """ Deregister a session. """ if session in self: self._sessions.pop(self._get_session_key(session), None)
[ "def", "_deregister", "(", "self", ",", "session", ")", ":", "if", "session", "in", "self", ":", "self", ".", "_sessions", ".", "pop", "(", "self", ".", "_get_session_key", "(", "session", ")", ",", "None", ")" ]
Deregister a session.
[ "Deregister", "a", "session", "." ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/api/session.py#L202-L207
train
38,723
gabstopper/smc-python
smc/api/session.py
Session.login
def login(self, url=None, api_key=None, login=None, pwd=None, api_version=None, timeout=None, verify=True, alt_filepath=None, domain=None, **kwargs): """ Login to SMC API and retrieve a valid session. Sessions use a pool connection manager to provide dynamic scalability during times of increased load. Each session is managed by a global session manager making it possible to have more than one session per interpreter. An example login and logout session:: from smc import session session.login(url='http://1.1.1.1:8082', api_key='SomeSMCG3ener@t3dPwd') .....do stuff..... session.logout() :param str url: ip of SMC management server :param str api_key: API key created for api client in SMC :param str login: Administrator user in SMC that has privilege to SMC API. :param str pwd: Password for user login. :param api_version (optional): specify api version :param int timeout: (optional): specify a timeout for initial connect; (default 10) :param str|boolean verify: verify SSL connections using cert (default: verify=True) You can pass verify the path to a CA_BUNDLE file or directory with certificates of trusted CAs :param str alt_filepath: If using .smcrc, alternate path+filename :param str domain: domain to log in to. If domains are not configured, this field will be ignored and api client logged in to 'Shared Domain'. :param bool retry_on_busy: pass as kwarg with boolean if you want to add retries if the SMC returns HTTP 503 error during operation. You can also optionally customize this behavior and call :meth:`.set_retry_on_busy` :raises ConfigLoadError: loading cfg from ~.smcrc fails For SSL connections, you can disable validation of the SMC SSL certificate by setting verify=False, however this is not a recommended practice. If you want to use the SSL certificate generated and used by the SMC API server for validation, set verify='path_to_my_dot_pem'. It is also recommended that your certificate has subjectAltName defined per RFC 2818 If SSL warnings are thrown in debug output, see: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings Logout should be called to remove the session immediately from the SMC server. .. note:: As of SMC 6.4 it is possible to give a standard Administrative user access to the SMC API. It is still possible to use an API Client by providing the api_key in the login call. """ params = {} if not url or (not api_key and not (login and pwd)): try: # First try load from file params = load_from_file(alt_filepath) if alt_filepath\ is not None else load_from_file() logger.debug('Read config data from file: %s', params) except ConfigLoadError: # Last ditch effort, try to load from environment params = load_from_environ() logger.debug('Read config data from environ: %s', params) params = params or dict( url=url, api_key=api_key, login=login, pwd=pwd, api_version=api_version, verify=verify, timeout=timeout, domain=domain, kwargs=kwargs or {}) # Check to see this session is already logged in. If so, return. # The session object represents a single connection. Log out to # re-use the same session object or get_session() from the # SessionManager to track multiple sessions. if self.manager and (self.session and self in self.manager): logger.info('An attempt to log in occurred when a session already ' 'exists, bypassing login for session: %s' % self) return self._params = {k: v for k, v in params.items() if v is not None} verify_ssl = self._params.get('verify', True) # Determine and set the API version we will use. self._params.update( api_version=get_api_version( self.url, self.api_version, self.timeout, verify_ssl)) extra_args = self._params.get('kwargs', {}) # Retries configured retry_on_busy = extra_args.pop('retry_on_busy', False) request = self._build_auth_request(verify_ssl, **extra_args) # This will raise if session login fails... self._session = self._get_session(request) self.session.verify = verify_ssl if retry_on_busy: self.set_retry_on_busy() # Load entry points load_entry_points(self) # Put session in manager self.manager._register(self) logger.debug('Login succeeded for admin: %s in domain: %s, session: %s', self.name, self.domain, self.session_id)
python
def login(self, url=None, api_key=None, login=None, pwd=None, api_version=None, timeout=None, verify=True, alt_filepath=None, domain=None, **kwargs): """ Login to SMC API and retrieve a valid session. Sessions use a pool connection manager to provide dynamic scalability during times of increased load. Each session is managed by a global session manager making it possible to have more than one session per interpreter. An example login and logout session:: from smc import session session.login(url='http://1.1.1.1:8082', api_key='SomeSMCG3ener@t3dPwd') .....do stuff..... session.logout() :param str url: ip of SMC management server :param str api_key: API key created for api client in SMC :param str login: Administrator user in SMC that has privilege to SMC API. :param str pwd: Password for user login. :param api_version (optional): specify api version :param int timeout: (optional): specify a timeout for initial connect; (default 10) :param str|boolean verify: verify SSL connections using cert (default: verify=True) You can pass verify the path to a CA_BUNDLE file or directory with certificates of trusted CAs :param str alt_filepath: If using .smcrc, alternate path+filename :param str domain: domain to log in to. If domains are not configured, this field will be ignored and api client logged in to 'Shared Domain'. :param bool retry_on_busy: pass as kwarg with boolean if you want to add retries if the SMC returns HTTP 503 error during operation. You can also optionally customize this behavior and call :meth:`.set_retry_on_busy` :raises ConfigLoadError: loading cfg from ~.smcrc fails For SSL connections, you can disable validation of the SMC SSL certificate by setting verify=False, however this is not a recommended practice. If you want to use the SSL certificate generated and used by the SMC API server for validation, set verify='path_to_my_dot_pem'. It is also recommended that your certificate has subjectAltName defined per RFC 2818 If SSL warnings are thrown in debug output, see: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings Logout should be called to remove the session immediately from the SMC server. .. note:: As of SMC 6.4 it is possible to give a standard Administrative user access to the SMC API. It is still possible to use an API Client by providing the api_key in the login call. """ params = {} if not url or (not api_key and not (login and pwd)): try: # First try load from file params = load_from_file(alt_filepath) if alt_filepath\ is not None else load_from_file() logger.debug('Read config data from file: %s', params) except ConfigLoadError: # Last ditch effort, try to load from environment params = load_from_environ() logger.debug('Read config data from environ: %s', params) params = params or dict( url=url, api_key=api_key, login=login, pwd=pwd, api_version=api_version, verify=verify, timeout=timeout, domain=domain, kwargs=kwargs or {}) # Check to see this session is already logged in. If so, return. # The session object represents a single connection. Log out to # re-use the same session object or get_session() from the # SessionManager to track multiple sessions. if self.manager and (self.session and self in self.manager): logger.info('An attempt to log in occurred when a session already ' 'exists, bypassing login for session: %s' % self) return self._params = {k: v for k, v in params.items() if v is not None} verify_ssl = self._params.get('verify', True) # Determine and set the API version we will use. self._params.update( api_version=get_api_version( self.url, self.api_version, self.timeout, verify_ssl)) extra_args = self._params.get('kwargs', {}) # Retries configured retry_on_busy = extra_args.pop('retry_on_busy', False) request = self._build_auth_request(verify_ssl, **extra_args) # This will raise if session login fails... self._session = self._get_session(request) self.session.verify = verify_ssl if retry_on_busy: self.set_retry_on_busy() # Load entry points load_entry_points(self) # Put session in manager self.manager._register(self) logger.debug('Login succeeded for admin: %s in domain: %s, session: %s', self.name, self.domain, self.session_id)
[ "def", "login", "(", "self", ",", "url", "=", "None", ",", "api_key", "=", "None", ",", "login", "=", "None", ",", "pwd", "=", "None", ",", "api_version", "=", "None", ",", "timeout", "=", "None", ",", "verify", "=", "True", ",", "alt_filepath", "=...
Login to SMC API and retrieve a valid session. Sessions use a pool connection manager to provide dynamic scalability during times of increased load. Each session is managed by a global session manager making it possible to have more than one session per interpreter. An example login and logout session:: from smc import session session.login(url='http://1.1.1.1:8082', api_key='SomeSMCG3ener@t3dPwd') .....do stuff..... session.logout() :param str url: ip of SMC management server :param str api_key: API key created for api client in SMC :param str login: Administrator user in SMC that has privilege to SMC API. :param str pwd: Password for user login. :param api_version (optional): specify api version :param int timeout: (optional): specify a timeout for initial connect; (default 10) :param str|boolean verify: verify SSL connections using cert (default: verify=True) You can pass verify the path to a CA_BUNDLE file or directory with certificates of trusted CAs :param str alt_filepath: If using .smcrc, alternate path+filename :param str domain: domain to log in to. If domains are not configured, this field will be ignored and api client logged in to 'Shared Domain'. :param bool retry_on_busy: pass as kwarg with boolean if you want to add retries if the SMC returns HTTP 503 error during operation. You can also optionally customize this behavior and call :meth:`.set_retry_on_busy` :raises ConfigLoadError: loading cfg from ~.smcrc fails For SSL connections, you can disable validation of the SMC SSL certificate by setting verify=False, however this is not a recommended practice. If you want to use the SSL certificate generated and used by the SMC API server for validation, set verify='path_to_my_dot_pem'. It is also recommended that your certificate has subjectAltName defined per RFC 2818 If SSL warnings are thrown in debug output, see: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings Logout should be called to remove the session immediately from the SMC server. .. note:: As of SMC 6.4 it is possible to give a standard Administrative user access to the SMC API. It is still possible to use an API Client by providing the api_key in the login call.
[ "Login", "to", "SMC", "API", "and", "retrieve", "a", "valid", "session", ".", "Sessions", "use", "a", "pool", "connection", "manager", "to", "provide", "dynamic", "scalability", "during", "times", "of", "increased", "load", ".", "Each", "session", "is", "man...
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/api/session.py#L404-L516
train
38,724
gabstopper/smc-python
smc/api/session.py
Session._build_auth_request
def _build_auth_request(self, verify=False, **kwargs): """ Build the authentication request to SMC """ json = { 'domain': self.domain } credential = self.credential params = {} if credential.provider_name.startswith('lms'): params = dict( login=credential._login, pwd=credential._pwd) else: json.update(authenticationkey=credential._api_key) if kwargs: json.update(**kwargs) self._extra_args.update(**kwargs) # Store in case we need to rebuild later request = dict( url=self.credential.get_provider_entry_point(self.url, self.api_version), json=json, params=params, headers={'content-type': 'application/json'}, verify=verify) return request
python
def _build_auth_request(self, verify=False, **kwargs): """ Build the authentication request to SMC """ json = { 'domain': self.domain } credential = self.credential params = {} if credential.provider_name.startswith('lms'): params = dict( login=credential._login, pwd=credential._pwd) else: json.update(authenticationkey=credential._api_key) if kwargs: json.update(**kwargs) self._extra_args.update(**kwargs) # Store in case we need to rebuild later request = dict( url=self.credential.get_provider_entry_point(self.url, self.api_version), json=json, params=params, headers={'content-type': 'application/json'}, verify=verify) return request
[ "def", "_build_auth_request", "(", "self", ",", "verify", "=", "False", ",", "*", "*", "kwargs", ")", ":", "json", "=", "{", "'domain'", ":", "self", ".", "domain", "}", "credential", "=", "self", ".", "credential", "params", "=", "{", "}", "if", "cr...
Build the authentication request to SMC
[ "Build", "the", "authentication", "request", "to", "SMC" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/api/session.py#L521-L550
train
38,725
gabstopper/smc-python
smc/policy/rule_elements.py
RuleElement.add
def add(self, data): """ Add a single entry to field. Entries can be added to a rule using the href of the element or by loading the element directly. Element should be of type :py:mod:`smc.elements.network`. After modifying rule, call :py:meth:`~.save`. Example of adding entry by element:: policy = FirewallPolicy('policy') for rule in policy.fw_ipv4_nat_rules.all(): if rule.name == 'therule': rule.sources.add(Host('myhost')) rule.save() .. note:: If submitting type Element and the element cannot be found, it will be skipped. :param data: entry to add :type data: Element or str """ if self.is_none or self.is_any: self.clear() self.data[self.typeof] = [] try: self.get(self.typeof).append(element_resolver(data)) except ElementNotFound: pass
python
def add(self, data): """ Add a single entry to field. Entries can be added to a rule using the href of the element or by loading the element directly. Element should be of type :py:mod:`smc.elements.network`. After modifying rule, call :py:meth:`~.save`. Example of adding entry by element:: policy = FirewallPolicy('policy') for rule in policy.fw_ipv4_nat_rules.all(): if rule.name == 'therule': rule.sources.add(Host('myhost')) rule.save() .. note:: If submitting type Element and the element cannot be found, it will be skipped. :param data: entry to add :type data: Element or str """ if self.is_none or self.is_any: self.clear() self.data[self.typeof] = [] try: self.get(self.typeof).append(element_resolver(data)) except ElementNotFound: pass
[ "def", "add", "(", "self", ",", "data", ")", ":", "if", "self", ".", "is_none", "or", "self", ".", "is_any", ":", "self", ".", "clear", "(", ")", "self", ".", "data", "[", "self", ".", "typeof", "]", "=", "[", "]", "try", ":", "self", ".", "g...
Add a single entry to field. Entries can be added to a rule using the href of the element or by loading the element directly. Element should be of type :py:mod:`smc.elements.network`. After modifying rule, call :py:meth:`~.save`. Example of adding entry by element:: policy = FirewallPolicy('policy') for rule in policy.fw_ipv4_nat_rules.all(): if rule.name == 'therule': rule.sources.add(Host('myhost')) rule.save() .. note:: If submitting type Element and the element cannot be found, it will be skipped. :param data: entry to add :type data: Element or str
[ "Add", "a", "single", "entry", "to", "field", "." ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/policy/rule_elements.py#L44-L74
train
38,726
gabstopper/smc-python
smc/policy/rule_elements.py
RuleElement.all
def all(self): """ Return all destinations for this rule. Elements returned are of the object type for the given element for further introspection. Search the fields in rule:: for sources in rule.sources.all(): print('My source: %s' % sources) :return: elements by resolved object type :rtype: list(Element) """ if not self.is_any and not self.is_none: return [Element.from_href(href) for href in self.get(self.typeof)] return []
python
def all(self): """ Return all destinations for this rule. Elements returned are of the object type for the given element for further introspection. Search the fields in rule:: for sources in rule.sources.all(): print('My source: %s' % sources) :return: elements by resolved object type :rtype: list(Element) """ if not self.is_any and not self.is_none: return [Element.from_href(href) for href in self.get(self.typeof)] return []
[ "def", "all", "(", "self", ")", ":", "if", "not", "self", ".", "is_any", "and", "not", "self", ".", "is_none", ":", "return", "[", "Element", ".", "from_href", "(", "href", ")", "for", "href", "in", "self", ".", "get", "(", "self", ".", "typeof", ...
Return all destinations for this rule. Elements returned are of the object type for the given element for further introspection. Search the fields in rule:: for sources in rule.sources.all(): print('My source: %s' % sources) :return: elements by resolved object type :rtype: list(Element)
[ "Return", "all", "destinations", "for", "this", "rule", ".", "Elements", "returned", "are", "of", "the", "object", "type", "for", "the", "given", "element", "for", "further", "introspection", "." ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/policy/rule_elements.py#L162-L179
train
38,727
gabstopper/smc-python
smc/policy/rule_elements.py
MatchExpression.create
def create(cls, name, user=None, network_element=None, domain_name=None, zone=None, executable=None): """ Create a match expression :param str name: name of match expression :param str user: name of user or user group :param Element network_element: valid network element type, i.e. host, network, etc :param DomainName domain_name: domain name network element :param Zone zone: zone to use :param str executable: name of executable or group :raises ElementNotFound: specified object does not exist :return: instance with meta :rtype: MatchExpression """ ref_list = [] if user: pass if network_element: ref_list.append(network_element.href) if domain_name: ref_list.append(domain_name.href) if zone: ref_list.append(zone.href) if executable: pass json = {'name': name, 'ref': ref_list} return ElementCreator(cls, json)
python
def create(cls, name, user=None, network_element=None, domain_name=None, zone=None, executable=None): """ Create a match expression :param str name: name of match expression :param str user: name of user or user group :param Element network_element: valid network element type, i.e. host, network, etc :param DomainName domain_name: domain name network element :param Zone zone: zone to use :param str executable: name of executable or group :raises ElementNotFound: specified object does not exist :return: instance with meta :rtype: MatchExpression """ ref_list = [] if user: pass if network_element: ref_list.append(network_element.href) if domain_name: ref_list.append(domain_name.href) if zone: ref_list.append(zone.href) if executable: pass json = {'name': name, 'ref': ref_list} return ElementCreator(cls, json)
[ "def", "create", "(", "cls", ",", "name", ",", "user", "=", "None", ",", "network_element", "=", "None", ",", "domain_name", "=", "None", ",", "zone", "=", "None", ",", "executable", "=", "None", ")", ":", "ref_list", "=", "[", "]", "if", "user", "...
Create a match expression :param str name: name of match expression :param str user: name of user or user group :param Element network_element: valid network element type, i.e. host, network, etc :param DomainName domain_name: domain name network element :param Zone zone: zone to use :param str executable: name of executable or group :raises ElementNotFound: specified object does not exist :return: instance with meta :rtype: MatchExpression
[ "Create", "a", "match", "expression" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/policy/rule_elements.py#L836-L866
train
38,728
gabstopper/smc-python
smc/core/addon.py
AntiVirus.enable
def enable(self): """ Enable antivirus on the engine """ self.update(antivirus_enabled=True, virus_mirror='update.nai.com/Products/CommonUpdater' if \ not self.get('virus_mirror') else self.virus_mirror, antivirus_update_time=self.antivirus_update_time if \ self.get('antivirus_update_time') else 21600000)
python
def enable(self): """ Enable antivirus on the engine """ self.update(antivirus_enabled=True, virus_mirror='update.nai.com/Products/CommonUpdater' if \ not self.get('virus_mirror') else self.virus_mirror, antivirus_update_time=self.antivirus_update_time if \ self.get('antivirus_update_time') else 21600000)
[ "def", "enable", "(", "self", ")", ":", "self", ".", "update", "(", "antivirus_enabled", "=", "True", ",", "virus_mirror", "=", "'update.nai.com/Products/CommonUpdater'", "if", "not", "self", ".", "get", "(", "'virus_mirror'", ")", "else", "self", ".", "virus_...
Enable antivirus on the engine
[ "Enable", "antivirus", "on", "the", "engine" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/addon.py#L133-L141
train
38,729
gabstopper/smc-python
smc/core/addon.py
Sandbox.disable
def disable(self): """ Disable the sandbox on this engine. """ self.engine.data.update(sandbox_type='none') self.pop('cloud_sandbox_settings', None) #pre-6.3 self.pop('sandbox_settings', None)
python
def disable(self): """ Disable the sandbox on this engine. """ self.engine.data.update(sandbox_type='none') self.pop('cloud_sandbox_settings', None) #pre-6.3 self.pop('sandbox_settings', None)
[ "def", "disable", "(", "self", ")", ":", "self", ".", "engine", ".", "data", ".", "update", "(", "sandbox_type", "=", "'none'", ")", "self", ".", "pop", "(", "'cloud_sandbox_settings'", ",", "None", ")", "#pre-6.3", "self", ".", "pop", "(", "'sandbox_set...
Disable the sandbox on this engine.
[ "Disable", "the", "sandbox", "on", "this", "engine", "." ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/addon.py#L348-L354
train
38,730
gabstopper/smc-python
smc/core/node.py
Node.bind_license
def bind_license(self, license_item_id=None): """ Auto bind license, uses dynamic if POS is not found :param str license_item_id: license id :raises LicenseError: binding license failed, possibly no licenses :return: None """ params = {'license_item_id': license_item_id} self.make_request( LicenseError, method='create', resource='bind', params=params)
python
def bind_license(self, license_item_id=None): """ Auto bind license, uses dynamic if POS is not found :param str license_item_id: license id :raises LicenseError: binding license failed, possibly no licenses :return: None """ params = {'license_item_id': license_item_id} self.make_request( LicenseError, method='create', resource='bind', params=params)
[ "def", "bind_license", "(", "self", ",", "license_item_id", "=", "None", ")", ":", "params", "=", "{", "'license_item_id'", ":", "license_item_id", "}", "self", ".", "make_request", "(", "LicenseError", ",", "method", "=", "'create'", ",", "resource", "=", "...
Auto bind license, uses dynamic if POS is not found :param str license_item_id: license id :raises LicenseError: binding license failed, possibly no licenses :return: None
[ "Auto", "bind", "license", "uses", "dynamic", "if", "POS", "is", "not", "found" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/node.py#L132-L145
train
38,731
gabstopper/smc-python
smc/core/node.py
Node.initial_contact
def initial_contact(self, enable_ssh=True, time_zone=None, keyboard=None, install_on_server=None, filename=None, as_base64=False): """ Allows to save the initial contact for for the specified node :param bool enable_ssh: flag to know if we allow the ssh daemon on the specified node :param str time_zone: optional time zone to set on the specified node :param str keyboard: optional keyboard to set on the specified node :param bool install_on_server: optional flag to know if the generated configuration needs to be installed on SMC Install server (POS is needed) :param str filename: filename to save initial_contact to :param bool as_base64: return the initial config in base 64 format. Useful for cloud based engine deployments as userdata :raises NodeCommandFailed: IOError handling initial configuration data :return: initial contact text information :rtype: str """ result = self.make_request( NodeCommandFailed, method='create', raw_result=True, resource='initial_contact', params={'enable_ssh': enable_ssh}) if result.content: if as_base64: result.content = b64encode(result.content) if filename: try: save_to_file(filename, result.content) except IOError as e: raise NodeCommandFailed( 'Error occurred when attempting to save initial ' 'contact to file: {}'.format(e)) return result.content
python
def initial_contact(self, enable_ssh=True, time_zone=None, keyboard=None, install_on_server=None, filename=None, as_base64=False): """ Allows to save the initial contact for for the specified node :param bool enable_ssh: flag to know if we allow the ssh daemon on the specified node :param str time_zone: optional time zone to set on the specified node :param str keyboard: optional keyboard to set on the specified node :param bool install_on_server: optional flag to know if the generated configuration needs to be installed on SMC Install server (POS is needed) :param str filename: filename to save initial_contact to :param bool as_base64: return the initial config in base 64 format. Useful for cloud based engine deployments as userdata :raises NodeCommandFailed: IOError handling initial configuration data :return: initial contact text information :rtype: str """ result = self.make_request( NodeCommandFailed, method='create', raw_result=True, resource='initial_contact', params={'enable_ssh': enable_ssh}) if result.content: if as_base64: result.content = b64encode(result.content) if filename: try: save_to_file(filename, result.content) except IOError as e: raise NodeCommandFailed( 'Error occurred when attempting to save initial ' 'contact to file: {}'.format(e)) return result.content
[ "def", "initial_contact", "(", "self", ",", "enable_ssh", "=", "True", ",", "time_zone", "=", "None", ",", "keyboard", "=", "None", ",", "install_on_server", "=", "None", ",", "filename", "=", "None", ",", "as_base64", "=", "False", ")", ":", "result", "...
Allows to save the initial contact for for the specified node :param bool enable_ssh: flag to know if we allow the ssh daemon on the specified node :param str time_zone: optional time zone to set on the specified node :param str keyboard: optional keyboard to set on the specified node :param bool install_on_server: optional flag to know if the generated configuration needs to be installed on SMC Install server (POS is needed) :param str filename: filename to save initial_contact to :param bool as_base64: return the initial config in base 64 format. Useful for cloud based engine deployments as userdata :raises NodeCommandFailed: IOError handling initial configuration data :return: initial contact text information :rtype: str
[ "Allows", "to", "save", "the", "initial", "contact", "for", "for", "the", "specified", "node" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/node.py#L171-L211
train
38,732
gabstopper/smc-python
smc/core/node.py
Node.go_offline
def go_offline(self, comment=None): """ Executes a Go-Offline operation on the specified node :param str comment: optional comment to audit :raises NodeCommandFailed: offline not available :return: None """ self.make_request( NodeCommandFailed, method='update', resource='go_offline', params={'comment': comment})
python
def go_offline(self, comment=None): """ Executes a Go-Offline operation on the specified node :param str comment: optional comment to audit :raises NodeCommandFailed: offline not available :return: None """ self.make_request( NodeCommandFailed, method='update', resource='go_offline', params={'comment': comment})
[ "def", "go_offline", "(", "self", ",", "comment", "=", "None", ")", ":", "self", ".", "make_request", "(", "NodeCommandFailed", ",", "method", "=", "'update'", ",", "resource", "=", "'go_offline'", ",", "params", "=", "{", "'comment'", ":", "comment", "}",...
Executes a Go-Offline operation on the specified node :param str comment: optional comment to audit :raises NodeCommandFailed: offline not available :return: None
[ "Executes", "a", "Go", "-", "Offline", "operation", "on", "the", "specified", "node" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/node.py#L333-L345
train
38,733
gabstopper/smc-python
smc/core/node.py
Node.lock_online
def lock_online(self, comment=None): """ Executes a Lock-Online operation on the specified node :param str comment: comment for audit :raises NodeCommandFailed: cannot lock online :return: None """ self.make_request( NodeCommandFailed, method='update', resource='lock_online', params={'comment': comment})
python
def lock_online(self, comment=None): """ Executes a Lock-Online operation on the specified node :param str comment: comment for audit :raises NodeCommandFailed: cannot lock online :return: None """ self.make_request( NodeCommandFailed, method='update', resource='lock_online', params={'comment': comment})
[ "def", "lock_online", "(", "self", ",", "comment", "=", "None", ")", ":", "self", ".", "make_request", "(", "NodeCommandFailed", ",", "method", "=", "'update'", ",", "resource", "=", "'lock_online'", ",", "params", "=", "{", "'comment'", ":", "comment", "}...
Executes a Lock-Online operation on the specified node :param str comment: comment for audit :raises NodeCommandFailed: cannot lock online :return: None
[ "Executes", "a", "Lock", "-", "Online", "operation", "on", "the", "specified", "node" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/node.py#L362-L374
train
38,734
gabstopper/smc-python
smc/core/node.py
Node.reset_user_db
def reset_user_db(self, comment=None): """ Executes a Send Reset LDAP User DB Request operation on this node. :param str comment: comment to audit :raises NodeCommandFailed: failure resetting db :return: None """ self.make_request( NodeCommandFailed, method='update', resource='reset_user_db', params={'comment': comment})
python
def reset_user_db(self, comment=None): """ Executes a Send Reset LDAP User DB Request operation on this node. :param str comment: comment to audit :raises NodeCommandFailed: failure resetting db :return: None """ self.make_request( NodeCommandFailed, method='update', resource='reset_user_db', params={'comment': comment})
[ "def", "reset_user_db", "(", "self", ",", "comment", "=", "None", ")", ":", "self", ".", "make_request", "(", "NodeCommandFailed", ",", "method", "=", "'update'", ",", "resource", "=", "'reset_user_db'", ",", "params", "=", "{", "'comment'", ":", "comment", ...
Executes a Send Reset LDAP User DB Request operation on this node. :param str comment: comment to audit :raises NodeCommandFailed: failure resetting db :return: None
[ "Executes", "a", "Send", "Reset", "LDAP", "User", "DB", "Request", "operation", "on", "this", "node", "." ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/node.py#L391-L404
train
38,735
gabstopper/smc-python
smc/core/node.py
Node.reboot
def reboot(self, comment=None): """ Send reboot command to this node. :param str comment: comment to audit :raises NodeCommandFailed: reboot failed with reason :return: None """ self.make_request( NodeCommandFailed, method='update', resource='reboot', params={'comment': comment})
python
def reboot(self, comment=None): """ Send reboot command to this node. :param str comment: comment to audit :raises NodeCommandFailed: reboot failed with reason :return: None """ self.make_request( NodeCommandFailed, method='update', resource='reboot', params={'comment': comment})
[ "def", "reboot", "(", "self", ",", "comment", "=", "None", ")", ":", "self", ".", "make_request", "(", "NodeCommandFailed", ",", "method", "=", "'update'", ",", "resource", "=", "'reboot'", ",", "params", "=", "{", "'comment'", ":", "comment", "}", ")" ]
Send reboot command to this node. :param str comment: comment to audit :raises NodeCommandFailed: reboot failed with reason :return: None
[ "Send", "reboot", "command", "to", "this", "node", "." ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/node.py#L446-L458
train
38,736
gabstopper/smc-python
smc/core/node.py
Node.ssh
def ssh(self, enable=True, comment=None): """ Enable or disable SSH :param bool enable: enable or disable SSH daemon :param str comment: optional comment for audit :raises NodeCommandFailed: cannot enable SSH daemon :return: None """ self.make_request( NodeCommandFailed, method='update', resource='ssh', params={'enable': enable, 'comment': comment})
python
def ssh(self, enable=True, comment=None): """ Enable or disable SSH :param bool enable: enable or disable SSH daemon :param str comment: optional comment for audit :raises NodeCommandFailed: cannot enable SSH daemon :return: None """ self.make_request( NodeCommandFailed, method='update', resource='ssh', params={'enable': enable, 'comment': comment})
[ "def", "ssh", "(", "self", ",", "enable", "=", "True", ",", "comment", "=", "None", ")", ":", "self", ".", "make_request", "(", "NodeCommandFailed", ",", "method", "=", "'update'", ",", "resource", "=", "'ssh'", ",", "params", "=", "{", "'enable'", ":"...
Enable or disable SSH :param bool enable: enable or disable SSH daemon :param str comment: optional comment for audit :raises NodeCommandFailed: cannot enable SSH daemon :return: None
[ "Enable", "or", "disable", "SSH" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/node.py#L517-L530
train
38,737
gabstopper/smc-python
smc/core/node.py
Node.change_ssh_pwd
def change_ssh_pwd(self, pwd=None, comment=None): """ Executes a change SSH password operation on the specified node :param str pwd: changed password value :param str comment: optional comment for audit log :raises NodeCommandFailed: cannot change ssh password :return: None """ self.make_request( NodeCommandFailed, method='update', resource='change_ssh_pwd', params={'comment': comment}, json={'value': pwd})
python
def change_ssh_pwd(self, pwd=None, comment=None): """ Executes a change SSH password operation on the specified node :param str pwd: changed password value :param str comment: optional comment for audit log :raises NodeCommandFailed: cannot change ssh password :return: None """ self.make_request( NodeCommandFailed, method='update', resource='change_ssh_pwd', params={'comment': comment}, json={'value': pwd})
[ "def", "change_ssh_pwd", "(", "self", ",", "pwd", "=", "None", ",", "comment", "=", "None", ")", ":", "self", ".", "make_request", "(", "NodeCommandFailed", ",", "method", "=", "'update'", ",", "resource", "=", "'change_ssh_pwd'", ",", "params", "=", "{", ...
Executes a change SSH password operation on the specified node :param str pwd: changed password value :param str comment: optional comment for audit log :raises NodeCommandFailed: cannot change ssh password :return: None
[ "Executes", "a", "change", "SSH", "password", "operation", "on", "the", "specified", "node" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/node.py#L532-L546
train
38,738
gabstopper/smc-python
smc/routing/access_list.py
AccessList.create
def create(cls, name, entries=None, comment=None, **kw): """ Create an Access List Entry. Depending on the access list type you are creating (IPAccessList, IPv6AccessList, IPPrefixList, IPv6PrefixList, CommunityAccessList, ExtendedCommunityAccessList), entries will define a dict of the valid attributes for that ACL type. Each class has a defined list of attributes documented in it's class. You can optionally leave entries blank and use the :meth:`~add_entry` method after creating the list container. :param str name: name of IP Access List :param list entries: access control entry :param kw: optional keywords that might be necessary to create the ACL (see specific Access Control List documentation for options) :raises CreateElementFailed: cannot create element :return: The access list based on type """ access_list_entry = [] if entries: for entry in entries: access_list_entry.append( {'{}_entry'.format(cls.typeof): entry}) json = {'name': name, 'entries': access_list_entry, 'comment': comment} json.update(kw) return ElementCreator(cls, json)
python
def create(cls, name, entries=None, comment=None, **kw): """ Create an Access List Entry. Depending on the access list type you are creating (IPAccessList, IPv6AccessList, IPPrefixList, IPv6PrefixList, CommunityAccessList, ExtendedCommunityAccessList), entries will define a dict of the valid attributes for that ACL type. Each class has a defined list of attributes documented in it's class. You can optionally leave entries blank and use the :meth:`~add_entry` method after creating the list container. :param str name: name of IP Access List :param list entries: access control entry :param kw: optional keywords that might be necessary to create the ACL (see specific Access Control List documentation for options) :raises CreateElementFailed: cannot create element :return: The access list based on type """ access_list_entry = [] if entries: for entry in entries: access_list_entry.append( {'{}_entry'.format(cls.typeof): entry}) json = {'name': name, 'entries': access_list_entry, 'comment': comment} json.update(kw) return ElementCreator(cls, json)
[ "def", "create", "(", "cls", ",", "name", ",", "entries", "=", "None", ",", "comment", "=", "None", ",", "*", "*", "kw", ")", ":", "access_list_entry", "=", "[", "]", "if", "entries", ":", "for", "entry", "in", "entries", ":", "access_list_entry", "....
Create an Access List Entry. Depending on the access list type you are creating (IPAccessList, IPv6AccessList, IPPrefixList, IPv6PrefixList, CommunityAccessList, ExtendedCommunityAccessList), entries will define a dict of the valid attributes for that ACL type. Each class has a defined list of attributes documented in it's class. You can optionally leave entries blank and use the :meth:`~add_entry` method after creating the list container. :param str name: name of IP Access List :param list entries: access control entry :param kw: optional keywords that might be necessary to create the ACL (see specific Access Control List documentation for options) :raises CreateElementFailed: cannot create element :return: The access list based on type
[ "Create", "an", "Access", "List", "Entry", "." ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/routing/access_list.py#L34-L65
train
38,739
gabstopper/smc-python
smc/routing/access_list.py
AccessList.add_entry
def add_entry(self, **kw): """ Add an entry to an AccessList. Use the supported arguments for the inheriting class for keyword arguments. :raises UpdateElementFailed: failure to modify with reason :return: None """ self.data.setdefault('entries', []).append( {'{}_entry'.format(self.typeof): kw})
python
def add_entry(self, **kw): """ Add an entry to an AccessList. Use the supported arguments for the inheriting class for keyword arguments. :raises UpdateElementFailed: failure to modify with reason :return: None """ self.data.setdefault('entries', []).append( {'{}_entry'.format(self.typeof): kw})
[ "def", "add_entry", "(", "self", ",", "*", "*", "kw", ")", ":", "self", ".", "data", ".", "setdefault", "(", "'entries'", ",", "[", "]", ")", ".", "append", "(", "{", "'{}_entry'", ".", "format", "(", "self", ".", "typeof", ")", ":", "kw", "}", ...
Add an entry to an AccessList. Use the supported arguments for the inheriting class for keyword arguments. :raises UpdateElementFailed: failure to modify with reason :return: None
[ "Add", "an", "entry", "to", "an", "AccessList", ".", "Use", "the", "supported", "arguments", "for", "the", "inheriting", "class", "for", "keyword", "arguments", "." ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/routing/access_list.py#L78-L87
train
38,740
gabstopper/smc-python
smc/routing/access_list.py
AccessList.remove_entry
def remove_entry(self, **field_value): """ Remove an AccessList entry by field specified. Use the supported arguments for the inheriting class for keyword arguments. :raises UpdateElementFailed: failed to modify with reason :return: None """ field, value = next(iter(field_value.items())) self.data['entries'][:] = [entry for entry in self.data.get('entries') if entry.get('{}_entry'.format(self.typeof)) .get(field) != str(value)]
python
def remove_entry(self, **field_value): """ Remove an AccessList entry by field specified. Use the supported arguments for the inheriting class for keyword arguments. :raises UpdateElementFailed: failed to modify with reason :return: None """ field, value = next(iter(field_value.items())) self.data['entries'][:] = [entry for entry in self.data.get('entries') if entry.get('{}_entry'.format(self.typeof)) .get(field) != str(value)]
[ "def", "remove_entry", "(", "self", ",", "*", "*", "field_value", ")", ":", "field", ",", "value", "=", "next", "(", "iter", "(", "field_value", ".", "items", "(", ")", ")", ")", "self", ".", "data", "[", "'entries'", "]", "[", ":", "]", "=", "["...
Remove an AccessList entry by field specified. Use the supported arguments for the inheriting class for keyword arguments. :raises UpdateElementFailed: failed to modify with reason :return: None
[ "Remove", "an", "AccessList", "entry", "by", "field", "specified", ".", "Use", "the", "supported", "arguments", "for", "the", "inheriting", "class", "for", "keyword", "arguments", "." ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/routing/access_list.py#L89-L101
train
38,741
gabstopper/smc-python
smc/administration/tasks.py
Task.update_status
def update_status(self): """ Gets the current status of this task and returns a new task object. :raises TaskRunFailed: fail to update task status """ task = self.make_request( TaskRunFailed, href=self.href) return Task(task)
python
def update_status(self): """ Gets the current status of this task and returns a new task object. :raises TaskRunFailed: fail to update task status """ task = self.make_request( TaskRunFailed, href=self.href) return Task(task)
[ "def", "update_status", "(", "self", ")", ":", "task", "=", "self", ".", "make_request", "(", "TaskRunFailed", ",", "href", "=", "self", ".", "href", ")", "return", "Task", "(", "task", ")" ]
Gets the current status of this task and returns a new task object. :raises TaskRunFailed: fail to update task status
[ "Gets", "the", "current", "status", "of", "this", "task", "and", "returns", "a", "new", "task", "object", "." ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/administration/tasks.py#L146-L157
train
38,742
gabstopper/smc-python
smc/administration/tasks.py
TaskOperationPoller.add_done_callback
def add_done_callback(self, callback): """ Add a callback to run after the task completes. The callable must take 1 argument which will be the completed Task. :param callback: a callable that takes a single argument which will be the completed Task. """ if self._done is None or self._done.is_set(): raise ValueError('Task has already finished') if callable(callback): self.callbacks.append(callback)
python
def add_done_callback(self, callback): """ Add a callback to run after the task completes. The callable must take 1 argument which will be the completed Task. :param callback: a callable that takes a single argument which will be the completed Task. """ if self._done is None or self._done.is_set(): raise ValueError('Task has already finished') if callable(callback): self.callbacks.append(callback)
[ "def", "add_done_callback", "(", "self", ",", "callback", ")", ":", "if", "self", ".", "_done", "is", "None", "or", "self", ".", "_done", ".", "is_set", "(", ")", ":", "raise", "ValueError", "(", "'Task has already finished'", ")", "if", "callable", "(", ...
Add a callback to run after the task completes. The callable must take 1 argument which will be the completed Task. :param callback: a callable that takes a single argument which will be the completed Task.
[ "Add", "a", "callback", "to", "run", "after", "the", "task", "completes", ".", "The", "callable", "must", "take", "1", "argument", "which", "will", "be", "the", "completed", "Task", "." ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/administration/tasks.py#L245-L257
train
38,743
gabstopper/smc-python
smc/administration/tasks.py
TaskOperationPoller.wait
def wait(self, timeout=None): """ Blocking wait for task status. """ if self._thread is None: return self._thread.join(timeout=timeout)
python
def wait(self, timeout=None): """ Blocking wait for task status. """ if self._thread is None: return self._thread.join(timeout=timeout)
[ "def", "wait", "(", "self", ",", "timeout", "=", "None", ")", ":", "if", "self", ".", "_thread", "is", "None", ":", "return", "self", ".", "_thread", ".", "join", "(", "timeout", "=", "timeout", ")" ]
Blocking wait for task status.
[ "Blocking", "wait", "for", "task", "status", "." ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/administration/tasks.py#L268-L274
train
38,744
gabstopper/smc-python
smc/administration/tasks.py
TaskOperationPoller.last_message
def last_message(self, timeout=5): """ Wait a specified amount of time and return the last message from the task :rtype: str """ if self._thread is not None: self._thread.join(timeout=timeout) return self._task.last_message
python
def last_message(self, timeout=5): """ Wait a specified amount of time and return the last message from the task :rtype: str """ if self._thread is not None: self._thread.join(timeout=timeout) return self._task.last_message
[ "def", "last_message", "(", "self", ",", "timeout", "=", "5", ")", ":", "if", "self", ".", "_thread", "is", "not", "None", ":", "self", ".", "_thread", ".", "join", "(", "timeout", "=", "timeout", ")", "return", "self", ".", "_task", ".", "last_messa...
Wait a specified amount of time and return the last message from the task :rtype: str
[ "Wait", "a", "specified", "amount", "of", "time", "and", "return", "the", "last", "message", "from", "the", "task" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/administration/tasks.py#L276-L285
train
38,745
gabstopper/smc-python
smc/administration/tasks.py
TaskOperationPoller.stop
def stop(self): """ Stop the running task """ if self._thread is not None and self._thread.isAlive(): self._done.set()
python
def stop(self): """ Stop the running task """ if self._thread is not None and self._thread.isAlive(): self._done.set()
[ "def", "stop", "(", "self", ")", ":", "if", "self", ".", "_thread", "is", "not", "None", "and", "self", ".", "_thread", ".", "isAlive", "(", ")", ":", "self", ".", "_done", ".", "set", "(", ")" ]
Stop the running task
[ "Stop", "the", "running", "task" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/administration/tasks.py#L304-L309
train
38,746
gabstopper/smc-python
smc/base/util.py
save_to_file
def save_to_file(filename, content): """ Save content to file. Used by node initial contact but can be used anywhere. :param str filename: name of file to save to :param str content: content to save :return: None :raises IOError: permissions issue saving, invalid directory, etc """ import os.path path = os.path.abspath(filename) with open(path, "w") as text_file: text_file.write("{}".format(content))
python
def save_to_file(filename, content): """ Save content to file. Used by node initial contact but can be used anywhere. :param str filename: name of file to save to :param str content: content to save :return: None :raises IOError: permissions issue saving, invalid directory, etc """ import os.path path = os.path.abspath(filename) with open(path, "w") as text_file: text_file.write("{}".format(content))
[ "def", "save_to_file", "(", "filename", ",", "content", ")", ":", "import", "os", ".", "path", "path", "=", "os", ".", "path", ".", "abspath", "(", "filename", ")", "with", "open", "(", "path", ",", "\"w\"", ")", "as", "text_file", ":", "text_file", ...
Save content to file. Used by node initial contact but can be used anywhere. :param str filename: name of file to save to :param str content: content to save :return: None :raises IOError: permissions issue saving, invalid directory, etc
[ "Save", "content", "to", "file", ".", "Used", "by", "node", "initial", "contact", "but", "can", "be", "used", "anywhere", "." ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/base/util.py#L55-L68
train
38,747
gabstopper/smc-python
smc/base/util.py
merge_dicts
def merge_dicts(dict1, dict2, append_lists=False): """ Merge the second dict into the first Not intended to merge list of dicts. :param append_lists: If true, instead of clobbering a list with the new value, append all of the new values onto the original list. """ for key in dict2: if isinstance(dict2[key], dict): if key in dict1 and key in dict2: merge_dicts(dict1[key], dict2[key], append_lists) else: dict1[key] = dict2[key] # If the value is a list and the ``append_lists`` flag is set, # append the new values onto the original list elif isinstance(dict2[key], list) and append_lists: # The value in dict1 must be a list in order to append new # values onto it. Don't add duplicates. if key in dict1 and isinstance(dict1[key], list): dict1[key].extend( [k for k in dict2[key] if k not in dict1[key]]) else: dict1[key] = dict2[key] else: dict1[key] = dict2[key]
python
def merge_dicts(dict1, dict2, append_lists=False): """ Merge the second dict into the first Not intended to merge list of dicts. :param append_lists: If true, instead of clobbering a list with the new value, append all of the new values onto the original list. """ for key in dict2: if isinstance(dict2[key], dict): if key in dict1 and key in dict2: merge_dicts(dict1[key], dict2[key], append_lists) else: dict1[key] = dict2[key] # If the value is a list and the ``append_lists`` flag is set, # append the new values onto the original list elif isinstance(dict2[key], list) and append_lists: # The value in dict1 must be a list in order to append new # values onto it. Don't add duplicates. if key in dict1 and isinstance(dict1[key], list): dict1[key].extend( [k for k in dict2[key] if k not in dict1[key]]) else: dict1[key] = dict2[key] else: dict1[key] = dict2[key]
[ "def", "merge_dicts", "(", "dict1", ",", "dict2", ",", "append_lists", "=", "False", ")", ":", "for", "key", "in", "dict2", ":", "if", "isinstance", "(", "dict2", "[", "key", "]", ",", "dict", ")", ":", "if", "key", "in", "dict1", "and", "key", "in...
Merge the second dict into the first Not intended to merge list of dicts. :param append_lists: If true, instead of clobbering a list with the new value, append all of the new values onto the original list.
[ "Merge", "the", "second", "dict", "into", "the", "first", "Not", "intended", "to", "merge", "list", "of", "dicts", "." ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/base/util.py#L106-L131
train
38,748
gabstopper/smc-python
smc/base/util.py
bytes_to_unicode
def bytes_to_unicode(s, encoding='utf-8', errors='replace'): """ Helper to convert byte string to unicode string for user based input :param str s: string to decode :param str encoding: utf-8 by default :param str errors: what to do when decoding fails :return: unicode utf-8 string """ if compat.PY3: return str(s, 'utf-8') if isinstance(s, bytes) else s return s if isinstance(s, unicode) else s.decode(encoding, errors)
python
def bytes_to_unicode(s, encoding='utf-8', errors='replace'): """ Helper to convert byte string to unicode string for user based input :param str s: string to decode :param str encoding: utf-8 by default :param str errors: what to do when decoding fails :return: unicode utf-8 string """ if compat.PY3: return str(s, 'utf-8') if isinstance(s, bytes) else s return s if isinstance(s, unicode) else s.decode(encoding, errors)
[ "def", "bytes_to_unicode", "(", "s", ",", "encoding", "=", "'utf-8'", ",", "errors", "=", "'replace'", ")", ":", "if", "compat", ".", "PY3", ":", "return", "str", "(", "s", ",", "'utf-8'", ")", "if", "isinstance", "(", "s", ",", "bytes", ")", "else",...
Helper to convert byte string to unicode string for user based input :param str s: string to decode :param str encoding: utf-8 by default :param str errors: what to do when decoding fails :return: unicode utf-8 string
[ "Helper", "to", "convert", "byte", "string", "to", "unicode", "string", "for", "user", "based", "input" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/base/util.py#L159-L170
train
38,749
gabstopper/smc-python
smc/base/collection.py
CollectionManager.iterator
def iterator(self, **kwargs): """ Return an iterator from the collection manager. The iterator can be re-used to chain together filters, each chaining event will be it's own unique element collection. :return: :class:`ElementCollection` """ cls_name = '{0}Collection'.format(self._cls.__name__) collection_cls = type(str(cls_name), (ElementCollection,), {}) params = {'filter_context': self._cls.typeof} params.update(kwargs) return collection_cls(**params)
python
def iterator(self, **kwargs): """ Return an iterator from the collection manager. The iterator can be re-used to chain together filters, each chaining event will be it's own unique element collection. :return: :class:`ElementCollection` """ cls_name = '{0}Collection'.format(self._cls.__name__) collection_cls = type(str(cls_name), (ElementCollection,), {}) params = {'filter_context': self._cls.typeof} params.update(kwargs) return collection_cls(**params)
[ "def", "iterator", "(", "self", ",", "*", "*", "kwargs", ")", ":", "cls_name", "=", "'{0}Collection'", ".", "format", "(", "self", ".", "_cls", ".", "__name__", ")", "collection_cls", "=", "type", "(", "str", "(", "cls_name", ")", ",", "(", "ElementCol...
Return an iterator from the collection manager. The iterator can be re-used to chain together filters, each chaining event will be it's own unique element collection. :return: :class:`ElementCollection`
[ "Return", "an", "iterator", "from", "the", "collection", "manager", ".", "The", "iterator", "can", "be", "re", "-", "used", "to", "chain", "together", "filters", "each", "chaining", "event", "will", "be", "it", "s", "own", "unique", "element", "collection", ...
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/base/collection.py#L654-L667
train
38,750
gabstopper/smc-python
smc/base/collection.py
Search.object_types
def object_types(): """ Show all available 'entry points' available for searching. An entry point defines a uri that provides unfiltered access to all elements of the entry point type. :return: list of entry points by name :rtype: list(str) """ # Return all elements from the root of the API nested under elements URI #element_uri = str( types = [element.rel for element in entry_point()] types.extend(list(CONTEXTS)) return types
python
def object_types(): """ Show all available 'entry points' available for searching. An entry point defines a uri that provides unfiltered access to all elements of the entry point type. :return: list of entry points by name :rtype: list(str) """ # Return all elements from the root of the API nested under elements URI #element_uri = str( types = [element.rel for element in entry_point()] types.extend(list(CONTEXTS)) return types
[ "def", "object_types", "(", ")", ":", "# Return all elements from the root of the API nested under elements URI", "#element_uri = str(", "types", "=", "[", "element", ".", "rel", "for", "element", "in", "entry_point", "(", ")", "]", "types", ".", "extend", "(", "list"...
Show all available 'entry points' available for searching. An entry point defines a uri that provides unfiltered access to all elements of the entry point type. :return: list of entry points by name :rtype: list(str)
[ "Show", "all", "available", "entry", "points", "available", "for", "searching", ".", "An", "entry", "point", "defines", "a", "uri", "that", "provides", "unfiltered", "access", "to", "all", "elements", "of", "the", "entry", "point", "type", "." ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/base/collection.py#L819-L833
train
38,751
gabstopper/smc-python
smc/examples/ospf_routing.py
create_ospf_area_with_message_digest_auth
def create_ospf_area_with_message_digest_auth(): """ If you require message-digest authentication for your OSPFArea, you must create an OSPF key chain configuration. """ OSPFKeyChain.create(name='secure-keychain', key_chain_entry=[{'key': 'fookey', 'key_id': 10, 'send_key': True}]) """ An OSPF interface is applied to a physical interface at the engines routing node level. This configuration is done by an OSPFInterfaceSetting element. To apply the key-chain to this configuration, add the authentication_type of message-digest and reference to the key-chain """ key_chain = OSPFKeyChain('secure-keychain') # obtain resource OSPFInterfaceSetting.create(name='authenicated-ospf', authentication_type='message_digest', key_chain_ref=key_chain.href) """ Create the OSPFArea and assign the above created OSPFInterfaceSetting. In this example, use the default system OSPFInterfaceSetting called 'Default OSPFv2 Interface Settings' """ for profile in describe_ospfv2_interface_settings(): if profile.name.startswith('Default OSPF'): # Use the system default interface_profile = profile.href OSPFArea.create(name='area0', interface_settings_ref=interface_profile, area_id=0)
python
def create_ospf_area_with_message_digest_auth(): """ If you require message-digest authentication for your OSPFArea, you must create an OSPF key chain configuration. """ OSPFKeyChain.create(name='secure-keychain', key_chain_entry=[{'key': 'fookey', 'key_id': 10, 'send_key': True}]) """ An OSPF interface is applied to a physical interface at the engines routing node level. This configuration is done by an OSPFInterfaceSetting element. To apply the key-chain to this configuration, add the authentication_type of message-digest and reference to the key-chain """ key_chain = OSPFKeyChain('secure-keychain') # obtain resource OSPFInterfaceSetting.create(name='authenicated-ospf', authentication_type='message_digest', key_chain_ref=key_chain.href) """ Create the OSPFArea and assign the above created OSPFInterfaceSetting. In this example, use the default system OSPFInterfaceSetting called 'Default OSPFv2 Interface Settings' """ for profile in describe_ospfv2_interface_settings(): if profile.name.startswith('Default OSPF'): # Use the system default interface_profile = profile.href OSPFArea.create(name='area0', interface_settings_ref=interface_profile, area_id=0)
[ "def", "create_ospf_area_with_message_digest_auth", "(", ")", ":", "OSPFKeyChain", ".", "create", "(", "name", "=", "'secure-keychain'", ",", "key_chain_entry", "=", "[", "{", "'key'", ":", "'fookey'", ",", "'key_id'", ":", "10", ",", "'send_key'", ":", "True", ...
If you require message-digest authentication for your OSPFArea, you must create an OSPF key chain configuration.
[ "If", "you", "require", "message", "-", "digest", "authentication", "for", "your", "OSPFArea", "you", "must", "create", "an", "OSPF", "key", "chain", "configuration", "." ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/examples/ospf_routing.py#L25-L57
train
38,752
gabstopper/smc-python
smc/examples/ospf_routing.py
create_ospf_profile
def create_ospf_profile(): """ An OSPF Profile contains administrative distance and redistribution settings. An OSPF Profile is applied at the engine level. When creating an OSPF Profile, you must reference a OSPFDomainSetting. An OSPFDomainSetting holds the settings of the area border router (ABR) type, throttle timer settings, and the max metric router link-state advertisement (LSA) settings. """ OSPFDomainSetting.create(name='custom', abr_type='cisco') ospf_domain = OSPFDomainSetting('custom') # obtain resource ospf_profile = OSPFProfile.create(name='myospfprofile', domain_settings_ref=ospf_domain.href) print(ospf_profile)
python
def create_ospf_profile(): """ An OSPF Profile contains administrative distance and redistribution settings. An OSPF Profile is applied at the engine level. When creating an OSPF Profile, you must reference a OSPFDomainSetting. An OSPFDomainSetting holds the settings of the area border router (ABR) type, throttle timer settings, and the max metric router link-state advertisement (LSA) settings. """ OSPFDomainSetting.create(name='custom', abr_type='cisco') ospf_domain = OSPFDomainSetting('custom') # obtain resource ospf_profile = OSPFProfile.create(name='myospfprofile', domain_settings_ref=ospf_domain.href) print(ospf_profile)
[ "def", "create_ospf_profile", "(", ")", ":", "OSPFDomainSetting", ".", "create", "(", "name", "=", "'custom'", ",", "abr_type", "=", "'cisco'", ")", "ospf_domain", "=", "OSPFDomainSetting", "(", "'custom'", ")", "# obtain resource", "ospf_profile", "=", "OSPFProfi...
An OSPF Profile contains administrative distance and redistribution settings. An OSPF Profile is applied at the engine level. When creating an OSPF Profile, you must reference a OSPFDomainSetting. An OSPFDomainSetting holds the settings of the area border router (ABR) type, throttle timer settings, and the max metric router link-state advertisement (LSA) settings.
[ "An", "OSPF", "Profile", "contains", "administrative", "distance", "and", "redistribution", "settings", ".", "An", "OSPF", "Profile", "is", "applied", "at", "the", "engine", "level", ".", "When", "creating", "an", "OSPF", "Profile", "you", "must", "reference", ...
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/examples/ospf_routing.py#L60-L77
train
38,753
gabstopper/smc-python
smc/core/engine_vss.py
VSSContainer.create
def create(cls, name, vss_def=None): """ Create a VSS Container. This maps to the Service Manager within NSX. vss_def is optional and has the following definition: {"isc_ovf_appliance_model": 'virtual', "isc_ovf_appliance_version": '', "isc_ip_address": '192.168.4.84', # IP of manager, i.e. OSC "isc_vss_id": '', "isc_virtual_connector_name": 'smc-python'} :param str name: name of container :param dict vss_def: dict of optional settings :raises CreateElementFailed: failed creating with reason :rtype: VSSContainer """ vss_def = {} if vss_def is None else vss_def json = { 'master_type': 'dcl2fw', 'name': name, 'vss_isc': vss_def } return ElementCreator(cls, json)
python
def create(cls, name, vss_def=None): """ Create a VSS Container. This maps to the Service Manager within NSX. vss_def is optional and has the following definition: {"isc_ovf_appliance_model": 'virtual', "isc_ovf_appliance_version": '', "isc_ip_address": '192.168.4.84', # IP of manager, i.e. OSC "isc_vss_id": '', "isc_virtual_connector_name": 'smc-python'} :param str name: name of container :param dict vss_def: dict of optional settings :raises CreateElementFailed: failed creating with reason :rtype: VSSContainer """ vss_def = {} if vss_def is None else vss_def json = { 'master_type': 'dcl2fw', 'name': name, 'vss_isc': vss_def } return ElementCreator(cls, json)
[ "def", "create", "(", "cls", ",", "name", ",", "vss_def", "=", "None", ")", ":", "vss_def", "=", "{", "}", "if", "vss_def", "is", "None", "else", "vss_def", "json", "=", "{", "'master_type'", ":", "'dcl2fw'", ",", "'name'", ":", "name", ",", "'vss_is...
Create a VSS Container. This maps to the Service Manager within NSX. vss_def is optional and has the following definition: {"isc_ovf_appliance_model": 'virtual', "isc_ovf_appliance_version": '', "isc_ip_address": '192.168.4.84', # IP of manager, i.e. OSC "isc_vss_id": '', "isc_virtual_connector_name": 'smc-python'} :param str name: name of container :param dict vss_def: dict of optional settings :raises CreateElementFailed: failed creating with reason :rtype: VSSContainer
[ "Create", "a", "VSS", "Container", ".", "This", "maps", "to", "the", "Service", "Manager", "within", "NSX", "." ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/engine_vss.py#L21-L45
train
38,754
gabstopper/smc-python
smc/core/engine_vss.py
VSSContainer.vss_contexts
def vss_contexts(self): """ Return all virtual contexts for this VSS Container. :return list VSSContext """ result = self.make_request( href=fetch_entry_point('visible_virtual_engine_mapping'), params={'filter': self.name}) if result.get('mapping', []): return [Element.from_href(ve) for ve in result['mapping'][0].get('virtual_engine', [])] return []
python
def vss_contexts(self): """ Return all virtual contexts for this VSS Container. :return list VSSContext """ result = self.make_request( href=fetch_entry_point('visible_virtual_engine_mapping'), params={'filter': self.name}) if result.get('mapping', []): return [Element.from_href(ve) for ve in result['mapping'][0].get('virtual_engine', [])] return []
[ "def", "vss_contexts", "(", "self", ")", ":", "result", "=", "self", ".", "make_request", "(", "href", "=", "fetch_entry_point", "(", "'visible_virtual_engine_mapping'", ")", ",", "params", "=", "{", "'filter'", ":", "self", ".", "name", "}", ")", "if", "r...
Return all virtual contexts for this VSS Container. :return list VSSContext
[ "Return", "all", "virtual", "contexts", "for", "this", "VSS", "Container", "." ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/engine_vss.py#L86-L98
train
38,755
gabstopper/smc-python
smc/core/engine_vss.py
VSSContainer.remove_security_group
def remove_security_group(self, name): """ Remove a security group from container """ for group in self.security_groups: if group.isc_name == name: group.delete()
python
def remove_security_group(self, name): """ Remove a security group from container """ for group in self.security_groups: if group.isc_name == name: group.delete()
[ "def", "remove_security_group", "(", "self", ",", "name", ")", ":", "for", "group", "in", "self", ".", "security_groups", ":", "if", "group", ".", "isc_name", "==", "name", ":", "group", ".", "delete", "(", ")" ]
Remove a security group from container
[ "Remove", "a", "security", "group", "from", "container" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/engine_vss.py#L111-L117
train
38,756
gabstopper/smc-python
smc/elements/netlink.py
StaticNetlink.create
def create(cls, name, gateway, network, input_speed=None, output_speed=None, domain_server_address=None, provider_name=None, probe_address=None, standby_mode_period=3600, standby_mode_timeout=30, active_mode_period=5, active_mode_timeout=1, comment=None): """ Create a new StaticNetlink to be used as a traffic handler. :param str name: name of netlink Element :param gateway_ref: gateway to map this netlink to. This can be an element or str href. :type gateway_ref: Router,Engine :param list ref: network/s associated with this netlink. :type ref: list(str,Element) :param int input_speed: input speed in Kbps, used for ratio-based load-balancing :param int output_speed: output speed in Kbps, used for ratio-based load-balancing :param list domain_server_address: dns addresses for netlink. Engine DNS can override this field :type dns_addresses: list(str,Element) :param str provider_name: optional name to identify provider for this netlink :param list probe_address: list of IP addresses to use as probing addresses to validate connectivity :type probe_ip_address: list(str) :param int standby_mode_period: Specifies the probe period when standby mode is used (in seconds) :param int standby_mode_timeout: probe timeout in seconds :param int active_mode_period: Specifies the probe period when active mode is used (in seconds) :param int active_mode_timeout: probe timeout in seconds :raises ElementNotFound: if using type Element parameters that are not found. :raises CreateElementFailed: failure to create netlink with reason :rtype: StaticNetlink .. note:: To monitor the status of the network links, you must define at least one probe IP address. """ json = {'name': name, 'gateway_ref': element_resolver(gateway), 'ref': element_resolver(network), 'input_speed': input_speed, 'output_speed': output_speed, 'probe_address': probe_address, 'nsp_name': provider_name, 'comment': comment, 'standby_mode_period': standby_mode_period, 'standby_mode_timeout': standby_mode_timeout, 'active_mode_period': active_mode_period, 'active_mode_timeout': active_mode_timeout} if domain_server_address: r = RankedDNSAddress([]) r.add(domain_server_address) json.update(domain_server_address=r.entries) return ElementCreator(cls, json)
python
def create(cls, name, gateway, network, input_speed=None, output_speed=None, domain_server_address=None, provider_name=None, probe_address=None, standby_mode_period=3600, standby_mode_timeout=30, active_mode_period=5, active_mode_timeout=1, comment=None): """ Create a new StaticNetlink to be used as a traffic handler. :param str name: name of netlink Element :param gateway_ref: gateway to map this netlink to. This can be an element or str href. :type gateway_ref: Router,Engine :param list ref: network/s associated with this netlink. :type ref: list(str,Element) :param int input_speed: input speed in Kbps, used for ratio-based load-balancing :param int output_speed: output speed in Kbps, used for ratio-based load-balancing :param list domain_server_address: dns addresses for netlink. Engine DNS can override this field :type dns_addresses: list(str,Element) :param str provider_name: optional name to identify provider for this netlink :param list probe_address: list of IP addresses to use as probing addresses to validate connectivity :type probe_ip_address: list(str) :param int standby_mode_period: Specifies the probe period when standby mode is used (in seconds) :param int standby_mode_timeout: probe timeout in seconds :param int active_mode_period: Specifies the probe period when active mode is used (in seconds) :param int active_mode_timeout: probe timeout in seconds :raises ElementNotFound: if using type Element parameters that are not found. :raises CreateElementFailed: failure to create netlink with reason :rtype: StaticNetlink .. note:: To monitor the status of the network links, you must define at least one probe IP address. """ json = {'name': name, 'gateway_ref': element_resolver(gateway), 'ref': element_resolver(network), 'input_speed': input_speed, 'output_speed': output_speed, 'probe_address': probe_address, 'nsp_name': provider_name, 'comment': comment, 'standby_mode_period': standby_mode_period, 'standby_mode_timeout': standby_mode_timeout, 'active_mode_period': active_mode_period, 'active_mode_timeout': active_mode_timeout} if domain_server_address: r = RankedDNSAddress([]) r.add(domain_server_address) json.update(domain_server_address=r.entries) return ElementCreator(cls, json)
[ "def", "create", "(", "cls", ",", "name", ",", "gateway", ",", "network", ",", "input_speed", "=", "None", ",", "output_speed", "=", "None", ",", "domain_server_address", "=", "None", ",", "provider_name", "=", "None", ",", "probe_address", "=", "None", ",...
Create a new StaticNetlink to be used as a traffic handler. :param str name: name of netlink Element :param gateway_ref: gateway to map this netlink to. This can be an element or str href. :type gateway_ref: Router,Engine :param list ref: network/s associated with this netlink. :type ref: list(str,Element) :param int input_speed: input speed in Kbps, used for ratio-based load-balancing :param int output_speed: output speed in Kbps, used for ratio-based load-balancing :param list domain_server_address: dns addresses for netlink. Engine DNS can override this field :type dns_addresses: list(str,Element) :param str provider_name: optional name to identify provider for this netlink :param list probe_address: list of IP addresses to use as probing addresses to validate connectivity :type probe_ip_address: list(str) :param int standby_mode_period: Specifies the probe period when standby mode is used (in seconds) :param int standby_mode_timeout: probe timeout in seconds :param int active_mode_period: Specifies the probe period when active mode is used (in seconds) :param int active_mode_timeout: probe timeout in seconds :raises ElementNotFound: if using type Element parameters that are not found. :raises CreateElementFailed: failure to create netlink with reason :rtype: StaticNetlink .. note:: To monitor the status of the network links, you must define at least one probe IP address.
[ "Create", "a", "new", "StaticNetlink", "to", "be", "used", "as", "a", "traffic", "handler", "." ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/elements/netlink.py#L91-L149
train
38,757
gabstopper/smc-python
smc/elements/netlink.py
DynamicNetlink.create
def create(cls, name, input_speed=None, learn_dns_automatically=True, output_speed=None, provider_name=None, probe_address=None, standby_mode_period=3600, standby_mode_timeout=30, active_mode_period=5, active_mode_timeout=1, comment=None): """ Create a Dynamic Netlink. :param str name: name of netlink Element :param int input_speed: input speed in Kbps, used for ratio-based load-balancing :param int output_speed: output speed in Kbps, used for ratio-based load-balancing :param bool learn_dns_automatically: whether to obtain DNS automatically from the DHCP interface :param str provider_name: optional name to identify provider for this netlink :param list probe_address: list of IP addresses to use as probing addresses to validate connectivity :type probe_ip_address: list(str) :param int standby_mode_period: Specifies the probe period when standby mode is used (in seconds) :param int standby_mode_timeout: probe timeout in seconds :param int active_mode_period: Specifies the probe period when active mode is used (in seconds) :param int active_mode_timeout: probe timeout in seconds :raises CreateElementFailed: failure to create netlink with reason :rtype: DynamicNetlink .. note:: To monitor the status of the network links, you must define at least one probe IP address. """ json = {'name': name, 'input_speed': input_speed, 'output_speed': output_speed, 'probe_address': probe_address, 'nsp_name': provider_name, 'comment': comment, 'standby_mode_period': standby_mode_period, 'standby_mode_timeout': standby_mode_timeout, 'active_mode_period': active_mode_period, 'active_mode_timeout': active_mode_timeout, 'learn_dns_server_automatically': learn_dns_automatically} return ElementCreator(cls, json)
python
def create(cls, name, input_speed=None, learn_dns_automatically=True, output_speed=None, provider_name=None, probe_address=None, standby_mode_period=3600, standby_mode_timeout=30, active_mode_period=5, active_mode_timeout=1, comment=None): """ Create a Dynamic Netlink. :param str name: name of netlink Element :param int input_speed: input speed in Kbps, used for ratio-based load-balancing :param int output_speed: output speed in Kbps, used for ratio-based load-balancing :param bool learn_dns_automatically: whether to obtain DNS automatically from the DHCP interface :param str provider_name: optional name to identify provider for this netlink :param list probe_address: list of IP addresses to use as probing addresses to validate connectivity :type probe_ip_address: list(str) :param int standby_mode_period: Specifies the probe period when standby mode is used (in seconds) :param int standby_mode_timeout: probe timeout in seconds :param int active_mode_period: Specifies the probe period when active mode is used (in seconds) :param int active_mode_timeout: probe timeout in seconds :raises CreateElementFailed: failure to create netlink with reason :rtype: DynamicNetlink .. note:: To monitor the status of the network links, you must define at least one probe IP address. """ json = {'name': name, 'input_speed': input_speed, 'output_speed': output_speed, 'probe_address': probe_address, 'nsp_name': provider_name, 'comment': comment, 'standby_mode_period': standby_mode_period, 'standby_mode_timeout': standby_mode_timeout, 'active_mode_period': active_mode_period, 'active_mode_timeout': active_mode_timeout, 'learn_dns_server_automatically': learn_dns_automatically} return ElementCreator(cls, json)
[ "def", "create", "(", "cls", ",", "name", ",", "input_speed", "=", "None", ",", "learn_dns_automatically", "=", "True", ",", "output_speed", "=", "None", ",", "provider_name", "=", "None", ",", "probe_address", "=", "None", ",", "standby_mode_period", "=", "...
Create a Dynamic Netlink. :param str name: name of netlink Element :param int input_speed: input speed in Kbps, used for ratio-based load-balancing :param int output_speed: output speed in Kbps, used for ratio-based load-balancing :param bool learn_dns_automatically: whether to obtain DNS automatically from the DHCP interface :param str provider_name: optional name to identify provider for this netlink :param list probe_address: list of IP addresses to use as probing addresses to validate connectivity :type probe_ip_address: list(str) :param int standby_mode_period: Specifies the probe period when standby mode is used (in seconds) :param int standby_mode_timeout: probe timeout in seconds :param int active_mode_period: Specifies the probe period when active mode is used (in seconds) :param int active_mode_timeout: probe timeout in seconds :raises CreateElementFailed: failure to create netlink with reason :rtype: DynamicNetlink .. note:: To monitor the status of the network links, you must define at least one probe IP address.
[ "Create", "a", "Dynamic", "Netlink", "." ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/elements/netlink.py#L218-L261
train
38,758
gabstopper/smc-python
smc/api/common.py
fetch_meta_by_name
def fetch_meta_by_name(name, filter_context=None, exact_match=True): """ Find the element based on name and optional filters. By default, the name provided uses the standard filter query. Additional filters can be used based on supported collections in the SMC API. :method: GET :param str name: element name, can use * as wildcard :param str filter_context: further filter request, i.e. 'host', 'group', 'single_fw', 'network_elements', 'services', 'services_and_applications' :param bool exact_match: Do an exact match by name, note this still can return multiple entries :rtype: SMCResult """ result = SMCRequest( params={'filter': name, 'filter_context': filter_context, 'exact_match': exact_match}).read() if not result.json: result.json = [] return result
python
def fetch_meta_by_name(name, filter_context=None, exact_match=True): """ Find the element based on name and optional filters. By default, the name provided uses the standard filter query. Additional filters can be used based on supported collections in the SMC API. :method: GET :param str name: element name, can use * as wildcard :param str filter_context: further filter request, i.e. 'host', 'group', 'single_fw', 'network_elements', 'services', 'services_and_applications' :param bool exact_match: Do an exact match by name, note this still can return multiple entries :rtype: SMCResult """ result = SMCRequest( params={'filter': name, 'filter_context': filter_context, 'exact_match': exact_match}).read() if not result.json: result.json = [] return result
[ "def", "fetch_meta_by_name", "(", "name", ",", "filter_context", "=", "None", ",", "exact_match", "=", "True", ")", ":", "result", "=", "SMCRequest", "(", "params", "=", "{", "'filter'", ":", "name", ",", "'filter_context'", ":", "filter_context", ",", "'exa...
Find the element based on name and optional filters. By default, the name provided uses the standard filter query. Additional filters can be used based on supported collections in the SMC API. :method: GET :param str name: element name, can use * as wildcard :param str filter_context: further filter request, i.e. 'host', 'group', 'single_fw', 'network_elements', 'services', 'services_and_applications' :param bool exact_match: Do an exact match by name, note this still can return multiple entries :rtype: SMCResult
[ "Find", "the", "element", "based", "on", "name", "and", "optional", "filters", ".", "By", "default", "the", "name", "provided", "uses", "the", "standard", "filter", "query", ".", "Additional", "filters", "can", "be", "used", "based", "on", "supported", "coll...
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/api/common.py#L133-L155
train
38,759
gabstopper/smc-python
smc/administration/system.py
System.references_by_element
def references_by_element(self, element_href): """ Return all references to element specified. :param str element_href: element reference :return: list of references where element is used :rtype: list(dict) """ result = self.make_request( method='create', resource='references_by_element', json={ 'value': element_href}) return result
python
def references_by_element(self, element_href): """ Return all references to element specified. :param str element_href: element reference :return: list of references where element is used :rtype: list(dict) """ result = self.make_request( method='create', resource='references_by_element', json={ 'value': element_href}) return result
[ "def", "references_by_element", "(", "self", ",", "element_href", ")", ":", "result", "=", "self", ".", "make_request", "(", "method", "=", "'create'", ",", "resource", "=", "'references_by_element'", ",", "json", "=", "{", "'value'", ":", "element_href", "}",...
Return all references to element specified. :param str element_href: element reference :return: list of references where element is used :rtype: list(dict)
[ "Return", "all", "references", "to", "element", "specified", "." ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/administration/system.py#L256-L269
train
38,760
gabstopper/smc-python
smc/administration/system.py
System.export_elements
def export_elements(self, filename='export_elements.zip', typeof='all'): """ Export elements from SMC. Valid types are: all (All Elements)|nw (Network Elements)|ips (IPS Elements)| sv (Services)|rb (Security Policies)|al (Alerts)| vpn (VPN Elements) :param type: type of element :param filename: Name of file for export :raises TaskRunFailed: failure during export with reason :rtype: DownloadTask """ valid_types = ['all', 'nw', 'ips', 'sv', 'rb', 'al', 'vpn'] if typeof not in valid_types: typeof = 'all' return Task.download(self, 'export_elements', filename, params={'recursive': True, 'type': typeof})
python
def export_elements(self, filename='export_elements.zip', typeof='all'): """ Export elements from SMC. Valid types are: all (All Elements)|nw (Network Elements)|ips (IPS Elements)| sv (Services)|rb (Security Policies)|al (Alerts)| vpn (VPN Elements) :param type: type of element :param filename: Name of file for export :raises TaskRunFailed: failure during export with reason :rtype: DownloadTask """ valid_types = ['all', 'nw', 'ips', 'sv', 'rb', 'al', 'vpn'] if typeof not in valid_types: typeof = 'all' return Task.download(self, 'export_elements', filename, params={'recursive': True, 'type': typeof})
[ "def", "export_elements", "(", "self", ",", "filename", "=", "'export_elements.zip'", ",", "typeof", "=", "'all'", ")", ":", "valid_types", "=", "[", "'all'", ",", "'nw'", ",", "'ips'", ",", "'sv'", ",", "'rb'", ",", "'al'", ",", "'vpn'", "]", "if", "t...
Export elements from SMC. Valid types are: all (All Elements)|nw (Network Elements)|ips (IPS Elements)| sv (Services)|rb (Security Policies)|al (Alerts)| vpn (VPN Elements) :param type: type of element :param filename: Name of file for export :raises TaskRunFailed: failure during export with reason :rtype: DownloadTask
[ "Export", "elements", "from", "SMC", "." ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/administration/system.py#L271-L290
train
38,761
gabstopper/smc-python
smc/administration/certificates/vpn.py
GatewayCertificate._create
def _create(self, common_name, public_key_algorithm='rsa', signature_algorithm='rsa_sha_512', key_length=2048, signing_ca=None): """ Internal method called as a reference from the engine.vpn node """ if signing_ca is None: signing_ca = VPNCertificateCA.objects.filter('Internal RSA').first() cert_auth = element_resolver(signing_ca) return ElementCreator( GatewayCertificate, exception=CertificateError, href=self.internal_gateway.get_relation('generate_certificate'), json={ 'common_name': common_name, 'public_key_algorithm': public_key_algorithm, 'signature_algorithm': signature_algorithm, 'public_key_length': key_length, 'certificate_authority_href': cert_auth})
python
def _create(self, common_name, public_key_algorithm='rsa', signature_algorithm='rsa_sha_512', key_length=2048, signing_ca=None): """ Internal method called as a reference from the engine.vpn node """ if signing_ca is None: signing_ca = VPNCertificateCA.objects.filter('Internal RSA').first() cert_auth = element_resolver(signing_ca) return ElementCreator( GatewayCertificate, exception=CertificateError, href=self.internal_gateway.get_relation('generate_certificate'), json={ 'common_name': common_name, 'public_key_algorithm': public_key_algorithm, 'signature_algorithm': signature_algorithm, 'public_key_length': key_length, 'certificate_authority_href': cert_auth})
[ "def", "_create", "(", "self", ",", "common_name", ",", "public_key_algorithm", "=", "'rsa'", ",", "signature_algorithm", "=", "'rsa_sha_512'", ",", "key_length", "=", "2048", ",", "signing_ca", "=", "None", ")", ":", "if", "signing_ca", "is", "None", ":", "...
Internal method called as a reference from the engine.vpn node
[ "Internal", "method", "called", "as", "a", "reference", "from", "the", "engine", ".", "vpn", "node" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/administration/certificates/vpn.py#L59-L80
train
38,762
gabstopper/smc-python
smc/elements/service.py
TCPService.create
def create(cls, name, min_dst_port, max_dst_port=None, min_src_port=None, max_src_port=None, protocol_agent=None, comment=None): """ Create the TCP service :param str name: name of tcp service :param int min_dst_port: minimum destination port value :param int max_dst_port: maximum destination port value :param int min_src_port: minimum source port value :param int max_src_port: maximum source port value :param str,ProtocolAgent protocol_agent: optional protocol agent for this service :param str comment: optional comment for service :raises CreateElementFailed: failure creating element with reason :return: instance with meta :rtype: TCPService """ max_dst_port = max_dst_port if max_dst_port is not None else '' json = {'name': name, 'min_dst_port': min_dst_port, 'max_dst_port': max_dst_port, 'min_src_port': min_src_port, 'max_src_port': max_src_port, 'protocol_agent_ref': element_resolver(protocol_agent) or None, 'comment': comment} return ElementCreator(cls, json)
python
def create(cls, name, min_dst_port, max_dst_port=None, min_src_port=None, max_src_port=None, protocol_agent=None, comment=None): """ Create the TCP service :param str name: name of tcp service :param int min_dst_port: minimum destination port value :param int max_dst_port: maximum destination port value :param int min_src_port: minimum source port value :param int max_src_port: maximum source port value :param str,ProtocolAgent protocol_agent: optional protocol agent for this service :param str comment: optional comment for service :raises CreateElementFailed: failure creating element with reason :return: instance with meta :rtype: TCPService """ max_dst_port = max_dst_port if max_dst_port is not None else '' json = {'name': name, 'min_dst_port': min_dst_port, 'max_dst_port': max_dst_port, 'min_src_port': min_src_port, 'max_src_port': max_src_port, 'protocol_agent_ref': element_resolver(protocol_agent) or None, 'comment': comment} return ElementCreator(cls, json)
[ "def", "create", "(", "cls", ",", "name", ",", "min_dst_port", ",", "max_dst_port", "=", "None", ",", "min_src_port", "=", "None", ",", "max_src_port", "=", "None", ",", "protocol_agent", "=", "None", ",", "comment", "=", "None", ")", ":", "max_dst_port", ...
Create the TCP service :param str name: name of tcp service :param int min_dst_port: minimum destination port value :param int max_dst_port: maximum destination port value :param int min_src_port: minimum source port value :param int max_src_port: maximum source port value :param str,ProtocolAgent protocol_agent: optional protocol agent for this service :param str comment: optional comment for service :raises CreateElementFailed: failure creating element with reason :return: instance with meta :rtype: TCPService
[ "Create", "the", "TCP", "service" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/elements/service.py#L40-L66
train
38,763
gabstopper/smc-python
smc/elements/service.py
IPService.create
def create(cls, name, protocol_number, protocol_agent=None, comment=None): """ Create the IP Service :param str name: name of ip-service :param int protocol_number: ip proto number for this service :param str,ProtocolAgent protocol_agent: optional protocol agent for this service :param str comment: optional comment :raises CreateElementFailed: failure creating element with reason :return: instance with meta :rtype: IPService """ json = {'name': name, 'protocol_number': protocol_number, 'protocol_agent_ref': element_resolver(protocol_agent) or None, 'comment': comment} return ElementCreator(cls, json)
python
def create(cls, name, protocol_number, protocol_agent=None, comment=None): """ Create the IP Service :param str name: name of ip-service :param int protocol_number: ip proto number for this service :param str,ProtocolAgent protocol_agent: optional protocol agent for this service :param str comment: optional comment :raises CreateElementFailed: failure creating element with reason :return: instance with meta :rtype: IPService """ json = {'name': name, 'protocol_number': protocol_number, 'protocol_agent_ref': element_resolver(protocol_agent) or None, 'comment': comment} return ElementCreator(cls, json)
[ "def", "create", "(", "cls", ",", "name", ",", "protocol_number", ",", "protocol_agent", "=", "None", ",", "comment", "=", "None", ")", ":", "json", "=", "{", "'name'", ":", "name", ",", "'protocol_number'", ":", "protocol_number", ",", "'protocol_agent_ref'...
Create the IP Service :param str name: name of ip-service :param int protocol_number: ip proto number for this service :param str,ProtocolAgent protocol_agent: optional protocol agent for this service :param str comment: optional comment :raises CreateElementFailed: failure creating element with reason :return: instance with meta :rtype: IPService
[ "Create", "the", "IP", "Service" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/elements/service.py#L138-L156
train
38,764
gabstopper/smc-python
smc/elements/service.py
EthernetService.create
def create(cls, name, frame_type='eth2', value1=None, comment=None): """ Create an ethernet service :param str name: name of service :param str frame_type: ethernet frame type, eth2 :param str value1: hex code representing ethertype field :param str comment: optional comment :raises CreateElementFailed: failure creating element with reason :return: instance with meta :rtype: EthernetService """ json = {'frame_type': frame_type, 'name': name, 'value1': int(value1, 16), 'comment': comment} return ElementCreator(cls, json)
python
def create(cls, name, frame_type='eth2', value1=None, comment=None): """ Create an ethernet service :param str name: name of service :param str frame_type: ethernet frame type, eth2 :param str value1: hex code representing ethertype field :param str comment: optional comment :raises CreateElementFailed: failure creating element with reason :return: instance with meta :rtype: EthernetService """ json = {'frame_type': frame_type, 'name': name, 'value1': int(value1, 16), 'comment': comment} return ElementCreator(cls, json)
[ "def", "create", "(", "cls", ",", "name", ",", "frame_type", "=", "'eth2'", ",", "value1", "=", "None", ",", "comment", "=", "None", ")", ":", "json", "=", "{", "'frame_type'", ":", "frame_type", ",", "'name'", ":", "name", ",", "'value1'", ":", "int...
Create an ethernet service :param str name: name of service :param str frame_type: ethernet frame type, eth2 :param str value1: hex code representing ethertype field :param str comment: optional comment :raises CreateElementFailed: failure creating element with reason :return: instance with meta :rtype: EthernetService
[ "Create", "an", "ethernet", "service" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/elements/service.py#L188-L205
train
38,765
gabstopper/smc-python
smc/administration/certificates/tls_common.py
pem_as_string
def pem_as_string(cert): """ Only return False if the certificate is a file path. Otherwise it is a file object or raw string and will need to be fed to the file open context. """ if hasattr(cert, 'read'): # File object - return as is return cert cert = cert.encode('utf-8') if isinstance(cert, unicode) else cert if re.match(_PEM_RE, cert): return True return False
python
def pem_as_string(cert): """ Only return False if the certificate is a file path. Otherwise it is a file object or raw string and will need to be fed to the file open context. """ if hasattr(cert, 'read'): # File object - return as is return cert cert = cert.encode('utf-8') if isinstance(cert, unicode) else cert if re.match(_PEM_RE, cert): return True return False
[ "def", "pem_as_string", "(", "cert", ")", ":", "if", "hasattr", "(", "cert", ",", "'read'", ")", ":", "# File object - return as is", "return", "cert", "cert", "=", "cert", ".", "encode", "(", "'utf-8'", ")", "if", "isinstance", "(", "cert", ",", "unicode"...
Only return False if the certificate is a file path. Otherwise it is a file object or raw string and will need to be fed to the file open context.
[ "Only", "return", "False", "if", "the", "certificate", "is", "a", "file", "path", ".", "Otherwise", "it", "is", "a", "file", "object", "or", "raw", "string", "and", "will", "need", "to", "be", "fed", "to", "the", "file", "open", "context", "." ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/administration/certificates/tls_common.py#L20-L31
train
38,766
gabstopper/smc-python
smc-monitoring/smc_monitoring/wsocket.py
SMCSocketProtocol.send_message
def send_message(self, message): """ Send a message down the socket. The message is expected to have a `request` attribute that holds the message to be serialized and sent. """ if self.connected: self.send( json.dumps(message.request))
python
def send_message(self, message): """ Send a message down the socket. The message is expected to have a `request` attribute that holds the message to be serialized and sent. """ if self.connected: self.send( json.dumps(message.request))
[ "def", "send_message", "(", "self", ",", "message", ")", ":", "if", "self", ".", "connected", ":", "self", ".", "send", "(", "json", ".", "dumps", "(", "message", ".", "request", ")", ")" ]
Send a message down the socket. The message is expected to have a `request` attribute that holds the message to be serialized and sent.
[ "Send", "a", "message", "down", "the", "socket", ".", "The", "message", "is", "expected", "to", "have", "a", "request", "attribute", "that", "holds", "the", "message", "to", "be", "serialized", "and", "sent", "." ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc-monitoring/smc_monitoring/wsocket.py#L153-L161
train
38,767
gabstopper/smc-python
smc-monitoring/smc_monitoring/wsocket.py
SMCSocketProtocol.receive
def receive(self): """ Generator yielding results from the web socket. Results will come as they are received. Even though socket select has a timeout, the SMC will not reply with a message more than every two minutes. """ try: itr = 0 while self.connected: r, w, e = select.select( (self.sock, ), (), (), 10.0) if r: message = json.loads(self.recv()) if 'fetch' in message: self.fetch_id = message['fetch'] if 'failure' in message: raise InvalidFetch(message['failure']) if 'records' in message: if 'added' in message['records']: num = len(message['records']['added']) else: num = len(message['records']) logger.debug('Query returned %s records.', num) if self.max_recv: itr += 1 if 'end' in message: logger.debug('Received end message: %s' % message['end']) yield message break yield message if self.max_recv and self.max_recv <= itr: break except (Exception, KeyboardInterrupt, SystemExit, FetchAborted) as e: logger.info('Caught exception in receive: %s -> %s', type(e), str(e)) if isinstance(e, (SystemExit, InvalidFetch)): # propagate SystemExit, InvalidFetch raise finally: if self.connected: if self.fetch_id: self.send(json.dumps({'abort': self.fetch_id})) self.close() if self.thread: self.event.set() while self.thread.isAlive(): self.event.wait(1) logger.info('Closed web socket connection normally.')
python
def receive(self): """ Generator yielding results from the web socket. Results will come as they are received. Even though socket select has a timeout, the SMC will not reply with a message more than every two minutes. """ try: itr = 0 while self.connected: r, w, e = select.select( (self.sock, ), (), (), 10.0) if r: message = json.loads(self.recv()) if 'fetch' in message: self.fetch_id = message['fetch'] if 'failure' in message: raise InvalidFetch(message['failure']) if 'records' in message: if 'added' in message['records']: num = len(message['records']['added']) else: num = len(message['records']) logger.debug('Query returned %s records.', num) if self.max_recv: itr += 1 if 'end' in message: logger.debug('Received end message: %s' % message['end']) yield message break yield message if self.max_recv and self.max_recv <= itr: break except (Exception, KeyboardInterrupt, SystemExit, FetchAborted) as e: logger.info('Caught exception in receive: %s -> %s', type(e), str(e)) if isinstance(e, (SystemExit, InvalidFetch)): # propagate SystemExit, InvalidFetch raise finally: if self.connected: if self.fetch_id: self.send(json.dumps({'abort': self.fetch_id})) self.close() if self.thread: self.event.set() while self.thread.isAlive(): self.event.wait(1) logger.info('Closed web socket connection normally.')
[ "def", "receive", "(", "self", ")", ":", "try", ":", "itr", "=", "0", "while", "self", ".", "connected", ":", "r", ",", "w", ",", "e", "=", "select", ".", "select", "(", "(", "self", ".", "sock", ",", ")", ",", "(", ")", ",", "(", ")", ",",...
Generator yielding results from the web socket. Results will come as they are received. Even though socket select has a timeout, the SMC will not reply with a message more than every two minutes.
[ "Generator", "yielding", "results", "from", "the", "web", "socket", ".", "Results", "will", "come", "as", "they", "are", "received", ".", "Even", "though", "socket", "select", "has", "a", "timeout", "the", "SMC", "will", "not", "reply", "with", "a", "messa...
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc-monitoring/smc_monitoring/wsocket.py#L170-L228
train
38,768
gabstopper/smc-python
smc/base/model.py
ElementCreator
def ElementCreator(cls, json, **kwargs): """ Helper method for creating elements. If the created element type is a SubElement class type, provide href value as kwargs since that class type does not have a direct entry point. This is a lazy load that will provide only the meta for the element. Additional attribute access will load the full data. :param Element,SubElement cls: class for creating :param dict json: json payload :param SMCException exception: exception class to override :return: instance of type Element with meta :rtype: Element """ if 'exception' not in kwargs: kwargs.update(exception=CreateElementFailed) href = kwargs.pop('href') if 'href' in kwargs else cls.href result = SMCRequest( href=href, json=json, **kwargs).create() element = cls( name=json.get('name'), type=cls.typeof, href=result.href) if result.user_session.in_atomic_block: result.user_session.transactions.append(element) return element
python
def ElementCreator(cls, json, **kwargs): """ Helper method for creating elements. If the created element type is a SubElement class type, provide href value as kwargs since that class type does not have a direct entry point. This is a lazy load that will provide only the meta for the element. Additional attribute access will load the full data. :param Element,SubElement cls: class for creating :param dict json: json payload :param SMCException exception: exception class to override :return: instance of type Element with meta :rtype: Element """ if 'exception' not in kwargs: kwargs.update(exception=CreateElementFailed) href = kwargs.pop('href') if 'href' in kwargs else cls.href result = SMCRequest( href=href, json=json, **kwargs).create() element = cls( name=json.get('name'), type=cls.typeof, href=result.href) if result.user_session.in_atomic_block: result.user_session.transactions.append(element) return element
[ "def", "ElementCreator", "(", "cls", ",", "json", ",", "*", "*", "kwargs", ")", ":", "if", "'exception'", "not", "in", "kwargs", ":", "kwargs", ".", "update", "(", "exception", "=", "CreateElementFailed", ")", "href", "=", "kwargs", ".", "pop", "(", "'...
Helper method for creating elements. If the created element type is a SubElement class type, provide href value as kwargs since that class type does not have a direct entry point. This is a lazy load that will provide only the meta for the element. Additional attribute access will load the full data. :param Element,SubElement cls: class for creating :param dict json: json payload :param SMCException exception: exception class to override :return: instance of type Element with meta :rtype: Element
[ "Helper", "method", "for", "creating", "elements", ".", "If", "the", "created", "element", "type", "is", "a", "SubElement", "class", "type", "provide", "href", "value", "as", "kwargs", "since", "that", "class", "type", "does", "not", "have", "a", "direct", ...
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/base/model.py#L97-L127
train
38,769
gabstopper/smc-python
smc/base/model.py
ElementCache.etag
def etag(self, href): """ ETag can be None if a subset of element json is using this container, such as the case with Routing. """ if self and self._etag is None: self._etag = LoadElement(href, only_etag=True) return self._etag
python
def etag(self, href): """ ETag can be None if a subset of element json is using this container, such as the case with Routing. """ if self and self._etag is None: self._etag = LoadElement(href, only_etag=True) return self._etag
[ "def", "etag", "(", "self", ",", "href", ")", ":", "if", "self", "and", "self", ".", "_etag", "is", "None", ":", "self", ".", "_etag", "=", "LoadElement", "(", "href", ",", "only_etag", "=", "True", ")", "return", "self", ".", "_etag" ]
ETag can be None if a subset of element json is using this container, such as the case with Routing.
[ "ETag", "can", "be", "None", "if", "a", "subset", "of", "element", "json", "is", "using", "this", "container", "such", "as", "the", "case", "with", "Routing", "." ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/base/model.py#L162-L169
train
38,770
gabstopper/smc-python
smc/base/model.py
ElementCache.get_link
def get_link(self, rel): """ Return link for specified resource """ if rel in self.links: return self.links[rel] raise ResourceNotFound('Resource requested: %r is not available ' 'on this element.' % rel)
python
def get_link(self, rel): """ Return link for specified resource """ if rel in self.links: return self.links[rel] raise ResourceNotFound('Resource requested: %r is not available ' 'on this element.' % rel)
[ "def", "get_link", "(", "self", ",", "rel", ")", ":", "if", "rel", "in", "self", ".", "links", ":", "return", "self", ".", "links", "[", "rel", "]", "raise", "ResourceNotFound", "(", "'Resource requested: %r is not available '", "'on this element.'", "%", "rel...
Return link for specified resource
[ "Return", "link", "for", "specified", "resource" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/base/model.py#L181-L188
train
38,771
gabstopper/smc-python
smc/base/model.py
Element.add_category
def add_category(self, category): """ Category Tags are used to characterize an element by a type identifier. They can then be searched and returned as a group of elements. If the category tag specified does not exist, it will be created. This change will take effect immediately. :param list tags: list of category tag names to add to this element :type tags: list(str) :raises ElementNotFound: Category tag element name not found :return: None .. seealso:: :class:`smc.elements.other.Category` """ assert isinstance(category, list), 'Category input was expecting list.' from smc.elements.other import Category for tag in category: category = Category(tag) try: category.add_element(self.href) except ElementNotFound: Category.create(name=tag) category.add_element(self.href)
python
def add_category(self, category): """ Category Tags are used to characterize an element by a type identifier. They can then be searched and returned as a group of elements. If the category tag specified does not exist, it will be created. This change will take effect immediately. :param list tags: list of category tag names to add to this element :type tags: list(str) :raises ElementNotFound: Category tag element name not found :return: None .. seealso:: :class:`smc.elements.other.Category` """ assert isinstance(category, list), 'Category input was expecting list.' from smc.elements.other import Category for tag in category: category = Category(tag) try: category.add_element(self.href) except ElementNotFound: Category.create(name=tag) category.add_element(self.href)
[ "def", "add_category", "(", "self", ",", "category", ")", ":", "assert", "isinstance", "(", "category", ",", "list", ")", ",", "'Category input was expecting list.'", "from", "smc", ".", "elements", ".", "other", "import", "Category", "for", "tag", "in", "cate...
Category Tags are used to characterize an element by a type identifier. They can then be searched and returned as a group of elements. If the category tag specified does not exist, it will be created. This change will take effect immediately. :param list tags: list of category tag names to add to this element :type tags: list(str) :raises ElementNotFound: Category tag element name not found :return: None .. seealso:: :class:`smc.elements.other.Category`
[ "Category", "Tags", "are", "used", "to", "characterize", "an", "element", "by", "a", "type", "identifier", ".", "They", "can", "then", "be", "searched", "and", "returned", "as", "a", "group", "of", "elements", ".", "If", "the", "category", "tag", "specifie...
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/base/model.py#L719-L742
train
38,772
gabstopper/smc-python
smc/base/model.py
Element.export
def export(self, filename='element.zip'): """ Export this element. Usage:: engine = Engine('myfirewall') extask = engine.export(filename='fooexport.zip') while not extask.done(): extask.wait(3) print("Finished download task: %s" % extask.message()) print("File downloaded to: %s" % extask.filename) :param str filename: filename to store exported element :raises TaskRunFailed: invalid permissions, invalid directory, or this element is a system element and cannot be exported. :return: DownloadTask .. note:: It is not possible to export system elements """ from smc.administration.tasks import Task return Task.download(self, 'export', filename)
python
def export(self, filename='element.zip'): """ Export this element. Usage:: engine = Engine('myfirewall') extask = engine.export(filename='fooexport.zip') while not extask.done(): extask.wait(3) print("Finished download task: %s" % extask.message()) print("File downloaded to: %s" % extask.filename) :param str filename: filename to store exported element :raises TaskRunFailed: invalid permissions, invalid directory, or this element is a system element and cannot be exported. :return: DownloadTask .. note:: It is not possible to export system elements """ from smc.administration.tasks import Task return Task.download(self, 'export', filename)
[ "def", "export", "(", "self", ",", "filename", "=", "'element.zip'", ")", ":", "from", "smc", ".", "administration", ".", "tasks", "import", "Task", "return", "Task", ".", "download", "(", "self", ",", "'export'", ",", "filename", ")" ]
Export this element. Usage:: engine = Engine('myfirewall') extask = engine.export(filename='fooexport.zip') while not extask.done(): extask.wait(3) print("Finished download task: %s" % extask.message()) print("File downloaded to: %s" % extask.filename) :param str filename: filename to store exported element :raises TaskRunFailed: invalid permissions, invalid directory, or this element is a system element and cannot be exported. :return: DownloadTask .. note:: It is not possible to export system elements
[ "Export", "this", "element", "." ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/base/model.py#L760-L781
train
38,773
gabstopper/smc-python
smc/base/model.py
Element.referenced_by
def referenced_by(self): """ Show all references for this element. A reference means that this element is being used, for example, in a policy rule, as a member of a group, etc. :return: list referenced elements :rtype: list(Element) """ href = fetch_entry_point('references_by_element') return [Element.from_meta(**ref) for ref in self.make_request( method='create', href=href, json={'value': self.href})]
python
def referenced_by(self): """ Show all references for this element. A reference means that this element is being used, for example, in a policy rule, as a member of a group, etc. :return: list referenced elements :rtype: list(Element) """ href = fetch_entry_point('references_by_element') return [Element.from_meta(**ref) for ref in self.make_request( method='create', href=href, json={'value': self.href})]
[ "def", "referenced_by", "(", "self", ")", ":", "href", "=", "fetch_entry_point", "(", "'references_by_element'", ")", "return", "[", "Element", ".", "from_meta", "(", "*", "*", "ref", ")", "for", "ref", "in", "self", ".", "make_request", "(", "method", "="...
Show all references for this element. A reference means that this element is being used, for example, in a policy rule, as a member of a group, etc. :return: list referenced elements :rtype: list(Element)
[ "Show", "all", "references", "for", "this", "element", ".", "A", "reference", "means", "that", "this", "element", "is", "being", "used", "for", "example", "in", "a", "policy", "rule", "as", "a", "member", "of", "a", "group", "etc", "." ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/base/model.py#L784-L798
train
38,774
gabstopper/smc-python
smc/core/route.py
flush_parent_cache
def flush_parent_cache(node): """ Flush parent cache will recurse back up the tree and wipe the cache from each parent node reference on the given element. This allows the objects to be reused and a clean way to force the object to update itself if attributes or methods are referenced after update. """ if node._parent is None: node._del_cache() return node._del_cache() flush_parent_cache(node._parent)
python
def flush_parent_cache(node): """ Flush parent cache will recurse back up the tree and wipe the cache from each parent node reference on the given element. This allows the objects to be reused and a clean way to force the object to update itself if attributes or methods are referenced after update. """ if node._parent is None: node._del_cache() return node._del_cache() flush_parent_cache(node._parent)
[ "def", "flush_parent_cache", "(", "node", ")", ":", "if", "node", ".", "_parent", "is", "None", ":", "node", ".", "_del_cache", "(", ")", "return", "node", ".", "_del_cache", "(", ")", "flush_parent_cache", "(", "node", ".", "_parent", ")" ]
Flush parent cache will recurse back up the tree and wipe the cache from each parent node reference on the given element. This allows the objects to be reused and a clean way to force the object to update itself if attributes or methods are referenced after update.
[ "Flush", "parent", "cache", "will", "recurse", "back", "up", "the", "tree", "and", "wipe", "the", "cache", "from", "each", "parent", "node", "reference", "on", "the", "given", "element", ".", "This", "allows", "the", "objects", "to", "be", "reused", "and",...
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/route.py#L126-L138
train
38,775
gabstopper/smc-python
smc/core/route.py
route_level
def route_level(root, level): """ Helper method to recurse the current node and return the specified routing node level. """ def recurse(nodes): for node in nodes: if node.level == level: routing_node.append(node) else: recurse(node) routing_node = [] recurse(root) return routing_node
python
def route_level(root, level): """ Helper method to recurse the current node and return the specified routing node level. """ def recurse(nodes): for node in nodes: if node.level == level: routing_node.append(node) else: recurse(node) routing_node = [] recurse(root) return routing_node
[ "def", "route_level", "(", "root", ",", "level", ")", ":", "def", "recurse", "(", "nodes", ")", ":", "for", "node", "in", "nodes", ":", "if", "node", ".", "level", "==", "level", ":", "routing_node", ".", "append", "(", "node", ")", "else", ":", "r...
Helper method to recurse the current node and return the specified routing node level.
[ "Helper", "method", "to", "recurse", "the", "current", "node", "and", "return", "the", "specified", "routing", "node", "level", "." ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/route.py#L857-L871
train
38,776
gabstopper/smc-python
smc/core/route.py
RoutingTree.get
def get(self, interface_id): """ Obtain routing configuration for a specific interface by ID. .. note:: If interface is a VLAN, you must use a str to specify the interface id, such as '3.13' (interface 3, VLAN 13) :param str,int interface_id: interface identifier :raises InterfaceNotFound: invalid interface for engine :return: Routing element, or None if not found :rtype: Routing """ for interface in self: if interface.nicid == str(interface_id) or \ interface.dynamic_nicid == str(interface_id): return interface raise InterfaceNotFound('Specified interface {} does not exist on ' 'this engine.'.format(interface_id))
python
def get(self, interface_id): """ Obtain routing configuration for a specific interface by ID. .. note:: If interface is a VLAN, you must use a str to specify the interface id, such as '3.13' (interface 3, VLAN 13) :param str,int interface_id: interface identifier :raises InterfaceNotFound: invalid interface for engine :return: Routing element, or None if not found :rtype: Routing """ for interface in self: if interface.nicid == str(interface_id) or \ interface.dynamic_nicid == str(interface_id): return interface raise InterfaceNotFound('Specified interface {} does not exist on ' 'this engine.'.format(interface_id))
[ "def", "get", "(", "self", ",", "interface_id", ")", ":", "for", "interface", "in", "self", ":", "if", "interface", ".", "nicid", "==", "str", "(", "interface_id", ")", "or", "interface", ".", "dynamic_nicid", "==", "str", "(", "interface_id", ")", ":", ...
Obtain routing configuration for a specific interface by ID. .. note:: If interface is a VLAN, you must use a str to specify the interface id, such as '3.13' (interface 3, VLAN 13) :param str,int interface_id: interface identifier :raises InterfaceNotFound: invalid interface for engine :return: Routing element, or None if not found :rtype: Routing
[ "Obtain", "routing", "configuration", "for", "a", "specific", "interface", "by", "ID", "." ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/route.py#L242-L261
train
38,777
gabstopper/smc-python
smc/core/route.py
Routing.add_ospf_area
def add_ospf_area(self, ospf_area, ospf_interface_setting=None, network=None, communication_mode='NOT_FORCED', unicast_ref=None): """ Add OSPF Area to this routing node. Communication mode specifies how the interface will interact with the adjacent OSPF environment. Please see SMC API documentation for more in depth information on each option. If the interface has multiple networks nested below, all networks will receive the OSPF area by default unless the ``network`` parameter is specified. OSPF cannot be applied to IPv6 networks. Example of adding an area to interface routing node:: area = OSPFArea('area0') #obtain area resource #Set on routing interface 0 interface = engine.routing.get(0) interface.add_ospf_area(area) .. note:: If UNICAST is specified, you must also provide a unicast_ref of element type Host to identify the remote host. If no unicast_ref is provided, this is skipped :param OSPFArea ospf_area: OSPF area instance or href :param OSPFInterfaceSetting ospf_interface_setting: used to override the OSPF settings for this interface (optional) :param str network: if network specified, only add OSPF to this network on interface :param str communication_mode: NOT_FORCED|POINT_TO_POINT|PASSIVE|UNICAST :param Element unicast_ref: Element used as unicast gw (required for UNICAST) :raises ModificationAborted: Change must be made at the interface level :raises UpdateElementFailed: failure updating routing :raises ElementNotFound: ospf area not found :return: Status of whether the route table was updated :rtype: bool """ communication_mode = communication_mode.upper() destinations=[] if not ospf_interface_setting else [ospf_interface_setting] if communication_mode == 'UNICAST' and unicast_ref: destinations.append(unicast_ref) routing_node_gateway = RoutingNodeGateway( ospf_area, communication_mode=communication_mode, destinations=destinations) return self._add_gateway_node('ospfv2_area', routing_node_gateway, network)
python
def add_ospf_area(self, ospf_area, ospf_interface_setting=None, network=None, communication_mode='NOT_FORCED', unicast_ref=None): """ Add OSPF Area to this routing node. Communication mode specifies how the interface will interact with the adjacent OSPF environment. Please see SMC API documentation for more in depth information on each option. If the interface has multiple networks nested below, all networks will receive the OSPF area by default unless the ``network`` parameter is specified. OSPF cannot be applied to IPv6 networks. Example of adding an area to interface routing node:: area = OSPFArea('area0') #obtain area resource #Set on routing interface 0 interface = engine.routing.get(0) interface.add_ospf_area(area) .. note:: If UNICAST is specified, you must also provide a unicast_ref of element type Host to identify the remote host. If no unicast_ref is provided, this is skipped :param OSPFArea ospf_area: OSPF area instance or href :param OSPFInterfaceSetting ospf_interface_setting: used to override the OSPF settings for this interface (optional) :param str network: if network specified, only add OSPF to this network on interface :param str communication_mode: NOT_FORCED|POINT_TO_POINT|PASSIVE|UNICAST :param Element unicast_ref: Element used as unicast gw (required for UNICAST) :raises ModificationAborted: Change must be made at the interface level :raises UpdateElementFailed: failure updating routing :raises ElementNotFound: ospf area not found :return: Status of whether the route table was updated :rtype: bool """ communication_mode = communication_mode.upper() destinations=[] if not ospf_interface_setting else [ospf_interface_setting] if communication_mode == 'UNICAST' and unicast_ref: destinations.append(unicast_ref) routing_node_gateway = RoutingNodeGateway( ospf_area, communication_mode=communication_mode, destinations=destinations) return self._add_gateway_node('ospfv2_area', routing_node_gateway, network)
[ "def", "add_ospf_area", "(", "self", ",", "ospf_area", ",", "ospf_interface_setting", "=", "None", ",", "network", "=", "None", ",", "communication_mode", "=", "'NOT_FORCED'", ",", "unicast_ref", "=", "None", ")", ":", "communication_mode", "=", "communication_mod...
Add OSPF Area to this routing node. Communication mode specifies how the interface will interact with the adjacent OSPF environment. Please see SMC API documentation for more in depth information on each option. If the interface has multiple networks nested below, all networks will receive the OSPF area by default unless the ``network`` parameter is specified. OSPF cannot be applied to IPv6 networks. Example of adding an area to interface routing node:: area = OSPFArea('area0') #obtain area resource #Set on routing interface 0 interface = engine.routing.get(0) interface.add_ospf_area(area) .. note:: If UNICAST is specified, you must also provide a unicast_ref of element type Host to identify the remote host. If no unicast_ref is provided, this is skipped :param OSPFArea ospf_area: OSPF area instance or href :param OSPFInterfaceSetting ospf_interface_setting: used to override the OSPF settings for this interface (optional) :param str network: if network specified, only add OSPF to this network on interface :param str communication_mode: NOT_FORCED|POINT_TO_POINT|PASSIVE|UNICAST :param Element unicast_ref: Element used as unicast gw (required for UNICAST) :raises ModificationAborted: Change must be made at the interface level :raises UpdateElementFailed: failure updating routing :raises ElementNotFound: ospf area not found :return: Status of whether the route table was updated :rtype: bool
[ "Add", "OSPF", "Area", "to", "this", "routing", "node", "." ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/route.py#L428-L473
train
38,778
gabstopper/smc-python
smc/elements/network.py
Host.create
def create(cls, name, address=None, ipv6_address=None, secondary=None, comment=None): """ Create the host element :param str name: Name of element :param str address: ipv4 address of host object (optional if ipv6) :param str ipv6_address: ipv6 address (optional if ipv4) :param list secondary: secondary ip addresses (optional) :param str comment: comment (optional) :raises CreateElementFailed: element creation failed with reason :return: instance with meta :rtype: Host .. note:: Either ipv4 or ipv6 address is required """ address = address if address else None ipv6_address = ipv6_address if ipv6_address else None secondaries = [] if secondary is None else secondary json = {'name': name, 'address': address, 'ipv6_address': ipv6_address, 'secondary': secondaries, 'comment': comment} return ElementCreator(cls, json)
python
def create(cls, name, address=None, ipv6_address=None, secondary=None, comment=None): """ Create the host element :param str name: Name of element :param str address: ipv4 address of host object (optional if ipv6) :param str ipv6_address: ipv6 address (optional if ipv4) :param list secondary: secondary ip addresses (optional) :param str comment: comment (optional) :raises CreateElementFailed: element creation failed with reason :return: instance with meta :rtype: Host .. note:: Either ipv4 or ipv6 address is required """ address = address if address else None ipv6_address = ipv6_address if ipv6_address else None secondaries = [] if secondary is None else secondary json = {'name': name, 'address': address, 'ipv6_address': ipv6_address, 'secondary': secondaries, 'comment': comment} return ElementCreator(cls, json)
[ "def", "create", "(", "cls", ",", "name", ",", "address", "=", "None", ",", "ipv6_address", "=", "None", ",", "secondary", "=", "None", ",", "comment", "=", "None", ")", ":", "address", "=", "address", "if", "address", "else", "None", "ipv6_address", "...
Create the host element :param str name: Name of element :param str address: ipv4 address of host object (optional if ipv6) :param str ipv6_address: ipv6 address (optional if ipv4) :param list secondary: secondary ip addresses (optional) :param str comment: comment (optional) :raises CreateElementFailed: element creation failed with reason :return: instance with meta :rtype: Host .. note:: Either ipv4 or ipv6 address is required
[ "Create", "the", "host", "element" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/elements/network.py#L35-L60
train
38,779
gabstopper/smc-python
smc/elements/network.py
AddressRange.create
def create(cls, name, ip_range, comment=None): """ Create an AddressRange element :param str name: Name of element :param str iprange: iprange of element :param str comment: comment (optional) :raises CreateElementFailed: element creation failed with reason :return: instance with meta :rtype: AddressRange """ json = {'name': name, 'ip_range': ip_range, 'comment': comment} return ElementCreator(cls, json)
python
def create(cls, name, ip_range, comment=None): """ Create an AddressRange element :param str name: Name of element :param str iprange: iprange of element :param str comment: comment (optional) :raises CreateElementFailed: element creation failed with reason :return: instance with meta :rtype: AddressRange """ json = {'name': name, 'ip_range': ip_range, 'comment': comment} return ElementCreator(cls, json)
[ "def", "create", "(", "cls", ",", "name", ",", "ip_range", ",", "comment", "=", "None", ")", ":", "json", "=", "{", "'name'", ":", "name", ",", "'ip_range'", ":", "ip_range", ",", "'comment'", ":", "comment", "}", "return", "ElementCreator", "(", "cls"...
Create an AddressRange element :param str name: Name of element :param str iprange: iprange of element :param str comment: comment (optional) :raises CreateElementFailed: element creation failed with reason :return: instance with meta :rtype: AddressRange
[ "Create", "an", "AddressRange", "element" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/elements/network.py#L92-L107
train
38,780
gabstopper/smc-python
smc/elements/network.py
Network.create
def create(cls, name, ipv4_network=None, ipv6_network=None, comment=None): """ Create the network element :param str name: Name of element :param str ipv4_network: network cidr (optional if ipv6) :param str ipv6_network: network cidr (optional if ipv4) :param str comment: comment (optional) :raises CreateElementFailed: element creation failed with reason :return: instance with meta :rtype: Network .. note:: Either an ipv4_network or ipv6_network must be specified """ ipv4_network = ipv4_network if ipv4_network else None ipv6_network = ipv6_network if ipv6_network else None json = {'name': name, 'ipv4_network': ipv4_network, 'ipv6_network': ipv6_network, 'comment': comment} return ElementCreator(cls, json)
python
def create(cls, name, ipv4_network=None, ipv6_network=None, comment=None): """ Create the network element :param str name: Name of element :param str ipv4_network: network cidr (optional if ipv6) :param str ipv6_network: network cidr (optional if ipv4) :param str comment: comment (optional) :raises CreateElementFailed: element creation failed with reason :return: instance with meta :rtype: Network .. note:: Either an ipv4_network or ipv6_network must be specified """ ipv4_network = ipv4_network if ipv4_network else None ipv6_network = ipv6_network if ipv6_network else None json = {'name': name, 'ipv4_network': ipv4_network, 'ipv6_network': ipv6_network, 'comment': comment} return ElementCreator(cls, json)
[ "def", "create", "(", "cls", ",", "name", ",", "ipv4_network", "=", "None", ",", "ipv6_network", "=", "None", ",", "comment", "=", "None", ")", ":", "ipv4_network", "=", "ipv4_network", "if", "ipv4_network", "else", "None", "ipv6_network", "=", "ipv6_network...
Create the network element :param str name: Name of element :param str ipv4_network: network cidr (optional if ipv6) :param str ipv6_network: network cidr (optional if ipv4) :param str comment: comment (optional) :raises CreateElementFailed: element creation failed with reason :return: instance with meta :rtype: Network .. note:: Either an ipv4_network or ipv6_network must be specified
[ "Create", "the", "network", "element" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/elements/network.py#L186-L208
train
38,781
gabstopper/smc-python
smc/elements/network.py
Expression.create
def create(cls, name, ne_ref=None, operator='exclusion', sub_expression=None, comment=None): """ Create the expression :param str name: name of expression :param list ne_ref: network element references for expression :param str operator: 'exclusion' (negation), 'union', 'intersection' (default: exclusion) :param dict sub_expression: sub expression used :param str comment: optional comment :raises CreateElementFailed: element creation failed with reason :return: instance with meta :rtype: Expression """ sub_expression = [] if sub_expression is None else [sub_expression] json = {'name': name, 'operator': operator, 'ne_ref': ne_ref, 'sub_expression': sub_expression, 'comment': comment} return ElementCreator(cls, json)
python
def create(cls, name, ne_ref=None, operator='exclusion', sub_expression=None, comment=None): """ Create the expression :param str name: name of expression :param list ne_ref: network element references for expression :param str operator: 'exclusion' (negation), 'union', 'intersection' (default: exclusion) :param dict sub_expression: sub expression used :param str comment: optional comment :raises CreateElementFailed: element creation failed with reason :return: instance with meta :rtype: Expression """ sub_expression = [] if sub_expression is None else [sub_expression] json = {'name': name, 'operator': operator, 'ne_ref': ne_ref, 'sub_expression': sub_expression, 'comment': comment} return ElementCreator(cls, json)
[ "def", "create", "(", "cls", ",", "name", ",", "ne_ref", "=", "None", ",", "operator", "=", "'exclusion'", ",", "sub_expression", "=", "None", ",", "comment", "=", "None", ")", ":", "sub_expression", "=", "[", "]", "if", "sub_expression", "is", "None", ...
Create the expression :param str name: name of expression :param list ne_ref: network element references for expression :param str operator: 'exclusion' (negation), 'union', 'intersection' (default: exclusion) :param dict sub_expression: sub expression used :param str comment: optional comment :raises CreateElementFailed: element creation failed with reason :return: instance with meta :rtype: Expression
[ "Create", "the", "expression" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/elements/network.py#L283-L305
train
38,782
gabstopper/smc-python
smc/elements/network.py
IPList.download
def download(self, filename=None, as_type='zip'): """ Download the IPList. List format can be either zip, text or json. For large lists, it is recommended to use zip encoding. Filename is required for zip downloads. :param str filename: Name of file to save to (required for zip) :param str as_type: type of format to download in: txt,json,zip (default: zip) :raises IOError: problem writing to destination filename :return: None """ headers = None if as_type in ['zip', 'txt', 'json']: if as_type == 'zip': if filename is None: raise MissingRequiredInput('Filename must be specified when ' 'downloading IPList as a zip file.') filename = '{}'.format(filename) elif as_type == 'txt': headers = {'accept': 'text/plain'} elif as_type == 'json': headers = {'accept': 'application/json'} result = self.make_request( FetchElementFailed, raw_result=True, resource='ip_address_list', filename=filename, headers=headers) return result.json if as_type == 'json' else result.content
python
def download(self, filename=None, as_type='zip'): """ Download the IPList. List format can be either zip, text or json. For large lists, it is recommended to use zip encoding. Filename is required for zip downloads. :param str filename: Name of file to save to (required for zip) :param str as_type: type of format to download in: txt,json,zip (default: zip) :raises IOError: problem writing to destination filename :return: None """ headers = None if as_type in ['zip', 'txt', 'json']: if as_type == 'zip': if filename is None: raise MissingRequiredInput('Filename must be specified when ' 'downloading IPList as a zip file.') filename = '{}'.format(filename) elif as_type == 'txt': headers = {'accept': 'text/plain'} elif as_type == 'json': headers = {'accept': 'application/json'} result = self.make_request( FetchElementFailed, raw_result=True, resource='ip_address_list', filename=filename, headers=headers) return result.json if as_type == 'json' else result.content
[ "def", "download", "(", "self", ",", "filename", "=", "None", ",", "as_type", "=", "'zip'", ")", ":", "headers", "=", "None", "if", "as_type", "in", "[", "'zip'", ",", "'txt'", ",", "'json'", "]", ":", "if", "as_type", "==", "'zip'", ":", "if", "fi...
Download the IPList. List format can be either zip, text or json. For large lists, it is recommended to use zip encoding. Filename is required for zip downloads. :param str filename: Name of file to save to (required for zip) :param str as_type: type of format to download in: txt,json,zip (default: zip) :raises IOError: problem writing to destination filename :return: None
[ "Download", "the", "IPList", ".", "List", "format", "can", "be", "either", "zip", "text", "or", "json", ".", "For", "large", "lists", "it", "is", "recommended", "to", "use", "zip", "encoding", ".", "Filename", "is", "required", "for", "zip", "downloads", ...
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/elements/network.py#L391-L421
train
38,783
gabstopper/smc-python
smc/elements/network.py
IPList.upload
def upload(self, filename=None, json=None, as_type='zip'): """ Upload an IPList to the SMC. The contents of the upload are not incremental to what is in the existing IPList. So if the intent is to add new entries, you should first retrieve the existing and append to the content, then upload. The only upload type that can be done without loading a file as the source is as_type='json'. :param str filename: required for zip/txt uploads :param str json: required for json uploads :param str as_type: type of format to upload in: txt|json|zip (default) :raises IOError: filename specified cannot be loaded :raises CreateElementFailed: element creation failed with reason :return: None """ headers = {'content-type': 'multipart/form-data'} params = None files = None if filename: files = {'ip_addresses': open(filename, 'rb')} if as_type == 'json': headers = {'accept': 'application/json', 'content-type': 'application/json'} elif as_type == 'txt': params = {'format': 'txt'} self.make_request( CreateElementFailed, method='create', resource='ip_address_list', headers=headers, files=files, json=json, params=params)
python
def upload(self, filename=None, json=None, as_type='zip'): """ Upload an IPList to the SMC. The contents of the upload are not incremental to what is in the existing IPList. So if the intent is to add new entries, you should first retrieve the existing and append to the content, then upload. The only upload type that can be done without loading a file as the source is as_type='json'. :param str filename: required for zip/txt uploads :param str json: required for json uploads :param str as_type: type of format to upload in: txt|json|zip (default) :raises IOError: filename specified cannot be loaded :raises CreateElementFailed: element creation failed with reason :return: None """ headers = {'content-type': 'multipart/form-data'} params = None files = None if filename: files = {'ip_addresses': open(filename, 'rb')} if as_type == 'json': headers = {'accept': 'application/json', 'content-type': 'application/json'} elif as_type == 'txt': params = {'format': 'txt'} self.make_request( CreateElementFailed, method='create', resource='ip_address_list', headers=headers, files=files, json=json, params=params)
[ "def", "upload", "(", "self", ",", "filename", "=", "None", ",", "json", "=", "None", ",", "as_type", "=", "'zip'", ")", ":", "headers", "=", "{", "'content-type'", ":", "'multipart/form-data'", "}", "params", "=", "None", "files", "=", "None", "if", "...
Upload an IPList to the SMC. The contents of the upload are not incremental to what is in the existing IPList. So if the intent is to add new entries, you should first retrieve the existing and append to the content, then upload. The only upload type that can be done without loading a file as the source is as_type='json'. :param str filename: required for zip/txt uploads :param str json: required for json uploads :param str as_type: type of format to upload in: txt|json|zip (default) :raises IOError: filename specified cannot be loaded :raises CreateElementFailed: element creation failed with reason :return: None
[ "Upload", "an", "IPList", "to", "the", "SMC", ".", "The", "contents", "of", "the", "upload", "are", "not", "incremental", "to", "what", "is", "in", "the", "existing", "IPList", ".", "So", "if", "the", "intent", "is", "to", "add", "new", "entries", "you...
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/elements/network.py#L423-L455
train
38,784
gabstopper/smc-python
smc/elements/network.py
Alias.resolve
def resolve(self, engine): """ Resolve this Alias to a specific value. Specify the engine by name to find it's value. :: alias = Alias('$$ Interface ID 0.ip') alias.resolve('smcpython-fw') :param str engine: name of engine to resolve value :raises ElementNotFound: if alias not found on engine :return: alias resolving values :rtype: list """ if not self.resolved_value: result = self.make_request( ElementNotFound, href=self.get_relation('resolve'), params={'for': engine}) self.resolved_value = result.get('resolved_value') return self.resolved_value
python
def resolve(self, engine): """ Resolve this Alias to a specific value. Specify the engine by name to find it's value. :: alias = Alias('$$ Interface ID 0.ip') alias.resolve('smcpython-fw') :param str engine: name of engine to resolve value :raises ElementNotFound: if alias not found on engine :return: alias resolving values :rtype: list """ if not self.resolved_value: result = self.make_request( ElementNotFound, href=self.get_relation('resolve'), params={'for': engine}) self.resolved_value = result.get('resolved_value') return self.resolved_value
[ "def", "resolve", "(", "self", ",", "engine", ")", ":", "if", "not", "self", ".", "resolved_value", ":", "result", "=", "self", ".", "make_request", "(", "ElementNotFound", ",", "href", "=", "self", ".", "get_relation", "(", "'resolve'", ")", ",", "param...
Resolve this Alias to a specific value. Specify the engine by name to find it's value. :: alias = Alias('$$ Interface ID 0.ip') alias.resolve('smcpython-fw') :param str engine: name of engine to resolve value :raises ElementNotFound: if alias not found on engine :return: alias resolving values :rtype: list
[ "Resolve", "this", "Alias", "to", "a", "specific", "value", ".", "Specify", "the", "engine", "by", "name", "to", "find", "it", "s", "value", "." ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/elements/network.py#L707-L729
train
38,785
gabstopper/smc-python
smc/policy/rule.py
Rule.name
def name(self): """ Name attribute of rule element """ return self._meta.name if self._meta.name else \ 'Rule @%s' % self.tag
python
def name(self): """ Name attribute of rule element """ return self._meta.name if self._meta.name else \ 'Rule @%s' % self.tag
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_meta", ".", "name", "if", "self", ".", "_meta", ".", "name", "else", "'Rule @%s'", "%", "self", ".", "tag" ]
Name attribute of rule element
[ "Name", "attribute", "of", "rule", "element" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/policy/rule.py#L93-L98
train
38,786
gabstopper/smc-python
smc/policy/rule.py
IPv4Rule.create
def create(self, name, sources=None, destinations=None, services=None, action='allow', log_options=None, authentication_options=None, connection_tracking=None, is_disabled=False, vpn_policy=None, mobile_vpn=False, add_pos=None, after=None, before=None, sub_policy=None, comment=None, **kw): """ Create a layer 3 firewall rule :param str name: name of rule :param sources: source/s for rule :type sources: list[str, Element] :param destinations: destination/s for rule :type destinations: list[str, Element] :param services: service/s for rule :type services: list[str, Element] :param action: allow,continue,discard,refuse,enforce_vpn, apply_vpn,forward_vpn, blacklist (default: allow) :type action: Action or str :param LogOptions log_options: LogOptions object :param ConnectionTracking connection_tracking: custom connection tracking settings :param AuthenticationOptions authentication_options: options for auth if any :param PolicyVPN,str vpn_policy: policy element or str href; required for enforce_vpn, use_vpn and apply_vpn actions :param bool mobile_vpn: if using a vpn action, you can set mobile_vpn to True and omit the vpn_policy setting if you want this VPN to apply to any mobile VPN based on the policy VPN associated with the engine :param str,Element sub_policy: sub policy required when rule has an action of 'jump'. Can be the FirewallSubPolicy element or href. :param int add_pos: position to insert the rule, starting with position 1. If the position value is greater than the number of rules, the rule is inserted at the bottom. If add_pos is not provided, rule is inserted in position 1. Mutually exclusive with ``after`` and ``before`` params. :param str after: Rule tag to add this rule after. Mutually exclusive with ``add_pos`` and ``before`` params. :param str before: Rule tag to add this rule before. Mutually exclusive with ``add_pos`` and ``after`` params. :param str comment: optional comment for this rule :raises MissingRequiredInput: when options are specified the need additional setting, i.e. use_vpn action requires a vpn policy be specified. :raises CreateRuleFailed: rule creation failure :return: the created ipv4 rule :rtype: IPv4Rule """ rule_values = self.update_targets(sources, destinations, services) rule_values.update(name=name, comment=comment) if isinstance(action, Action): rule_action = action else: rule_action = Action() rule_action.action = action if not rule_action.action in self._actions: raise CreateRuleFailed('Action specified is not valid for this ' 'rule type; action: {}'.format(rule_action.action)) if rule_action.action in ('apply_vpn', 'enforce_vpn', 'forward_vpn'): if vpn_policy is None and not mobile_vpn: raise MissingRequiredInput('You must either specify a vpn_policy or set ' 'mobile_vpn when using a rule with a VPN action') if mobile_vpn: rule_action.mobile_vpn = True else: try: vpn = element_resolver(vpn_policy) # VPNPolicy rule_action.vpn = vpn except ElementNotFound: raise MissingRequiredInput('Cannot find VPN policy specified: {}, ' .format(vpn_policy)) elif rule_action.action == 'jump': try: rule_action.sub_policy = element_resolver(sub_policy) except ElementNotFound: raise MissingRequiredInput('Cannot find sub policy specified: {} ' .format(sub_policy)) #rule_values.update(action=rule_action.data) log_options = LogOptions() if not log_options else log_options if connection_tracking is not None: rule_action.connection_tracking_options.update(**connection_tracking) auth_options = AuthenticationOptions() if not authentication_options \ else authentication_options rule_values.update( action=rule_action.data, options=log_options.data, authentication_options=auth_options.data, is_disabled=is_disabled) params = None href = self.href if add_pos is not None: href = self.add_at_position(add_pos) elif before or after: params = self.add_before_after(before, after) return ElementCreator( self.__class__, exception=CreateRuleFailed, href=href, params=params, json=rule_values)
python
def create(self, name, sources=None, destinations=None, services=None, action='allow', log_options=None, authentication_options=None, connection_tracking=None, is_disabled=False, vpn_policy=None, mobile_vpn=False, add_pos=None, after=None, before=None, sub_policy=None, comment=None, **kw): """ Create a layer 3 firewall rule :param str name: name of rule :param sources: source/s for rule :type sources: list[str, Element] :param destinations: destination/s for rule :type destinations: list[str, Element] :param services: service/s for rule :type services: list[str, Element] :param action: allow,continue,discard,refuse,enforce_vpn, apply_vpn,forward_vpn, blacklist (default: allow) :type action: Action or str :param LogOptions log_options: LogOptions object :param ConnectionTracking connection_tracking: custom connection tracking settings :param AuthenticationOptions authentication_options: options for auth if any :param PolicyVPN,str vpn_policy: policy element or str href; required for enforce_vpn, use_vpn and apply_vpn actions :param bool mobile_vpn: if using a vpn action, you can set mobile_vpn to True and omit the vpn_policy setting if you want this VPN to apply to any mobile VPN based on the policy VPN associated with the engine :param str,Element sub_policy: sub policy required when rule has an action of 'jump'. Can be the FirewallSubPolicy element or href. :param int add_pos: position to insert the rule, starting with position 1. If the position value is greater than the number of rules, the rule is inserted at the bottom. If add_pos is not provided, rule is inserted in position 1. Mutually exclusive with ``after`` and ``before`` params. :param str after: Rule tag to add this rule after. Mutually exclusive with ``add_pos`` and ``before`` params. :param str before: Rule tag to add this rule before. Mutually exclusive with ``add_pos`` and ``after`` params. :param str comment: optional comment for this rule :raises MissingRequiredInput: when options are specified the need additional setting, i.e. use_vpn action requires a vpn policy be specified. :raises CreateRuleFailed: rule creation failure :return: the created ipv4 rule :rtype: IPv4Rule """ rule_values = self.update_targets(sources, destinations, services) rule_values.update(name=name, comment=comment) if isinstance(action, Action): rule_action = action else: rule_action = Action() rule_action.action = action if not rule_action.action in self._actions: raise CreateRuleFailed('Action specified is not valid for this ' 'rule type; action: {}'.format(rule_action.action)) if rule_action.action in ('apply_vpn', 'enforce_vpn', 'forward_vpn'): if vpn_policy is None and not mobile_vpn: raise MissingRequiredInput('You must either specify a vpn_policy or set ' 'mobile_vpn when using a rule with a VPN action') if mobile_vpn: rule_action.mobile_vpn = True else: try: vpn = element_resolver(vpn_policy) # VPNPolicy rule_action.vpn = vpn except ElementNotFound: raise MissingRequiredInput('Cannot find VPN policy specified: {}, ' .format(vpn_policy)) elif rule_action.action == 'jump': try: rule_action.sub_policy = element_resolver(sub_policy) except ElementNotFound: raise MissingRequiredInput('Cannot find sub policy specified: {} ' .format(sub_policy)) #rule_values.update(action=rule_action.data) log_options = LogOptions() if not log_options else log_options if connection_tracking is not None: rule_action.connection_tracking_options.update(**connection_tracking) auth_options = AuthenticationOptions() if not authentication_options \ else authentication_options rule_values.update( action=rule_action.data, options=log_options.data, authentication_options=auth_options.data, is_disabled=is_disabled) params = None href = self.href if add_pos is not None: href = self.add_at_position(add_pos) elif before or after: params = self.add_before_after(before, after) return ElementCreator( self.__class__, exception=CreateRuleFailed, href=href, params=params, json=rule_values)
[ "def", "create", "(", "self", ",", "name", ",", "sources", "=", "None", ",", "destinations", "=", "None", ",", "services", "=", "None", ",", "action", "=", "'allow'", ",", "log_options", "=", "None", ",", "authentication_options", "=", "None", ",", "conn...
Create a layer 3 firewall rule :param str name: name of rule :param sources: source/s for rule :type sources: list[str, Element] :param destinations: destination/s for rule :type destinations: list[str, Element] :param services: service/s for rule :type services: list[str, Element] :param action: allow,continue,discard,refuse,enforce_vpn, apply_vpn,forward_vpn, blacklist (default: allow) :type action: Action or str :param LogOptions log_options: LogOptions object :param ConnectionTracking connection_tracking: custom connection tracking settings :param AuthenticationOptions authentication_options: options for auth if any :param PolicyVPN,str vpn_policy: policy element or str href; required for enforce_vpn, use_vpn and apply_vpn actions :param bool mobile_vpn: if using a vpn action, you can set mobile_vpn to True and omit the vpn_policy setting if you want this VPN to apply to any mobile VPN based on the policy VPN associated with the engine :param str,Element sub_policy: sub policy required when rule has an action of 'jump'. Can be the FirewallSubPolicy element or href. :param int add_pos: position to insert the rule, starting with position 1. If the position value is greater than the number of rules, the rule is inserted at the bottom. If add_pos is not provided, rule is inserted in position 1. Mutually exclusive with ``after`` and ``before`` params. :param str after: Rule tag to add this rule after. Mutually exclusive with ``add_pos`` and ``before`` params. :param str before: Rule tag to add this rule before. Mutually exclusive with ``add_pos`` and ``after`` params. :param str comment: optional comment for this rule :raises MissingRequiredInput: when options are specified the need additional setting, i.e. use_vpn action requires a vpn policy be specified. :raises CreateRuleFailed: rule creation failure :return: the created ipv4 rule :rtype: IPv4Rule
[ "Create", "a", "layer", "3", "firewall", "rule" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/policy/rule.py#L469-L575
train
38,787
gabstopper/smc-python
smc/policy/rule.py
EthernetRule.create
def create(self, name, sources=None, destinations=None, services=None, action='allow', is_disabled=False, logical_interfaces=None, add_pos=None, after=None, before=None, comment=None): """ Create an Ethernet rule :param str name: name of rule :param sources: source/s for rule :type sources: list[str, Element] :param destinations: destination/s for rule :type destinations: list[str, Element] :param services: service/s for rule :type services: list[str, Element] :param str action: \|allow\|continue\|discard\|refuse\|blacklist :param bool is_disabled: whether to disable rule or not :param list logical_interfaces: logical interfaces by name :param int add_pos: position to insert the rule, starting with position 1. If the position value is greater than the number of rules, the rule is inserted at the bottom. If add_pos is not provided, rule is inserted in position 1. Mutually exclusive with ``after`` and ``before`` params. :param str after: Rule tag to add this rule after. Mutually exclusive with ``add_pos`` and ``before`` params. :param str before: Rule tag to add this rule before. Mutually exclusive with ``add_pos`` and ``after`` params. :raises MissingReuqiredInput: when options are specified the need additional setting, i.e. use_vpn action requires a vpn policy be specified. :raises CreateRuleFailed: rule creation failure :return: newly created rule :rtype: EthernetRule """ rule_values = self.update_targets(sources, destinations, services) rule_values.update(name=name, comment=comment) rule_values.update(is_disabled=is_disabled) if isinstance(action, Action): rule_action = action else: rule_action = Action() rule_action.action = action if not rule_action.action in self._actions: raise CreateRuleFailed('Action specified is not valid for this ' 'rule type; action: {}' .format(rule_action.action)) rule_values.update(action=rule_action.data) rule_values.update(self.update_logical_if(logical_interfaces)) params = None href = self.href if add_pos is not None: href = self.add_at_position(add_pos) else: params = self.add_before_after(before, after) return ElementCreator( self.__class__, exception=CreateRuleFailed, href=href, params=params, json=rule_values)
python
def create(self, name, sources=None, destinations=None, services=None, action='allow', is_disabled=False, logical_interfaces=None, add_pos=None, after=None, before=None, comment=None): """ Create an Ethernet rule :param str name: name of rule :param sources: source/s for rule :type sources: list[str, Element] :param destinations: destination/s for rule :type destinations: list[str, Element] :param services: service/s for rule :type services: list[str, Element] :param str action: \|allow\|continue\|discard\|refuse\|blacklist :param bool is_disabled: whether to disable rule or not :param list logical_interfaces: logical interfaces by name :param int add_pos: position to insert the rule, starting with position 1. If the position value is greater than the number of rules, the rule is inserted at the bottom. If add_pos is not provided, rule is inserted in position 1. Mutually exclusive with ``after`` and ``before`` params. :param str after: Rule tag to add this rule after. Mutually exclusive with ``add_pos`` and ``before`` params. :param str before: Rule tag to add this rule before. Mutually exclusive with ``add_pos`` and ``after`` params. :raises MissingReuqiredInput: when options are specified the need additional setting, i.e. use_vpn action requires a vpn policy be specified. :raises CreateRuleFailed: rule creation failure :return: newly created rule :rtype: EthernetRule """ rule_values = self.update_targets(sources, destinations, services) rule_values.update(name=name, comment=comment) rule_values.update(is_disabled=is_disabled) if isinstance(action, Action): rule_action = action else: rule_action = Action() rule_action.action = action if not rule_action.action in self._actions: raise CreateRuleFailed('Action specified is not valid for this ' 'rule type; action: {}' .format(rule_action.action)) rule_values.update(action=rule_action.data) rule_values.update(self.update_logical_if(logical_interfaces)) params = None href = self.href if add_pos is not None: href = self.add_at_position(add_pos) else: params = self.add_before_after(before, after) return ElementCreator( self.__class__, exception=CreateRuleFailed, href=href, params=params, json=rule_values)
[ "def", "create", "(", "self", ",", "name", ",", "sources", "=", "None", ",", "destinations", "=", "None", ",", "services", "=", "None", ",", "action", "=", "'allow'", ",", "is_disabled", "=", "False", ",", "logical_interfaces", "=", "None", ",", "add_pos...
Create an Ethernet rule :param str name: name of rule :param sources: source/s for rule :type sources: list[str, Element] :param destinations: destination/s for rule :type destinations: list[str, Element] :param services: service/s for rule :type services: list[str, Element] :param str action: \|allow\|continue\|discard\|refuse\|blacklist :param bool is_disabled: whether to disable rule or not :param list logical_interfaces: logical interfaces by name :param int add_pos: position to insert the rule, starting with position 1. If the position value is greater than the number of rules, the rule is inserted at the bottom. If add_pos is not provided, rule is inserted in position 1. Mutually exclusive with ``after`` and ``before`` params. :param str after: Rule tag to add this rule after. Mutually exclusive with ``add_pos`` and ``before`` params. :param str before: Rule tag to add this rule before. Mutually exclusive with ``add_pos`` and ``after`` params. :raises MissingReuqiredInput: when options are specified the need additional setting, i.e. use_vpn action requires a vpn policy be specified. :raises CreateRuleFailed: rule creation failure :return: newly created rule :rtype: EthernetRule
[ "Create", "an", "Ethernet", "rule" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/policy/rule.py#L677-L740
train
38,788
gabstopper/smc-python
smc/core/resource.py
Snapshot.download
def download(self, filename=None): """ Download snapshot to filename :param str filename: fully qualified path including filename .zip :raises EngineCommandFailed: IOError occurred downloading snapshot :return: None """ if not filename: filename = '{}{}'.format(self.name, '.zip') try: self.make_request( EngineCommandFailed, resource='content', filename=filename) except IOError as e: raise EngineCommandFailed("Snapshot download failed: {}" .format(e))
python
def download(self, filename=None): """ Download snapshot to filename :param str filename: fully qualified path including filename .zip :raises EngineCommandFailed: IOError occurred downloading snapshot :return: None """ if not filename: filename = '{}{}'.format(self.name, '.zip') try: self.make_request( EngineCommandFailed, resource='content', filename=filename) except IOError as e: raise EngineCommandFailed("Snapshot download failed: {}" .format(e))
[ "def", "download", "(", "self", ",", "filename", "=", "None", ")", ":", "if", "not", "filename", ":", "filename", "=", "'{}{}'", ".", "format", "(", "self", ".", "name", ",", "'.zip'", ")", "try", ":", "self", ".", "make_request", "(", "EngineCommandFa...
Download snapshot to filename :param str filename: fully qualified path including filename .zip :raises EngineCommandFailed: IOError occurred downloading snapshot :return: None
[ "Download", "snapshot", "to", "filename" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/resource.py#L30-L49
train
38,789
gabstopper/smc-python
smc/vpn/policy.py
PolicyVPN.create
def create(cls, name, nat=False, mobile_vpn_toplogy_mode=None, vpn_profile=None): """ Create a new policy based VPN :param name: name of vpn policy :param bool nat: whether to apply NAT to the VPN (default False) :param mobile_vpn_toplogy_mode: whether to allow remote vpn :param VPNProfile vpn_profile: reference to VPN profile, or uses default :rtype: PolicyVPN """ vpn_profile = element_resolver(vpn_profile) or \ VPNProfile('VPN-A Suite').href json = {'mobile_vpn_topology_mode': mobile_vpn_toplogy_mode, 'name': name, 'nat': nat, 'vpn_profile': vpn_profile} try: return ElementCreator(cls, json) except CreateElementFailed as err: raise CreatePolicyFailed(err)
python
def create(cls, name, nat=False, mobile_vpn_toplogy_mode=None, vpn_profile=None): """ Create a new policy based VPN :param name: name of vpn policy :param bool nat: whether to apply NAT to the VPN (default False) :param mobile_vpn_toplogy_mode: whether to allow remote vpn :param VPNProfile vpn_profile: reference to VPN profile, or uses default :rtype: PolicyVPN """ vpn_profile = element_resolver(vpn_profile) or \ VPNProfile('VPN-A Suite').href json = {'mobile_vpn_topology_mode': mobile_vpn_toplogy_mode, 'name': name, 'nat': nat, 'vpn_profile': vpn_profile} try: return ElementCreator(cls, json) except CreateElementFailed as err: raise CreatePolicyFailed(err)
[ "def", "create", "(", "cls", ",", "name", ",", "nat", "=", "False", ",", "mobile_vpn_toplogy_mode", "=", "None", ",", "vpn_profile", "=", "None", ")", ":", "vpn_profile", "=", "element_resolver", "(", "vpn_profile", ")", "or", "VPNProfile", "(", "'VPN-A Suit...
Create a new policy based VPN :param name: name of vpn policy :param bool nat: whether to apply NAT to the VPN (default False) :param mobile_vpn_toplogy_mode: whether to allow remote vpn :param VPNProfile vpn_profile: reference to VPN profile, or uses default :rtype: PolicyVPN
[ "Create", "a", "new", "policy", "based", "VPN" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/vpn/policy.py#L32-L54
train
38,790
gabstopper/smc-python
smc/vpn/policy.py
PolicyVPN.enable_disable_nat
def enable_disable_nat(self): """ Enable or disable NAT on this policy. If NAT is disabled, it will be enabled and vice versa. :return: None """ if self.nat: self.data['nat'] = False else: self.data['nat'] = True
python
def enable_disable_nat(self): """ Enable or disable NAT on this policy. If NAT is disabled, it will be enabled and vice versa. :return: None """ if self.nat: self.data['nat'] = False else: self.data['nat'] = True
[ "def", "enable_disable_nat", "(", "self", ")", ":", "if", "self", ".", "nat", ":", "self", ".", "data", "[", "'nat'", "]", "=", "False", "else", ":", "self", ".", "data", "[", "'nat'", "]", "=", "True" ]
Enable or disable NAT on this policy. If NAT is disabled, it will be enabled and vice versa. :return: None
[ "Enable", "or", "disable", "NAT", "on", "this", "policy", ".", "If", "NAT", "is", "disabled", "it", "will", "be", "enabled", "and", "vice", "versa", "." ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/vpn/policy.py#L66-L76
train
38,791
gabstopper/smc-python
smc/elements/group.py
GroupMixin.update_members
def update_members(self, members, append_lists=False, remove_members=False): """ Update group members with member list. Set append=True to append to existing members, or append=False to overwrite. :param list members: new members for group by href or Element :type members: list[str, Element] :param bool append_lists: whether to append :param bool remove_members: remove members from the group :return: bool was modified or not """ if members: elements = [element_resolver(element) for element in members] if remove_members: element = [e for e in self.members if e not in elements] if set(element) == set(self.members): remove_members = element = False append_lists = False elif append_lists: element = [e for e in elements if e not in self.members] else: element = list(set(elements)) if element or remove_members: self.update( element=element, append_lists=append_lists) return True return False
python
def update_members(self, members, append_lists=False, remove_members=False): """ Update group members with member list. Set append=True to append to existing members, or append=False to overwrite. :param list members: new members for group by href or Element :type members: list[str, Element] :param bool append_lists: whether to append :param bool remove_members: remove members from the group :return: bool was modified or not """ if members: elements = [element_resolver(element) for element in members] if remove_members: element = [e for e in self.members if e not in elements] if set(element) == set(self.members): remove_members = element = False append_lists = False elif append_lists: element = [e for e in elements if e not in self.members] else: element = list(set(elements)) if element or remove_members: self.update( element=element, append_lists=append_lists) return True return False
[ "def", "update_members", "(", "self", ",", "members", ",", "append_lists", "=", "False", ",", "remove_members", "=", "False", ")", ":", "if", "members", ":", "elements", "=", "[", "element_resolver", "(", "element", ")", "for", "element", "in", "members", ...
Update group members with member list. Set append=True to append to existing members, or append=False to overwrite. :param list members: new members for group by href or Element :type members: list[str, Element] :param bool append_lists: whether to append :param bool remove_members: remove members from the group :return: bool was modified or not
[ "Update", "group", "members", "with", "member", "list", ".", "Set", "append", "=", "True", "to", "append", "to", "existing", "members", "or", "append", "=", "False", "to", "overwrite", "." ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/elements/group.py#L53-L82
train
38,792
gabstopper/smc-python
smc/elements/group.py
TCPServiceGroup.create
def create(cls, name, members=None, comment=None): """ Create the TCP Service group :param str name: name of tcp service group :param list element: tcp services by element or href :type element: list(str,Element) :raises CreateElementFailed: element creation failed with reason :return: instance with meta :rtype: TCPServiceGroup """ element = [] if members is None else element_resolver(members) json = {'name': name, 'element': element, 'comment': comment} return ElementCreator(cls, json)
python
def create(cls, name, members=None, comment=None): """ Create the TCP Service group :param str name: name of tcp service group :param list element: tcp services by element or href :type element: list(str,Element) :raises CreateElementFailed: element creation failed with reason :return: instance with meta :rtype: TCPServiceGroup """ element = [] if members is None else element_resolver(members) json = {'name': name, 'element': element, 'comment': comment} return ElementCreator(cls, json)
[ "def", "create", "(", "cls", ",", "name", ",", "members", "=", "None", ",", "comment", "=", "None", ")", ":", "element", "=", "[", "]", "if", "members", "is", "None", "else", "element_resolver", "(", "members", ")", "json", "=", "{", "'name'", ":", ...
Create the TCP Service group :param str name: name of tcp service group :param list element: tcp services by element or href :type element: list(str,Element) :raises CreateElementFailed: element creation failed with reason :return: instance with meta :rtype: TCPServiceGroup
[ "Create", "the", "TCP", "Service", "group" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/elements/group.py#L214-L230
train
38,793
gabstopper/smc-python
smc/vpn/route.py
RouteVPN.create_gre_tunnel_no_encryption
def create_gre_tunnel_no_encryption(cls, name, local_endpoint, remote_endpoint, mtu=0, pmtu_discovery=True, ttl=0, enabled=True, comment=None): """ Create a GRE Tunnel with no encryption. See `create_gre_tunnel_mode` for constructor descriptions. """ return cls.create_gre_tunnel_mode( name, local_endpoint, remote_endpoint, policy_vpn=None, mtu=mtu, pmtu_discovery=pmtu_discovery, ttl=ttl, enabled=enabled, comment=comment)
python
def create_gre_tunnel_no_encryption(cls, name, local_endpoint, remote_endpoint, mtu=0, pmtu_discovery=True, ttl=0, enabled=True, comment=None): """ Create a GRE Tunnel with no encryption. See `create_gre_tunnel_mode` for constructor descriptions. """ return cls.create_gre_tunnel_mode( name, local_endpoint, remote_endpoint, policy_vpn=None, mtu=mtu, pmtu_discovery=pmtu_discovery, ttl=ttl, enabled=enabled, comment=comment)
[ "def", "create_gre_tunnel_no_encryption", "(", "cls", ",", "name", ",", "local_endpoint", ",", "remote_endpoint", ",", "mtu", "=", "0", ",", "pmtu_discovery", "=", "True", ",", "ttl", "=", "0", ",", "enabled", "=", "True", ",", "comment", "=", "None", ")",...
Create a GRE Tunnel with no encryption. See `create_gre_tunnel_mode` for constructor descriptions.
[ "Create", "a", "GRE", "Tunnel", "with", "no", "encryption", ".", "See", "create_gre_tunnel_mode", "for", "constructor", "descriptions", "." ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/vpn/route.py#L252-L262
train
38,794
gabstopper/smc-python
smc/core/interfaces.py
InterfaceOptions.set_auth_request
def set_auth_request(self, interface_id, address=None): """ Set the authentication request field for the specified engine. """ self.interface.set_auth_request(interface_id, address) self._engine.update()
python
def set_auth_request(self, interface_id, address=None): """ Set the authentication request field for the specified engine. """ self.interface.set_auth_request(interface_id, address) self._engine.update()
[ "def", "set_auth_request", "(", "self", ",", "interface_id", ",", "address", "=", "None", ")", ":", "self", ".", "interface", ".", "set_auth_request", "(", "interface_id", ",", "address", ")", "self", ".", "_engine", ".", "update", "(", ")" ]
Set the authentication request field for the specified engine.
[ "Set", "the", "authentication", "request", "field", "for", "the", "specified", "engine", "." ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/interfaces.py#L134-L141
train
38,795
gabstopper/smc-python
smc/core/interfaces.py
Interface.name
def name(self): """ Read only name tag """ name = super(Interface, self).name return name if name else self.data.get('name')
python
def name(self): """ Read only name tag """ name = super(Interface, self).name return name if name else self.data.get('name')
[ "def", "name", "(", "self", ")", ":", "name", "=", "super", "(", "Interface", ",", "self", ")", ".", "name", "return", "name", "if", "name", "else", "self", ".", "data", ".", "get", "(", "'name'", ")" ]
Read only name tag
[ "Read", "only", "name", "tag" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/interfaces.py#L845-L850
train
38,796
gabstopper/smc-python
smc/core/interfaces.py
TunnelInterface._add_interface
def _add_interface(self, interface_id, **kw): """ Create a tunnel interface. Kw argument list is as follows """ base_interface = ElementCache() base_interface.update( interface_id=str(interface_id), interfaces=[]) if 'zone_ref' in kw: zone_ref = kw.pop('zone_ref') base_interface.update(zone_ref=zone_helper(zone_ref) if zone_ref else None) if 'comment' in kw: base_interface.update(comment=kw.pop('comment')) self.data = base_interface interfaces = kw.pop('interfaces', []) if interfaces: for interface in interfaces: if interface.get('cluster_virtual', None) or \ len(interface.get('nodes', [])) > 1: # Cluster kw.update(interface_id=interface_id, interfaces=interfaces) cvi = ClusterPhysicalInterface(**kw) cvi.data.pop('vlanInterfaces', None) self.data.update(cvi.data) else: # Single interface FW for node in interface.get('nodes', []): node.update(nodeid=1) sni = SingleNodeInterface.create(interface_id, **node) base_interface.setdefault('interfaces', []).append( {sni.typeof: sni.data})
python
def _add_interface(self, interface_id, **kw): """ Create a tunnel interface. Kw argument list is as follows """ base_interface = ElementCache() base_interface.update( interface_id=str(interface_id), interfaces=[]) if 'zone_ref' in kw: zone_ref = kw.pop('zone_ref') base_interface.update(zone_ref=zone_helper(zone_ref) if zone_ref else None) if 'comment' in kw: base_interface.update(comment=kw.pop('comment')) self.data = base_interface interfaces = kw.pop('interfaces', []) if interfaces: for interface in interfaces: if interface.get('cluster_virtual', None) or \ len(interface.get('nodes', [])) > 1: # Cluster kw.update(interface_id=interface_id, interfaces=interfaces) cvi = ClusterPhysicalInterface(**kw) cvi.data.pop('vlanInterfaces', None) self.data.update(cvi.data) else: # Single interface FW for node in interface.get('nodes', []): node.update(nodeid=1) sni = SingleNodeInterface.create(interface_id, **node) base_interface.setdefault('interfaces', []).append( {sni.typeof: sni.data})
[ "def", "_add_interface", "(", "self", ",", "interface_id", ",", "*", "*", "kw", ")", ":", "base_interface", "=", "ElementCache", "(", ")", "base_interface", ".", "update", "(", "interface_id", "=", "str", "(", "interface_id", ")", ",", "interfaces", "=", "...
Create a tunnel interface. Kw argument list is as follows
[ "Create", "a", "tunnel", "interface", ".", "Kw", "argument", "list", "is", "as", "follows" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/interfaces.py#L941-L976
train
38,797
gabstopper/smc-python
smc/core/interfaces.py
ClusterPhysicalInterface._add_interface
def _add_interface(self, interface_id, mgt=None, **kw): """ Add the Cluster interface. If adding a cluster interface to an existing node, retrieve the existing interface and call this method. Use the supported format for defining an interface. """ _kw = copy.deepcopy(kw) # Preserve original kw, especially lists mgt = mgt if mgt else {} if 'cvi_mode' in _kw: self.data.update(cvi_mode=_kw.pop('cvi_mode')) if 'macaddress' in _kw: self.data.update( macaddress=_kw.pop('macaddress')) if 'cvi_mode' not in self.data: self.data.update(cvi_mode='packetdispatch') if 'zone_ref' in _kw: zone_ref = _kw.pop('zone_ref') self.data.update(zone_ref=zone_helper(zone_ref) if zone_ref else None) if 'comment' in _kw: self.data.update(comment=_kw.pop('comment')) interfaces = _kw.pop('interfaces', []) for interface in interfaces: vlan_id = interface.pop('vlan_id', None) if vlan_id: _interface_id = '{}.{}'.format(interface_id, vlan_id) else: _interface_id = interface_id _interface = [] if_mgt = {k: str(v) == str(_interface_id) for k, v in mgt.items()} if 'cluster_virtual' in interface and 'network_value' in interface: cluster_virtual = interface.pop('cluster_virtual') network_value = interface.pop('network_value') if cluster_virtual and network_value: cvi = ClusterVirtualInterface.create( _interface_id, cluster_virtual, network_value, auth_request=True if if_mgt.get('primary_mgt') else False) _interface.append({cvi.typeof: cvi.data}) for node in interface.pop('nodes', []): _node = if_mgt.copy() _node.update(outgoing=True if if_mgt.get('primary_mgt') else False) # Add node specific key/value pairs set on the node. This can # also be used to override management settings _node.update(node) ndi = NodeInterface.create( interface_id=_interface_id, **_node) _interface.append({ndi.typeof: ndi.data}) if vlan_id: vlan_interface = { 'interface_id': _interface_id, 'zone_ref': zone_helper(interface.pop('zone_ref', None)), 'comment': interface.pop('comment', None), 'interfaces': _interface} # Add remaining kwargs on vlan level to VLAN physical interface for name, value in interface.items(): vlan_interface[name] = value self.data.setdefault('vlanInterfaces', []).append( vlan_interface) else: self.data.setdefault('interfaces', []).extend( _interface) # Remaining kw go to base level interface for name, value in _kw.items(): self.data[name] = value
python
def _add_interface(self, interface_id, mgt=None, **kw): """ Add the Cluster interface. If adding a cluster interface to an existing node, retrieve the existing interface and call this method. Use the supported format for defining an interface. """ _kw = copy.deepcopy(kw) # Preserve original kw, especially lists mgt = mgt if mgt else {} if 'cvi_mode' in _kw: self.data.update(cvi_mode=_kw.pop('cvi_mode')) if 'macaddress' in _kw: self.data.update( macaddress=_kw.pop('macaddress')) if 'cvi_mode' not in self.data: self.data.update(cvi_mode='packetdispatch') if 'zone_ref' in _kw: zone_ref = _kw.pop('zone_ref') self.data.update(zone_ref=zone_helper(zone_ref) if zone_ref else None) if 'comment' in _kw: self.data.update(comment=_kw.pop('comment')) interfaces = _kw.pop('interfaces', []) for interface in interfaces: vlan_id = interface.pop('vlan_id', None) if vlan_id: _interface_id = '{}.{}'.format(interface_id, vlan_id) else: _interface_id = interface_id _interface = [] if_mgt = {k: str(v) == str(_interface_id) for k, v in mgt.items()} if 'cluster_virtual' in interface and 'network_value' in interface: cluster_virtual = interface.pop('cluster_virtual') network_value = interface.pop('network_value') if cluster_virtual and network_value: cvi = ClusterVirtualInterface.create( _interface_id, cluster_virtual, network_value, auth_request=True if if_mgt.get('primary_mgt') else False) _interface.append({cvi.typeof: cvi.data}) for node in interface.pop('nodes', []): _node = if_mgt.copy() _node.update(outgoing=True if if_mgt.get('primary_mgt') else False) # Add node specific key/value pairs set on the node. This can # also be used to override management settings _node.update(node) ndi = NodeInterface.create( interface_id=_interface_id, **_node) _interface.append({ndi.typeof: ndi.data}) if vlan_id: vlan_interface = { 'interface_id': _interface_id, 'zone_ref': zone_helper(interface.pop('zone_ref', None)), 'comment': interface.pop('comment', None), 'interfaces': _interface} # Add remaining kwargs on vlan level to VLAN physical interface for name, value in interface.items(): vlan_interface[name] = value self.data.setdefault('vlanInterfaces', []).append( vlan_interface) else: self.data.setdefault('interfaces', []).extend( _interface) # Remaining kw go to base level interface for name, value in _kw.items(): self.data[name] = value
[ "def", "_add_interface", "(", "self", ",", "interface_id", ",", "mgt", "=", "None", ",", "*", "*", "kw", ")", ":", "_kw", "=", "copy", ".", "deepcopy", "(", "kw", ")", "# Preserve original kw, especially lists", "mgt", "=", "mgt", "if", "mgt", "else", "{...
Add the Cluster interface. If adding a cluster interface to an existing node, retrieve the existing interface and call this method. Use the supported format for defining an interface.
[ "Add", "the", "Cluster", "interface", ".", "If", "adding", "a", "cluster", "interface", "to", "an", "existing", "node", "retrieve", "the", "existing", "interface", "and", "call", "this", "method", ".", "Use", "the", "supported", "format", "for", "defining", ...
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/interfaces.py#L1616-L1689
train
38,798
gabstopper/smc-python
smc/routing/bgp.py
BGPProfile.create
def create(cls, name, port=179, external_distance=20, internal_distance=200, local_distance=200, subnet_distance=None): """ Create a custom BGP Profile :param str name: name of profile :param int port: port for BGP process :param int external_distance: external administrative distance; (1-255) :param int internal_distance: internal administrative distance (1-255) :param int local_distance: local administrative distance (aggregation) (1-255) :param list subnet_distance: configure specific subnet's with respective distances :type tuple subnet_distance: (subnet element(Network), distance(int)) :raises CreateElementFailed: reason for failure :return: instance with meta :rtype: BGPProfile """ json = {'name': name, 'external': external_distance, 'internal': internal_distance, 'local': local_distance, 'port': port} if subnet_distance: d = [{'distance': distance, 'subnet': subnet.href} for subnet, distance in subnet_distance] json.update(distance_entry=d) return ElementCreator(cls, json)
python
def create(cls, name, port=179, external_distance=20, internal_distance=200, local_distance=200, subnet_distance=None): """ Create a custom BGP Profile :param str name: name of profile :param int port: port for BGP process :param int external_distance: external administrative distance; (1-255) :param int internal_distance: internal administrative distance (1-255) :param int local_distance: local administrative distance (aggregation) (1-255) :param list subnet_distance: configure specific subnet's with respective distances :type tuple subnet_distance: (subnet element(Network), distance(int)) :raises CreateElementFailed: reason for failure :return: instance with meta :rtype: BGPProfile """ json = {'name': name, 'external': external_distance, 'internal': internal_distance, 'local': local_distance, 'port': port} if subnet_distance: d = [{'distance': distance, 'subnet': subnet.href} for subnet, distance in subnet_distance] json.update(distance_entry=d) return ElementCreator(cls, json)
[ "def", "create", "(", "cls", ",", "name", ",", "port", "=", "179", ",", "external_distance", "=", "20", ",", "internal_distance", "=", "200", ",", "local_distance", "=", "200", ",", "subnet_distance", "=", "None", ")", ":", "json", "=", "{", "'name'", ...
Create a custom BGP Profile :param str name: name of profile :param int port: port for BGP process :param int external_distance: external administrative distance; (1-255) :param int internal_distance: internal administrative distance (1-255) :param int local_distance: local administrative distance (aggregation) (1-255) :param list subnet_distance: configure specific subnet's with respective distances :type tuple subnet_distance: (subnet element(Network), distance(int)) :raises CreateElementFailed: reason for failure :return: instance with meta :rtype: BGPProfile
[ "Create", "a", "custom", "BGP", "Profile" ]
e027b8a5dcfaf884eada32d113d41c1e56b32457
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/routing/bgp.py#L393-L420
train
38,799