code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
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=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`
3.990316
3.784021
1.054517
virt_resource_href = None # need virtual resource reference master_engine = Engine(master_engine) for virt_resource in master_engine.virtual_resource.all(): if virt_resource.name == virtual_resource: virt_resource_href = virt_resource.href break if not virt_resource_href: raise CreateEngineFailed('Cannot find associated virtual resource for ' 'VE named: {}. You must first create a virtual resource for the ' 'master engine before you can associate a virtual engine. Cannot ' 'add VE'.format(name)) virtual_interfaces = [] for interface in interfaces: nodes = {'address': interface.get('address'), 'network_value': interface.get('network_value')} layer3 = {'interface_id': interface.get('interface_id'), 'interface': 'single_node_interface', 'comment': interface.get('comment', None), 'zone_ref': interface.get('zone_ref')} if interface.get('interface_id') == outgoing_intf: nodes.update(outgoing=True, auth_request=True) layer3['interfaces'] = [{'nodes': [nodes]}] virtual_interfaces.append( {'virtual_physical_interface': Layer3PhysicalInterface(**layer3).data.data}) engine = super(Layer3VirtualEngine, cls)._create( name=name, node_type='virtual_fw_node', physical_interfaces=virtual_interfaces, domain_server_address=domain_server_address, log_server_ref=None, # Isn't used in VE nodes=1, default_nat=default_nat, enable_ospf=enable_ospf, ospf_profile=ospf_profile, comment=comment) engine.update(virtual_resource=virt_resource_href) # Master Engine provides this service engine.pop('log_server_ref', None) try: return ElementCreator(cls, json=engine) except CreateElementFailed as e: raise CreateEngineFailed(e)
def create(cls, name, master_engine, virtual_resource, interfaces, default_nat=False, outgoing_intf=0, domain_server_address=None, enable_ospf=False, ospf_profile=None, comment=None, **kw)
Create a Layer3Virtual engine for a Master Engine. Provide interfaces as a list of dict items specifying the interface details in format:: {'interface_id': 1, 'address': '1.1.1.1', 'network_value': '1.1.1.0/24', 'zone_ref': zone_by_name,href, 'comment': 'my interface comment'} :param str name: Name of this layer 3 virtual engine :param str master_engine: Name of existing master engine :param str virtual_resource: name of pre-created virtual resource :param list interfaces: dict of interface details :param bool default_nat: Whether to enable default NAT for outbound :param int outgoing_intf: outgoing interface for VE. Specifies interface number :param list interfaces: interfaces mappings passed in :param bool enable_ospf: whether to turn OSPF on within engine :param str ospf_profile: optional OSPF profile to use on engine, by ref :raises CreateEngineFailed: Failure to create with reason :raises LoadEngineFailed: master engine not found :return: :py:class:`smc.core.engine.Engine`
4.670749
4.107766
1.137053
primary_heartbeat = primary_mgt if not primary_heartbeat else primary_heartbeat physical_interfaces = [] for interface in interfaces: if 'interface_id' not in interface: raise CreateEngineFailed('Interface definitions must contain the interface_id ' 'field. Failed to create engine: %s' % name) if interface.get('type', None) == 'tunnel_interface': tunnel_interface = TunnelInterface(**interface) physical_interfaces.append( {'tunnel_interface': tunnel_interface}) else: cluster_interface = ClusterPhysicalInterface( primary_mgt=primary_mgt, backup_mgt=backup_mgt, primary_heartbeat=primary_heartbeat, **interface) physical_interfaces.append( {'physical_interface': cluster_interface}) if snmp: snmp_agent = dict( snmp_agent_ref=snmp.get('snmp_agent', ''), snmp_location=snmp.get('snmp_location', '')) snmp_agent.update( snmp_interface=add_snmp( interfaces, snmp.get('snmp_interface', []))) try: engine = super(FirewallCluster, cls)._create( name=name, node_type='firewall_node', physical_interfaces=physical_interfaces, domain_server_address=domain_server_address, log_server_ref=log_server_ref, location_ref=location_ref, nodes=nodes, enable_gti=enable_gti, enable_antivirus=enable_antivirus, default_nat=default_nat, snmp_agent=snmp_agent if snmp else None, comment=comment) engine.update(cluster_mode=cluster_mode) return ElementCreator(cls, json=engine) except (ElementNotFound, CreateElementFailed) as e: raise CreateEngineFailed(e)
def create_bulk(cls, name, interfaces=None, nodes=2, cluster_mode='balancing', primary_mgt=None, backup_mgt=None, primary_heartbeat=None, log_server_ref=None, domain_server_address=None, location_ref=None, default_nat=False, enable_antivirus=False, enable_gti=False, comment=None, snmp=None, **kw)
:param dict snmp: SNMP dict should have keys `snmp_agent` str defining name of SNMPAgent, `snmp_interface` which is a list of interface IDs, and optionally `snmp_location` which is a string with the SNMP location name.
2.874522
2.729871
1.052988
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=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`
4.90802
4.565933
1.074922
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_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}]
4.739044
4.791801
0.98899
def set_stream_logger(log_level=logging.DEBUG, format_string=None, logger_name='smc'): if format_string is None: format_string = LOG_FORMAT logger = logging.getLogger(logger_name) logger.setLevel(log_level) # create console handler and set level ch = logging.StreamHandler() ch.setLevel(log_level) # create formatter formatter = logging.Formatter(format_string) # add formatter to ch ch.setFormatter(formatter) logger.addHandler(ch)
Stream logger convenience function to log to console :param int log_level: A log level as specified in the `logging` module :param str format_string: Optional format string as specified in the `logging` module
null
null
null
if format_string is None: format_string = LOG_FORMAT log = logging.getLogger(logger_name) log.setLevel(log_level) # create file handler and set level ch = logging.FileHandler(path) ch.setLevel(log_level) # create formatter formatter = logging.Formatter(format_string) # add formatter to ch ch.setFormatter(formatter) # add ch to logger log.addHandler(ch)
def set_file_logger(path, log_level=logging.DEBUG, format_string=None, logger_name='smc')
Convenience function to quickly configure any level of logging to a file. :param int log_level: A log level as specified in the `logging` module :param str format_string: Optional format string as specified in the `logging` module :param str path: Path to the log file. The file will be created if it doesn't already exist.
1.775157
1.948722
0.910934
return ElementCreator(cls, json={'name': name, 'ldap_server': element_resolver(ldap_server), 'auth_method': element_resolver(auth_method), 'isdefault': isdefault, 'comment': comment})
def create(cls, name, ldap_server, isdefault=False, auth_method=None, comment=None)
Create an External LDAP user domain. These are used as containers for retrieving user and groups from the configured LDAP server/s. If you have multiple authentication methods supported for your LDAP server, or have none configured, you can set the `auth_method` to a supported AuthenticationMethod. :param str name: name of external LDAP domain :param list(str,ActiveDirectoryServer) ldap_server: list of existing authentication servers in href or element format :param bool isdefault: set this to 'Default LDAP domain' :param str,AuthenticationMethod auth_method: authentication method to use. Usually set when multiple are defined in LDAP service or none are defined. :param str comment: optional comment :raises CreateElementFailed: failed to create :rtype: ExternalLdapUserDomain
4.38574
4.806925
0.91238
json = { 'name': name, 'unique_id': 'cn={},{}'.format(name, InternalUserDomain.user_dn), 'comment': comment} limits = {'activation_date': activation_date, 'expiration_date': expiration_date} for attr, value in limits.items(): json[attr] = datetime_to_ms(value) if value else None if user_group: json.update(user_group=element_resolver(user_group)) return ElementCreator(cls, json)
def create(cls, name, user_group=None, activation_date=None, expiration_date=None, comment=None)
Create an internal user. Add a user example:: InternalUser.create(name='goog', comment='my comment') :param str name: name of user that is displayed in SMC :param list(str,InternalUserGroup) user_group: internal user groups which to add this user to. :param datetime activation_date: activation date as datetime object. Activation date only supports year and month/day :param datetime expiration_date: expiration date as datetime object. Expiration date only supports year and month/day :param str comment: optional comment :raises ElementNotFound: thrown if group specified does not exist :rtype: InternalUser
5.09731
5.530697
0.92164
json={'name': name, 'unique_id': 'cn={},{}'.format(name, InternalUserDomain.user_dn), 'comment': comment} if member: json.update(member=element_resolver(member)) return ElementCreator(cls, json)
def create(cls, name, member=None, comment=None)
Create an internal group. An internal group will always be attached to the default (and only) InternalUserDomain within the SMC. Example of creating an internal user group:: InternalUserGroup.create(name='foogroup2', comment='mycomment') :param str name: Name of group :param list(InternalUser) member: list of internal users to add to this group :param str comment: optional comment :raises CreateElementFailed: failed to create user group :rtype: InternalUserGroup
11.856325
10.275658
1.153826
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)
Get all loopback interfaces for a given engine
5.704566
5.484362
1.040151
loopback = super(LoopbackCollection, self).get(address=address) if loopback: return loopback raise InterfaceNotFound('Loopback address specified was not found')
def get(self, address)
Get a loopback address by it's address. Find all loopback addresses by iterating at either the node level or the engine:: loopback = engine.loopback_interface.get('127.0.0.10') :param str address: ip address of loopback :raises InterfaceNotFound: invalid interface specified :rtype: LoopbackInterface
7.699177
7.197682
1.069674
created, modified = (False, False) try: intf = self._engine.interface.get( interface.interface_id) interface, updated = intf.update_interface(interface) if updated: modified = True except InterfaceNotFound: self._engine.add_interface(interface) interface = self._engine.interface.get(interface.interface_id) created = True return interface, modified, created
def update_or_create(self, interface)
Collections class update or create method that can be used as a shortcut to updating or creating an interface. The interface must first be defined and provided as the argument. The interface method must have an `update_interface` method which resolves differences and adds as necessary. :param Interface interface: an instance of an interface type, either PhysicalInterface or TunnelInterface :raises EngineCommandFailed: Failed to create new interface :raises UpdateElementFailed: Failure to update element with reason :rtype: tuple :return: A tuple with (Interface, modified, created), where created and modified are booleans indicating the operations performed
3.592728
3.85127
0.932868
interfaces = [{'cluster_virtual': cluster_virtual, 'network_value': network_value, 'nodes': nodes if nodes else []}] 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_cluster_virtual_interface(self, interface_id, cluster_virtual=None, network_value=None, nodes=None, zone_ref=None, comment=None)
Add a tunnel interface on a clustered engine. For tunnel interfaces on a cluster, you can specify a CVI only, NDI interfaces, or both. This interface type is only supported on layer 3 firewall engines. :: Add a tunnel CVI and NDI: engine.tunnel_interface.add_cluster_virtual_interface( interface_id_id=3000, cluster_virtual='4.4.4.1', network_value='4.4.4.0/24', nodes=nodes) Add tunnel NDI's only: engine.tunnel_interface.add_cluster_virtual_interface( interface_id=3000, nodes=nodes) Add tunnel CVI only: engine.tunnel_interface.add_cluster_virtual_interface( interface_id=3000, cluster_virtual='31.31.31.31', network_value='31.31.31.0/24', zone_ref='myzone') :param str,int interface_id: tunnel identifier (akin to interface_id) :param str cluster_virtual: CVI ipaddress (optional) :param str network_value: CVI network; required if ``cluster_virtual`` set :param list nodes: nodes for clustered engine with address,network_value,nodeid :param str zone_ref: zone reference, can be name, href or Zone :param str comment: optional comment
3.497741
3.71955
0.940367
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)
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
3.187883
3.404548
0.93636
capture = {'interface_id': interface_id, 'interface': 'capture_interface', 'logical_interface_ref': logical_interface_ref, 'inspect_unspecified_vlans': inspect_unspecified_vlans, 'zone_ref': zone_ref, 'comment': comment} interface = Layer2PhysicalInterface(engine=self._engine, **capture) return self._engine.add_interface(interface)
def add_capture_interface(self, interface_id, logical_interface_ref, inspect_unspecified_vlans=True, zone_ref=None, comment=None)
Add a capture interface. Capture interfaces are supported on Layer 2 FW and IPS engines. ..note:: Capture interface are supported on Layer 3 FW/clusters for NGFW engines version >= 6.3 and SMC >= 6.3. :param str,int interface_id: interface identifier :param str logical_interface_ref: logical interface name, href or LogicalInterface. If None, 'default_eth' logical interface will be used. :param str zone_ref: zone reference, can be name, href or Zone :raises EngineCommandFailed: failure creating interface :return: None See :class:`smc.core.sub_interfaces.CaptureInterface` for more information
3.086579
3.434628
0.898665
interfaces = {'interface_id': interface_id, 'interfaces': [{'nodes': [{'address': address, 'network_value': network_value}]}], 'zone_ref': zone_ref, 'comment': comment} interfaces.update(kw) if 'single_fw' in self._engine.type: # L2FW / IPS interfaces.update(interface='single_node_interface') try: interface = self._engine.interface.get(interface_id) interface._add_interface(**interfaces) return interface.update() except InterfaceNotFound: interface = Layer3PhysicalInterface(**interfaces) return self._engine.add_interface(interface)
def add_layer3_interface(self, interface_id, address, network_value, zone_ref=None, comment=None, **kw)
Add a layer 3 interface on a non-clustered engine. For Layer 2 FW and IPS engines, this interface type represents a layer 3 routed (node dedicated) interface. For clusters, use the cluster related methods such as :func:`add_cluster_virtual_interface` :param str,int interface_id: interface identifier :param str address: ip address :param str network_value: network/cidr (12.12.12.0/24) :param str zone_ref: zone reference, can be name, href or Zone :param kw: keyword arguments are passed to the sub-interface during create time. If the engine is a single FW, the sub-interface type is :class:`smc.core.sub_interfaces.SingleNodeInterface`. For all other engines, the type is :class:`smc.core.sub_interfaces.NodeInterface` For example, pass 'backup_mgt=True' to enable this interface as the management backup. :raises EngineCommandFailed: failure creating interface :return: None .. note:: If an existing ip address exists on the interface and zone_ref is provided, this value will overwrite any previous zone definition.
5.936561
5.177251
1.146663
interfaces = {'nodes': [{'address': address, 'network_value': network_value}] if address and network_value else [], 'zone_ref': zone_ref, 'virtual_mapping': virtual_mapping, 'virtual_resource_name': virtual_resource_name, 'comment': comment} interfaces.update(**kw) _interface = {'interface_id': interface_id, 'interfaces': [interfaces]} if 'single_fw' in self._engine.type: # L2FW / IPS _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: interfaces.update(vlan_id=vlan_id) interface._add_interface(**_interface) else: _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 = Layer3PhysicalInterface(**_interface) return self._engine.add_interface(interface)
def add_layer3_vlan_interface(self, interface_id, vlan_id, address=None, network_value=None, virtual_mapping=None, virtual_resource_name=None, zone_ref=None, comment=None, **kw)
Add a Layer 3 VLAN interface. Optionally specify an address and network if assigning an IP to the VLAN. This method will also assign an IP address to an existing VLAN, or add an additional address to an existing VLAN. This method may commonly be used on a Master Engine to create VLANs for virtual firewall engines. Example of creating a VLAN and passing kwargs to define a DHCP server service on the VLAN interface:: engine = Engine('engine1') engine.physical_interface.add_layer3_vlan_interface(interface_id=20, vlan_id=20, address='20.20.20.20', network_value='20.20.20.0/24', comment='foocomment', dhcp_server_on_interface={ 'default_gateway': '20.20.20.1', 'default_lease_time': 7200, 'dhcp_address_range': '20.20.20.101-20.20.20.120', 'dhcp_range_per_node': [], 'primary_dns_server': '8.8.8.8'}) :param str,int interface_id: interface identifier :param int vlan_id: vlan identifier :param str address: optional IP address to assign to VLAN :param str network_value: network cidr if address is specified. In format: 10.10.10.0/24. :param str zone_ref: zone to use, by name, href, or Zone :param str comment: optional comment for VLAN level of interface :param int virtual_mapping: virtual engine mapping id See :class:`smc.core.engine.VirtualResource.vfw_id` :param str virtual_resource_name: name of virtual resource See :class:`smc.core.engine.VirtualResource.name` :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
4.139026
4.201827
0.985054
interfaces = [{'nodes': nodes if nodes else [], 'cluster_virtual': cluster_virtual, 'network_value': network_value}] try: interface = self._engine.interface.get(interface_id) interface._add_interface(interface_id, interfaces=interfaces) return interface.update() except InterfaceNotFound: interface = ClusterPhysicalInterface( engine=self._engine, interface_id=interface_id, interfaces=interfaces, cvi_mode=cvi_mode if macaddress else 'none', macaddress=macaddress, zone_ref=zone_ref, comment=comment, **kw) return self._engine.add_interface(interface)
def add_layer3_cluster_interface(self, interface_id, cluster_virtual=None, network_value=None, macaddress=None, nodes=None, cvi_mode='packetdispatch', zone_ref=None, comment=None, **kw)
Add cluster virtual interface. A "CVI" interface is used as a VIP address for clustered engines. Providing 'nodes' will create the node specific interfaces. You can also add a cluster address with only a CVI, or only NDI's. Add CVI only:: engine.physical_interface.add_cluster_virtual_interface( interface_id=30, cluster_virtual='30.30.30.1', network_value='30.30.30.0/24', macaddress='02:02:02:02:02:06') Add NDI's only:: engine.physical_interface.add_cluster_virtual_interface( interface_id=30, nodes=nodes) Add CVI and NDI's:: engine.physical_interface.add_cluster_virtual_interface( cluster_virtual='5.5.5.1', network_value='5.5.5.0/24', macaddress='02:03:03:03:03:03', 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}]) .. versionchanged:: 0.6.1 Renamed from add_cluster_virtual_interface :param str,int interface_id: physical interface identifier :param str cluster_virtual: CVI address (VIP) for this interface :param str network_value: network value for VIP; format: 10.10.10.0/24 :param str macaddress: mandatory mac address if cluster_virtual and cluster_mask provided :param list nodes: list of dictionary items identifying cluster nodes :param str cvi_mode: packetdispatch is recommended setting :param str zone_ref: zone reference, can be name, href or Zone :param kw: key word arguments are valid NodeInterface sub-interface settings passed in during create time. For example, 'backup_mgt=True' to enable this interface as the management backup. :raises EngineCommandFailed: failure creating interface :return: None
3.782468
3.959074
0.955392
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='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.
3.426574
3.770094
0.908883
interface_spec = {'interface_id': interface_id, 'second_interface_id': second_interface_id, 'interface': kw.get('interface') if self._engine.type in ('single_fw', 'fw_cluster') else 'inline_interface'} _interface = {'logical_interface_ref': logical_interface_ref, 'failure_mode': failure_mode, 'zone_ref': zone_ref, 'second_zone_ref': second_zone_ref, 'comment': comment} vlan = {'vlan_id': vlan_id, 'second_vlan_id': second_vlan_id} try: inline_id = '{}-{}'.format(interface_id, second_interface_id) interface = self._engine.interface.get(inline_id) _interface.update(vlan) interface_spec.update(interfaces=[_interface]) interface._add_interface(**interface_spec) return interface.update() except InterfaceNotFound: _interface.update(interfaces=[vlan]) interface_spec.update(_interface) interface = Layer2PhysicalInterface(**interface_spec) return self._engine.add_interface(interface)
def add_inline_interface(self, interface_id, second_interface_id, logical_interface_ref=None, vlan_id=None, second_vlan_id=None, zone_ref=None, second_zone_ref=None, failure_mode='normal', comment=None, **kw)
Add an inline interface pair. This method is only for IPS or L2FW engine types. :param str interface_id: interface id of first interface :param str second_interface_id: second interface pair id :param str, href logical_interface_ref: logical interface by href or name :param str vlan_id: vlan ID for first interface in pair :param str second_vlan_id: vlan ID for second interface in pair :param str, href zone_ref: zone reference by name or href for first interface :param str, href second_zone_ref: zone reference by nae or href for second interface :param str failure_mode: normal or bypass :param str comment: optional comment :raises EngineCommandFailed: failure creating interface :return: None
3.159921
3.317235
0.952577
_interface = {'interface_id': interface_id, 'second_interface_id': second_interface_id, 'logical_interface_ref': logical_interface_ref, 'failure_mode': failure_mode, 'zone_ref': zone_ref, 'second_zone_ref': second_zone_ref, 'comment': comment, 'interface': 'inline_ips_interface', 'vlan_id': vlan_id} return self.add_inline_interface(**_interface)
def add_inline_ips_interface(self, interface_id, second_interface_id, logical_interface_ref=None, vlan_id=None, failure_mode='normal', zone_ref=None, second_zone_ref=None, comment=None)
.. versionadded:: 0.5.6 Using an inline interface on a layer 3 FW requires SMC and engine version >= 6.3. An inline IPS interface is a new interface type for Layer 3 NGFW engines version >=6.3. Traffic passing an Inline IPS interface will have a access rule default action of Allow. Inline IPS interfaces are bypass capable. When using bypass interfaces and NGFW is powered off, in an offline state or overloaded, traffic is allowed through without inspection regardless of the access rules. If the interface does not exist and a VLAN id is specified, the logical interface and zones will be applied to the top level physical interface. If adding VLANs to an existing inline ips pair, the logical and zones will be applied to the VLAN. :param str interface_id: first interface in the interface pair :param str second_interface_id: second interface in the interface pair :param str logical_interface_ref: logical interface name, href or LogicalInterface. If None, 'default_eth' logical interface will be used. :param str vlan_id: optional VLAN id for first interface pair :param str failure_mode: 'normal' or 'bypass' (default: normal). Bypass mode requires fail open interfaces. :param zone_ref: zone for first interface in pair, can be name, str href or Zone :param second_zone_ref: zone for second interface in pair, can be name, str href or Zone :param str comment: comment for this interface :raises EngineCommandFailed: failure creating interface :return: None .. note:: Only a single VLAN is supported on this inline pair type
2.21162
2.558869
0.864296
_interface = {'interface_id': interface_id, 'second_interface_id': second_interface_id, 'logical_interface_ref': logical_interface_ref, 'failure_mode': 'normal', 'zone_ref': zone_ref, 'second_zone_ref': second_zone_ref, 'comment': comment, 'interface': 'inline_l2fw_interface', 'vlan_id': vlan_id} return self.add_inline_interface(**_interface)
def add_inline_l2fw_interface(self, interface_id, second_interface_id, logical_interface_ref=None, vlan_id=None, zone_ref=None, second_zone_ref=None, comment=None)
.. versionadded:: 0.5.6 Requires NGFW engine >=6.3 and layer 3 FW or cluster An inline L2 FW interface is a new interface type for Layer 3 NGFW engines version >=6.3. Traffic passing an Inline Layer 2 Firewall interface will have a default action in access rules of Discard. Layer 2 Firewall interfaces are not bypass capable, so when NGFW is powered off, in an offline state or overloaded, traffic is blocked on this interface. If the interface does not exist and a VLAN id is specified, the logical interface and zones will be applied to the top level physical interface. If adding VLANs to an existing inline ips pair, the logical and zones will be applied to the VLAN. :param str interface_id: interface id; '1-2', '3-4', etc :param str logical_interface_ref: logical interface name, href or LogicalInterface. If None, 'default_eth' logical interface will be used. :param str vlan_id: optional VLAN id for first interface pair :param str vlan_id2: optional VLAN id for second interface pair :param zone_ref_intf1: zone for first interface in pair, can be name, str href or Zone :param zone_ref_intf2: zone for second interface in pair, can be name, str href or Zone :raises EngineCommandFailed: failure creating interface :return: None .. note:: Only a single VLAN is supported on this inline pair type
2.704397
3.365203
0.803636
_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)
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
5.265389
5.397703
0.975487
_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)
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
4.438453
4.948897
0.896857
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)
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
3.616055
3.879128
0.932182
try: from urllib.parse import urlparse except ImportError: from urlparse import urlparse smc_address = os.environ.get('SMC_ADDRESS', '') smc_apikey = os.environ.get('SMC_API_KEY', '') smc_timeout = os.environ.get('SMC_TIMEOUT', None) api_version = os.environ.get('SMC_API_VERSION', None) domain = os.environ.get('SMC_DOMAIN', None) smc_extra_args = os.environ.get('SMC_EXTRA_ARGS', '') if not smc_apikey or not smc_address: raise ConfigLoadError( 'If loading from environment variables, you must provide values ' 'SMC_ADDRESS and SMC_API_KEY.') config_dict = {} if smc_extra_args: try: args_as_dict = json.loads(smc_extra_args) config_dict.update(args_as_dict) except ValueError: pass config_dict.update(smc_apikey=smc_apikey) config_dict.update(timeout=smc_timeout) config_dict.update(api_version=api_version) config_dict.update(domain=domain) url = urlparse(smc_address) config_dict.update(smc_address=url.hostname) port = url.port if not port: port = '8082' config_dict.update(smc_port=port) if url.scheme == 'https': config_dict.update(smc_ssl=True) ssl_cert = os.environ.get('SMC_CLIENT_CERT', None) if ssl_cert: # Enable cert validation config_dict.update(verify_ssl=True) config_dict.update(ssl_cert_file=ssl_cert) # Else http return transform_login(config_dict)
def load_from_environ()
Load the SMC URL, API KEY and optional SSL certificate from the environment. Fields are:: SMC_ADDRESS=http://1.1.1.1:8082 SMC_API_KEY=123abc SMC_CLIENT_CERT=path/to/cert SMC_TIMEOUT = 30 (seconds) SMC_API_VERSION = 6.1 (optional - uses latest by default) SMC_DOMAIN = name of domain, Shared is default SMC_EXTRA_ARGS = string in dict format of extra args needed SMC_CLIENT CERT is only checked IF the SMC_URL is an HTTPS url. Example of forcing retry on service unavailable:: os.environ['SMC_EXTRA_ARGS'] = '{"retry_on_busy": "True"}'
2.401354
2.217513
1.082904
required = ['smc_address', 'smc_apikey'] bool_type = ['smc_ssl', 'verify_ssl', 'retry_on_busy'] # boolean option flag option_names = ['smc_port', 'api_version', 'smc_ssl', 'verify_ssl', 'ssl_cert_file', 'retry_on_busy', 'timeout', 'domain'] parser = configparser.SafeConfigParser(defaults={ 'smc_port': '8082', 'api_version': None, 'smc_ssl': 'false', 'verify_ssl': 'false', 'ssl_cert_file': None, 'timeout': None, 'domain': None}, allow_no_value=True) path = '~/.smcrc' if alt_filepath is not None: full_path = alt_filepath else: ex_path = os.path.expandvars(path) full_path = os.path.expanduser(ex_path) section = 'smc' config_dict = {} try: with io.open(full_path, 'rt', encoding='UTF-8') as f: parser.readfp(f) # Get required settings, if not found it will raise err for name in required: config_dict[name] = parser.get(section, name) for name in option_names: if parser.has_option(section, name): if name in bool_type: config_dict[name] = parser.getboolean(section, name) else: # str config_dict[name] = parser.get(section, name) except configparser.NoOptionError as e: raise ConfigLoadError('Failed loading credentials from configuration ' 'file: {}; {}'.format(path, e)) except (configparser.NoSectionError, configparser.MissingSectionHeaderError) as e: raise ConfigLoadError('Failed loading credential file from: {}, check the ' 'path and verify contents are correct.'.format(path, e)) except IOError as e: raise ConfigLoadError( 'Failed loading configuration file: {}'.format(e)) return transform_login(config_dict)
def load_from_file(alt_filepath=None)
Attempt to read the SMC configuration from a dot(.) file in the users home directory. The order in which credentials are parsed is: - Passing credentials as parameters to the session login - Shared credential file (~/.smcrc) - Environment variables :param alt_filepath: Specify a different file name for the configuration file. This should be fully qualified and include the name of the configuration file to read. Configuration file should look like:: [smc] smc_address=172.18.1.150 smc_apikey=xxxxxxxxxxxxxxxxxxx api_version=6.1 smc_port=8082 smc_ssl=True verify_ssl=True retry_on_busy=True ssl_cert_file='/Users/davidlepage/home/mycacert.pem' :param str smc_address: IP of the SMC Server :param str smc_apikey: obtained from creating an API Client in SMC :param str api_version: Which version to use (default: latest) :param int smc_port: port to use for SMC, (default: 8082) :param bool smc_ssl: Whether to use SSL (default: False) :param bool verify_ssl: Verify client cert (default: False) :param bool retry_on_busy: Retry CRUD operation if service is unavailable (default: False) :param str ssl_cert_file: Full path to client pem (default: None) The only settings that are required are smc_address and smc_apikey. Setting verify_ssl to True (default) validates the client cert for SSL connections and requires the ssl_cert_file path to the cacert.pem. If not given, verify will default back to False. FQDN will be constructed from the information above.
3.095964
2.68286
1.153979
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)
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
3.018624
3.116887
0.968474
v = ['ipv4_net("%s")' % net for net in values] self.update_filter('{} IN union({})'.format(field, ','.join(v)))
def within_ipv4_network(self, field, values)
This filter adds specified networks to a filter to check for inclusion. :param str field: name of field to filter on. Taken from 'Show Filter Expression' within SMC. :param list values: network definitions, in cidr format, i.e: 1.1.1.0/24.
8.96422
11.225782
0.798539
v = ['ipv4("%s")' % part for iprange in values for part in iprange.split('-')] self.update_filter('{} IN range({})'.format(field, ','.join(v)))
def within_ipv4_range(self, field, values)
Add an IP range network filter for relevant address fields. Range (between) filters allow only one range be provided. :param str field: name of field to filter on. Taken from 'Show Filter Expression' within SMC. :param list values: IP range values. Values would be a list of IP's separated by a '-', i.e. ['1.1.1.1-1.1.1.254']
9.552101
11.308159
0.844709
if len(values) > 1: v = ['ipv4("%s")' % ip for ip in values] value='{} IN union({})'.format(field, ','.join(v)) else: value='{} == ipv4("{}")'.format(field, values[0]) self.update_filter(value)
def exact_ipv4_match(self, field, values)
An exact IPv4 address match on relevant address fields. :param str field: name of field to filter on. Taken from 'Show Filter Expression' within SMC. :param list values: value/s to add. If more than a single value is provided, the query is modified to use UNION vs. == :param bool complex: A complex filter is one which requires AND'ing or OR'ing values. Set to return the filter before committing.
4.431376
4.835484
0.916429
return Task.execute(self, 'download', timeout=timeout, wait_for_finish=wait_for_finish)
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
4.689965
5.354835
0.875837
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)
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
4.364499
5.421875
0.80498
attribute = self._attr[0] return self.profile.data.get(attribute, [])
def all(self)
Return all entries :rtype: list(dict)
19.124475
17.443121
1.096391
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)
Create a Sandbox Service element
3.38814
3.576215
0.94741
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)
Get all available API versions for this SMC :return version numbers :rtype: list
3.329539
3.215058
1.035608
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)
Get the API version specified or resolve the latest version :return api version :rtype: float
3.197545
3.591645
0.890273
manager = getattr(SMCRequest, '_session_manager') if manager is not None: return manager manager = SessionManager(sessions) manager.mount() return manager
def create(cls, sessions=None)
A session manager will be mounted to the SMCRequest class through this classmethod. If there is already an existing SessionManager, that is returned instead. :param list sessions: a list of Session objects :rtype: SessionManager
11.150307
4.312398
2.58564
if self._sessions: return self.get_session(next(iter(self._sessions))) return self.get_session()
def get_default_session(self)
The default session is nothing more than the first session added into the session handler pool. This will likely change in the future but for now each session identifies the domain and also manages domain switching within a single session. :rtype: Session
4.858835
4.930565
0.985452
if session.session_id: self._sessions[session.name] = session
def _register(self, session)
Register a session
8.11588
6.783164
1.196474
if session in self: self._sessions.pop(self._get_session_key(session), None)
def _deregister(self, session)
Deregister a session.
6.128586
4.954195
1.23705
manager = SMCRequest._session_manager if not self._manager \ else self._manager if not manager: raise SessionManagerNotFound('A session manager was not found. ' 'This is an initialization error binding the SessionManager. ') return manager
def manager(self)
Return the session manager for this session :rtype: SessionManager
13.108052
13.845186
0.946759
return None if not self.session or 'JSESSIONID' not in \ self.session.cookies else 'JSESSIONID={}'.format( self.session.cookies['JSESSIONID'])
def session_id(self)
The session ID in header type format. Can be inserted into a connection if necessary using:: {'Cookie': session.session_id} :rtype: str
5.00975
5.077919
0.986575
if self.session: # protect cached property from being set before session try: return self.current_user.name except AttributeError: # TODO: Catch ConnectionError? No session pass return hash(self)
def name(self)
Return the administrator name for this session. Can be None if the session has not yet been established. .. note:: The administrator name was introduced in SMC version 6.4. Previous versions will show the unique session identifier for this session. :rtype: str
19.05998
20.942871
0.910094
if self.session: try: response = self.session.get(self.entry_points.get('current_user')) if response.status_code in (200, 201): admin_href=response.json().get('value') request = SMCRequest(href=admin_href) smcresult = send_request(self, 'get', request) return ElementFactory(admin_href, smcresult) except UnsupportedEntryPoint: pass
def current_user(self)
.. versionadded:: 0.6.0 Requires SMC version >= 6.4 Return the currently logged on API Client user element. :raises UnsupportedEntryPoint: Current user is only supported with SMC version >= 6.4 :rtype: Element
6.71226
4.76009
1.410112
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)
Build the authentication request to SMC
5.261258
5.253921
1.001396
_session = requests.session() # empty session response = _session.post(**request) logger.info('Using SMC API version: %s', self.api_version) if response.status_code != 200: raise SMCConnectionError( 'Login failed, HTTP status code: %s and reason: %s' % ( response.status_code, response.reason)) return _session
def _get_session(self, request)
Authenticate the request dict :param dict request: request dict built from user input :raises SMCConnectionError: failure to connect :return: python requests session :rtype: requests.Session
4.778089
3.821844
1.250205
if not self.session: self.manager._deregister(self) return try: r = self.session.put(self.entry_points.get('logout')) if r.status_code == 204: logger.info('Logged out admin: %s of domain: %s successfully', self.name, self.domain) else: logger.error('Logout status was unexpected. Received response ' 'with status code: %s', (r.status_code)) except requests.exceptions.SSLError as e: logger.error('SSL exception thrown during logout: %s', e) except requests.exceptions.ConnectionError as e: logger.error('Connection error on logout: %s', e) finally: self.entry_points.clear() self.manager._deregister(self) self._session = None try: delattr(self, 'current_user') except AttributeError: pass logger.debug('Call counters: %s' % counters)
def logout(self)
Logout session from SMC :return: None
3.804637
3.842079
0.990255
if self.session and self.session_id: # Did session timeout? logger.info('Session timed out, will try obtaining a new session using ' 'previously saved credential information.') self.logout() # Force log out session just in case return self.login(**self.copy()) raise SMCConnectionError('Session expired and attempted refresh failed.')
def refresh(self)
Refresh session on 401. This is called automatically if your existing session times out and resends the operation/s which returned the error. :raises SMCConnectionError: Problem re-authenticating using existing api credentials
14.926502
11.7343
1.27204
if self.domain != domain: if self in self.manager: # Exit current domain self.logout() logger.info('Switching to domain: %r and creating new session', domain) params = self.copy() params.update(domain=domain) self.login(**params)
def switch_domain(self, domain)
Switch from one domain to another. You can call session.login() with a domain key value to log directly into the domain of choice or alternatively switch from domain to domain. The user must have permissions to the domain or unauthorized will be returned. In addition, when switching domains, you will be logged out of the current domain to close the connection pool associated with the previous session. This prevents potentially excessive open connections to SMC :: session.login() # Log in to 'Shared Domain' ... session.switch_domain('MyDomain') :raises SMCConnectionError: Error logging in to specified domain. This typically means the domain either doesn't exist or the user does not have privileges to that domain.
6.786952
6.618984
1.025377
if self.session: from requests.adapters import HTTPAdapter from requests.packages.urllib3.util.retry import Retry method_whitelist = kwargs.pop('method_whitelist', []) or ['GET', 'POST', 'PUT'] status_forcelist = frozenset(status_forcelist) if status_forcelist else frozenset([503]) retry = Retry( total=total, backoff_factor=backoff_factor, status_forcelist=status_forcelist, method_whitelist=method_whitelist) for proto_str in ('http://', 'https://'): self.session.mount(proto_str, HTTPAdapter(max_retries=retry)) logger.debug('Mounting retry object to HTTP session: %s' % retry)
def set_retry_on_busy(self, total=5, backoff_factor=0.1, status_forcelist=None, **kwargs)
Mount a custom retry object on the current session that allows service level retries when the SMC might reply with a Service Unavailable (503) message. This can be possible in larger environments with higher database activity. You can all this on the existing session, or provide as a dict to the login constructor. :param int total: total retries :param float backoff_factor: when to retry :param list status_forcelist: list of HTTP error codes to retry on :param list method_whitelist: list of methods to apply retries for, GET, POST and PUT by default :return: None
2.520377
2.356696
1.069454
if self.session and self.session_id: schema = '{}/{}/monitoring/log/schemas'.format(self.url, self.api_version) response = self.session.get( url=schema, headers={'cookie': self.session_id, 'content-type': 'application/json'}) if response.status_code in (200, 201): return response.json()
def _get_log_schema(self)
Get the log schema for this SMC version. :return: dict
3.644708
3.496091
1.042509
return all([ getattr(self, '_%s' % field, None) is not None for field in self.CredentialMap.get(self.provider_name)])
def has_credentials(self)
Does this session have valid credentials :rtype: bool
8.687983
9.982608
0.870312
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)
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
8.750549
11.281112
0.775681
assert isinstance(data, list), "Incorrect format. Expecting list." if self.is_none or self.is_any: self.clear() self.data[self.typeof] = [] data = element_resolver(data, do_raise=False) self.data[self.typeof] = data
def add_many(self, data)
Add multiple entries to field. Entries should be list format. Entries can be of types relavant to the field type. For example, for source and destination fields, elements may be of type :py:mod:`smc.elements.network` or be the elements direct href, or a combination of both. Add several entries to existing rule:: policy = FirewallPolicy('policy') for rule in policy.fw_ipv4_nat_rules.all(): if rule.name == 'therule': rule.sources.add_many([Host('myhost'), 'http://1.1.1.1/hosts/12345']) rule.save() :param list data: list of sources .. note:: If submitting type Element and the element cannot be found, it will be skipped.
8.395117
8.726426
0.962034
changed = False if isinstance(elements, list): if self.is_any or self.is_none: self.add_many(elements) changed = True else: _elements = element_resolver(elements, do_raise=False) if set(self.all_as_href()) ^ set(_elements): self.data[self.typeof] = _elements changed = True if changed and self.rule and (isinstance(self, (Source, Destination)) and \ self.rule.typeof in ('fw_ipv4_nat_rule', 'fw_ipv6_nat_rule')): # Modify NAT cell if necessary self.rule._update_nat_field(self) return changed
def update_field(self, elements)
Update the field with a list of provided values but only if the values are different. Return a boolean indicating whether a change was made indicating whether `save` should be called. If the field is currently set to any or none, then no comparison is made and field is updated. :param list elements: list of elements in href or Element format to compare to existing field :rtype: bool
7.452327
6.525874
1.141966
if not self.is_any and not self.is_none: return [element for element in self.get(self.typeof)] return []
def all_as_href(self)
Return all elements without resolving to :class:`smc.elements.network` or :class:`smc.elements.service`. Just raw representation as href. :return: elements in href form :rtype: list
10.353421
9.663891
1.071351
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)
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)
10.099035
8.301178
1.216579
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)
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
2.37919
2.757985
0.862655
self.update( antivirus_http_proxy=proxy, antivirus_proxy_port=proxy_port, antivirus_proxy_user=user if user else '', antivirus_proxy_password=password if password else '', antivirus_http_proxy_enabled=True)
def http_proxy(self, proxy, proxy_port, user=None, password=None)
.. versionadded:: 0.5.7 Requires SMC and engine version >= 6.4 Set http proxy settings for Antivirus updates. :param str proxy: proxy IP address :param str,int proxy_port: proxy port :param str user: optional user for authentication
3.055886
3.095579
0.987177
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)
Enable antivirus on the engine
8.18594
7.147271
1.145324
self.update(ts_enabled=True, http_proxy=get_proxy(http_proxy))
def enable(self, http_proxy=None)
Enable URL Filtering on the engine. If proxy servers are needed, provide a list of HTTPProxy elements. :param http_proxy: list of proxies for GTI connections :type http_proxy: list(str,HttpProxy)
9.938966
10.70245
0.928663
if 'sandbox_type' in self.engine.data: if self.engine.sandbox_type == 'none': return False return True return False
def status(self)
Status of sandbox on this engine :rtype: bool
8.794971
5.670116
1.551109
self.engine.data.update(sandbox_type='none') self.pop('cloud_sandbox_settings', None) #pre-6.3 self.pop('sandbox_settings', None)
def disable(self)
Disable the sandbox on this engine.
19.431026
12.880919
1.508512
service = element_resolver(SandboxService(service), do_raise=False) or \ element_resolver(SandboxService.create(name=service, sandbox_data_center=SandboxDataCenter(sandbox_data_center))) self.update(sandbox_license_key=license_key, sandbox_license_token=license_token, sandbox_service=service, http_proxy=get_proxy(http_proxy)) self.engine.data.setdefault('sandbox_settings', {}).update(self.data) self.engine.data.update(sandbox_type=sandbox_type)
def enable(self, license_key, license_token, sandbox_type='cloud_sandbox', service='Automatic', http_proxy=None, sandbox_data_center='Automatic')
Enable sandbox on this engine. Provide a valid license key and license token obtained from your engine licensing. Requires SMC version >= 6.3. .. note:: Cloud sandbox is a feature that requires an engine license. :param str license_key: license key for specific engine :param str license_token: license token for specific engine :param str sandbox_type: 'local_sandbox' or 'cloud_sandbox' :param str,SandboxService service: a sandbox service element from SMC. The service defines which location the engine is in and which data centers to use. The default is to use the 'US Data Centers' profile if undefined. :param str,SandboxDataCenter sandbox_data_center: sandbox data center to use if the service specified does not exist. Requires SMC >= 6.4.3 :return: None
4.650909
4.828751
0.96317
for cred in credentials: href = element_resolver(cred) if href not in self.engine.server_credential: self.engine.server_credential.append(href)
def add_tls_credential(self, credentials)
Add a list of TLSServerCredential to this engine. TLSServerCredentials can be in element form or can also be the href for the element. :param credentials: list of pre-created TLSServerCredentials :type credentials: list(str,TLSServerCredential) :return: None
7.238427
5.931305
1.220377
for cred in credentials: href = element_resolver(cred) if href in self.engine.server_credential: self.engine.server_credential.remove(href)
def remove_tls_credential(self, credentials)
Remove a list of TLSServerCredentials on this engine. :param credentials: list of credentials to remove from the engine :type credentials: list(str,TLSServerCredential) :return: None
7.415232
7.491383
0.989835
validation_settings = { 'configuration_validation_for_alert_chain': False, 'duplicate_rule_check_settings': False, 'empty_rule_check_settings': True, 'empty_rule_check_settings_for_alert': False, 'general_check_settings': True, 'nat_modification_check_settings': True, 'non_supported_feature': True, 'routing_modification_check': False, 'unreachable_rule_check_settings': False, 'vpn_validation_check_settings': True} for key, value in kwargs.items(): validation_settings[key] = value return {'validation_settings': validation_settings}
def policy_validation_settings(**kwargs)
Set policy validation settings. This is used when policy based tasks are created and `validate_policy` is set to True. The following kwargs can be overridden in the create constructor. :param bool configuration_validation_for_alert_chain: default False :param bool duplicate_rule_check_settings: default False :param bool empty_rule_check_settings: default True :param bool emtpy_rule_check_settings_for_alert: default False :param bool general_check_settings: default True :param bool nat_modification_check_settings: default True :param bool non_supported_feature: default True :param bool routing_modification_check: default False :param bool unreachable_rule_check_settings: default False :param bool vpn_validation_check_settings: default True :return: dict of validation settings
4.399518
1.461101
3.011099
log_types = { 'for_alert_event_log': False, 'for_alert_log': False, 'for_audit_log': False, 'for_fw_log': False, 'for_ips_log': False, 'for_ips_recording_log': False, 'for_l2fw_log': False, 'for_third_party_log': False} if all_logs: for key in log_types.keys(): log_types[key] = True else: for key, value in kwargs.items(): log_types[key] = value return log_types
def log_target_types(all_logs=False, **kwargs)
Log targets for log tasks. A log target defines the log types that will be affected by the operation. For example, when creating a DeleteLogTask, you can specify which log types are deleted. :param bool for_alert_event_log: alert events traces (default: False) :param bool for_alert_log: alerts (default: False) :param bool for_fw_log: FW logs (default: False) :param bool for_ips_log: IPS logs (default: False) :param bool for_ips_recording: any IPS pcaps (default: False) :param bool for_l2fw_log: layer 2 FW logs (default: False) :param bool for_third_party_log: any 3rd party logs (default: False) :return: dict of log targets
2.801634
1.785453
1.569145
if 'activate' in self.data.links: self.make_request( ActionCommandFailed, method='update', etag=self.etag, resource='activate') self._del_cache() else: raise ActionCommandFailed('Task is already activated. To ' 'suspend, call suspend() on this task schedule')
def activate(self)
If a task is suspended, this will re-activate the task. Usually it's best to check for activated before running this:: task = RefreshPolicyTask('mytask') for scheduler in task.task_schedule: if scheduler.activated: scheduler.suspend() else: scheduler.activate()
14.490174
11.451509
1.265351
json = { 'name': name, 'activation_date': activation_date, 'day_period': day_period, 'day_mask': day_mask, 'activated': activated, 'final_action': final_action, 'minute_period': minute_period, 'repeat_until_date': repeat_until_date if repeat_until_date else None, 'comment': comment} if 'daily' in day_period: minute_period = minute_period if minute_period != 'one_time' else 'hourly' json['minute_period'] = minute_period return self.make_request( ActionCommandFailed, method='create', resource='task_schedule', json=json)
def add_schedule(self, name, activation_date, day_period='one_time', final_action='ALERT_FAILURE', activated=True, minute_period='one_time', day_mask=None, repeat_until_date=None, comment=None)
Add a schedule to an existing task. :param str name: name for this schedule :param int activation_date: when to start this task. Activation date should be a UTC time represented in milliseconds. :param str day_period: when this task should be run. Valid options: 'one_time', 'daily', 'weekly', 'monthly', 'yearly'. If 'daily' is selected, you can also provide a value for 'minute_period'. (default: 'one_time') :param str minute_period: only required if day_period is set to 'daily'. Valid options: 'each_quarter' (15 min), 'each_half' (30 minutes), or 'hourly', 'one_time' (default: 'one_time') :param int day_mask: If the task day_period=weekly, then specify the day or days for repeating. Day masks are: sun=1, mon=2, tue=4, wed=8, thu=16, fri=32, sat=64. To repeat for instance every Monday, Wednesday and Friday, the value must be 2 + 8 + 32 = 42 :param str final_action: what type of action to perform after the scheduled task runs. Options are: 'ALERT_FAILURE', 'ALERT', or 'NO_ACTION' (default: ALERT_FAILURE) :param bool activated: whether to activate the schedule (default: True) :param str repeat_until_date: if this is anything but a one time task run, you can specify the date when this task should end. The format is the same as the `activation_date` param. :param str comment: optional comment :raises ActionCommandFailed: failed adding schedule :return: None
2.463785
2.340596
1.052631
json = { 'resources': [engine.href for engine in engines], 'name': name, 'comment': comment} if validate_policy: json.update(policy_validation_settings(**kwargs)) return ElementCreator(cls, json)
def create(cls, name, engines, comment=None, validate_policy=True, **kwargs)
Create a refresh policy task associated with specific engines. A policy refresh task does not require a policy be specified. The policy used in the refresh will be the policy already assigned to the engine. :param str name: name of this task :param engines: list of Engines for the task :type engines: list(Engine) :param str comment: optional comment :param bool validate_policy: validate the policy before upload. If set to true, validation kwargs can also be provided if customization is required, otherwise default validation settings are used. :param kwargs: see :func:`~policy_validation_settings` for keyword arguments and default values. :raises ElementNotFound: engine specified does not exist :raises CreateElementFailed: failure to create the task :return: the task :rtype: RefreshPolicyTask
5.126545
4.693594
1.092243
json = { 'name': name, 'resources': [eng.href for eng in engines], 'policy': policy.href if policy is not None else policy, 'comment': comment} if kwargs: json.update(policy_validation_settings(**kwargs)) return ElementCreator(cls, json)
def create(cls, name, engines, policy=None, comment=None, **kwargs)
Create a new validate policy task. If a policy is not specified, the engines existing policy will be validated. Override default validation settings as kwargs. :param str name: name of task :param engines: list of engines to validate :type engines: list(Engine) :param Policy policy: policy to validate. Uses the engines assigned policy if none specified. :param kwargs: see :func:`~policy_validation_settings` for keyword arguments and default values. :raises ElementNotFound: engine or policy specified does not exist :raises CreateElementFailed: failure to create the task :return: the task :rtype: ValidatePolicyTask
5.437113
4.609869
1.179451
json = { 'name': name, 'comment': comment, 'resources': [eng.href for eng in master_engines if isinstance(eng, MasterEngine)]} return ElementCreator(cls, json)
def create(cls, name, master_engines, comment=None)
Create a refresh task for master engines. :param str name: name of task :param master_engines: list of master engines for this task :type master_engines: list(MasterEngine) :param str comment: optional comment :raises CreateElementFailed: failed to create the task :return: the task :rtype: RefreshMasterEnginePolicyTask
6.622912
9.044747
0.732238
if not servers: servers = [svr.href for svr in ManagementServer.objects.all()] servers.extend([svr.href for svr in LogServer.objects.all()]) else: servers = [svr.href for svr in servers] filter_for_delete = filter_for_delete.href if filter_for_delete else \ FilterExpression('Match All').href json = { 'name': name, 'resources': servers, 'time_limit_type': time_range, 'start_time': 0, 'end_time': 0, 'file_format': 'unknown', 'filter_for_delete': filter_for_delete, 'comment': comment} json.update(**log_target_types(all_logs, **kwargs)) return ElementCreator(cls, json)
def create(cls, name, servers=None, time_range='yesterday', all_logs=False, filter_for_delete=None, comment=None, **kwargs)
Create a new delete log task. Provide True to all_logs to delete all log types. Otherwise provide kwargs to specify each log by type of interest. :param str name: name for this task :param servers: servers to back up. Servers must be instances of management servers or log servers. If no value is provided, all servers are backed up. :type servers: list(ManagementServer or LogServer) :param str time_range: specify a time range for the deletion. Valid options are 'yesterday', 'last_full_week_sun_sat', 'last_full_week_mon_sun', 'last_full_month' (default 'yesterday') :param FilterExpression filter_for_delete: optional filter for deleting. (default: FilterExpression('Match All') :param bool all_logs: if True, all log types will be deleted. If this is True, kwargs are ignored (default: False) :param kwargs: see :func:`~log_target_types` for keyword arguments and default values. :raises ElementNotFound: specified servers were not found :raises CreateElementFailed: failure to create the task :return: the task :rtype: DeleteLogTask
4.397586
3.105177
1.416211
if not servers: servers = [svr.href for svr in ManagementServer.objects.all()] servers.extend([svr.href for svr in LogServer.objects.all()]) else: servers = [svr.href for svr in servers] json = { 'resources': servers, 'name': name, 'password': encrypt_password if encrypt_password else None, 'log_data_must_be_saved': backup_log_data, 'comment': comment} return ElementCreator(cls, json)
def create(cls, name, servers, backup_log_data=False, encrypt_password=None, comment=None)
Create a new server backup task. This task provides the ability to backup individual or all management and log servers under SMC management. :param str name: name of task :param servers: servers to back up. Servers must be instances of management servers or log servers. If no value is provided all servers are backed up. :type servers: list(ManagementServer or LogServer) :param bool backup_log_data: Should the log files be backed up. This field is only relevant if a Log Server is backed up. :param str encrypt_password: Provide an encrypt password if you want this backup to be encrypted. :param str comment: optional comment :raises ElementNotFound: specified servers were not found :raises CreateElementFailed: failure to create the task :return: the task :rtype: ServerBackupTask
4.027891
3.388191
1.188803
json = { 'name': name, 'comment': comment, 'resources': [engine.href for engine in engines], 'include_core_files': include_core_files, 'include_slapcat_output': include_slapcat_output} return ElementCreator(cls, json)
def create(cls, name, engines, include_core_files=False, include_slapcat_output=False, comment=None)
Create an sginfo task. :param str name: name of task :param engines: list of engines to apply the sginfo task :type engines: list(Engine) :param bool include_core_files: include core files in the sginfo backup (default: False) :param bool include_slapcat_output: include output from a slapcat command in output (default: False) :raises ElementNotFound: engine not found :raises CreateElementFailed: create the task failed :return: the task :rtype: SGInfoTask
2.97568
3.739731
0.795694
if user_session.session: session = user_session.session # requests session try: method = method.upper() if method else '' if method == GET: if request.filename: # File download request return file_download(user_session, request) response = session.get( request.href, params=request.params, headers=request.headers, timeout=user_session.timeout) response.encoding = 'utf-8' counters.update(read=1) if logger.isEnabledFor(logging.DEBUG): debug(response) if response.status_code not in (200, 204, 304): raise SMCOperationFailure(response) elif method == POST: if request.files: # File upload request return file_upload(user_session, method, request) response = session.post( request.href, data=json.dumps(request.json, cls=CacheEncoder), headers=request.headers, params=request.params) response.encoding = 'utf-8' counters.update(create=1) if logger.isEnabledFor(logging.DEBUG): debug(response) if response.status_code not in (200, 201, 202): # 202 is asynchronous response with follower link raise SMCOperationFailure(response) elif method == PUT: if request.files: # File upload request return file_upload(user_session, method, request) # Etag should be set in request object request.headers.update(Etag=request.etag) response = session.put( request.href, data=json.dumps(request.json, cls=CacheEncoder), params=request.params, headers=request.headers) counters.update(update=1) if logger.isEnabledFor(logging.DEBUG): debug(response) if response.status_code != 200: raise SMCOperationFailure(response) elif method == DELETE: response = session.delete( request.href, headers=request.headers) counters.update(delete=1) # Conflict (409) if ETag is not current if response.status_code in (409,): req = session.get(request.href) etag = req.headers.get('ETag') response = session.delete( request.href, headers={'if-match': etag}) response.encoding = 'utf-8' if logger.isEnabledFor(logging.DEBUG): debug(response) if response.status_code not in (200, 204): raise SMCOperationFailure(response) else: # Unsupported method return SMCResult(msg='Unsupported method: %s' % method, user_session=user_session) except SMCOperationFailure as error: if error.code in (401,): user_session.refresh() return send_request(user_session, method, request) raise error except requests.exceptions.RequestException as e: raise SMCConnectionError('Connection problem to SMC, ensure the API ' 'service is running and host is correct: %s, exiting.' % e) else: return SMCResult(response, user_session=user_session) else: raise SMCConnectionError('No session found. Please login to continue')
def send_request(user_session, method, request)
Send request to SMC :param Session user_session: session object :param str method: method for request :param SMCRequest request: request object :raises SMCOperationFailure: failure with reason :rtype: SMCResult
2.495081
2.427534
1.027826
logger.debug('Download file: %s', vars(request)) response = user_session.session.get( request.href, params=request.params, headers=request.headers, stream=True) if response.status_code == 200: logger.debug('Streaming to file... Content length: %s', len(response.content)) try: path = os.path.abspath(request.filename) logger.debug('Operation: %s, saving to file: %s', request.href, path) with open(path, "wb") as handle: for chunk in response.iter_content(chunk_size=1024): if chunk: handle.write(chunk) handle.flush() except IOError as e: raise IOError('Error attempting to save to file: {}'.format(e)) result = SMCResult(response, user_session=user_session) result.content = path return result else: raise SMCOperationFailure(response)
def file_download(user_session, request)
Called when GET request specifies a filename to retrieve. :param Session user_session: session object :param SMCRequest request: request object :raises SMCOperationFailure: failure with reason :rtype: SMCResult
2.991756
2.698673
1.108603
logger.debug('Upload: %s', vars(request)) http_command = getattr(user_session.session, method.lower()) try: response = http_command( request.href, params=request.params, files=request.files) except AttributeError: raise TypeError('File specified in request was not readable: %s' % request.files) else: if response.status_code in (200, 201, 202, 204): logger.debug('Success sending file in elapsed time: %s', response.elapsed) return SMCResult(response, user_session=user_session) raise SMCOperationFailure(response)
def file_upload(user_session, method, request)
Perform a file upload PUT/POST to SMC. Request should have the files attribute set which will be an open handle to the file that will be binary transfer. :param Session user_session: session object :param str method: method to use, could be put or post :param SMCRequest request: request object :raises SMCOperationFailure: failure with reason :rtype: SMCResult
4.865666
3.984157
1.221254
self.update(name='{} node {}'.format(name, self.nodeid))
def rename(self, name)
Rename this node :param str name: new name for node
17.523674
15.48306
1.131797
loopback = loopback_ndi if loopback_ndi else [] node = {node_type: { 'activate_test': True, 'disabled': False, 'loopback_node_dedicated_interface': loopback, 'name': name + ' node ' + str(nodeid), 'nodeid': nodeid} } return node
def _create(cls, name, node_type, nodeid=1, loopback_ndi=None)
Create the node/s for the engine. This isn't called directly, instead it is used when engine.create() is called :param str name: name of node :param str node_type: based on engine type specified :param int nodeid: used to identify which node :param list LoopbackInterface loopback_ndi: optional loopback interface for node.
5.105617
6.060761
0.842405
for lb in self.data.get('loopback_node_dedicated_interface', []): yield LoopbackInterface(lb, self._engine)
def loopback_interface(self)
Loopback interfaces for this node. This will return empty if the engine is not a layer 3 firewall type:: >>> engine = Engine('dingo') >>> for node in engine.nodes: ... for loopback in node.loopback_interface: ... loopback ... LoopbackInterface(address=172.20.1.1, nodeid=1, rank=1) LoopbackInterface(address=172.31.1.1, nodeid=1, rank=2) LoopbackInterface(address=2.2.2.2, nodeid=1, rank=3) :rtype: list(LoopbackInterface)
14.313285
12.813774
1.117023
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)
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
6.779589
7.215545
0.939581
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)
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
3.880246
3.521926
1.10174
result = self.make_request( NodeCommandFailed, resource='appliance_status') return InterfaceStatus(result.get('interface_statuses', []))
def interface_status(self)
Obtain the interface status for this node. This will return an iterable that provides information about the existing interfaces. Retrieve a single interface status:: >>> node = engine.nodes[0] >>> node Node(name=ngf-1065) >>> node.interface_status <smc.core.node.InterfaceStatus object at 0x103b2f310> >>> node.interface_status.get(0) InterfaceStatus(aggregate_is_active=False, capability=u'Normal Interface', flow_control=u'AutoNeg: off Rx: off Tx: off', interface_id=0, mtu=1500, name=u'eth0_0', port=u'Copper', speed_duplex=u'1000 Mb/s / Full / Automatic', status=u'Up') Or iterate and get all interfaces:: >>> for stat in node.interface_status: ... stat ... InterfaceStatus(aggregate_is_active=False, capability=u'Normal Interface', ... ... :raises NodeCommandFailed: failure to retrieve current status :rtype: InterfaceStatus
17.675579
13.230938
1.335928
result = self.make_request( NodeCommandFailed, resource='appliance_status') return HardwareStatus(result.get('hardware_statuses', []))
def hardware_status(self)
Obtain hardware statistics for various areas of this node. See :class:`~HardwareStatus` for usage. :raises NodeCommandFailed: failure to retrieve current status :rtype: HardwareStatus
18.000675
10.806729
1.665691
self.make_request( NodeCommandFailed, method='update', resource='go_online', params={'comment': comment})
def go_online(self, comment=None)
Executes a Go-Online operation on the specified node typically done when the node has already been forced offline via :func:`go_offline` :param str comment: (optional) comment to audit :raises NodeCommandFailed: online not available :return: None
14.927905
9.489035
1.573174
self.make_request( NodeCommandFailed, method='update', resource='go_offline', params={'comment': comment})
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
14.060353
8.855562
1.587743
self.make_request( NodeCommandFailed, method='update', resource='go_standby', params={'comment': comment})
def go_standby(self, comment=None)
Executes a Go-Standby operation on the specified node. To get the status of the current node/s, run :func:`status` :param str comment: optional comment to audit :raises NodeCommandFailed: engine cannot go standby :return: None
13.358732
9.191329
1.453406
self.make_request( NodeCommandFailed, method='update', resource='lock_online', params={'comment': comment})
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
14.279691
8.902304
1.604044
self.make_request( NodeCommandFailed, method='update', resource='lock_offline', params={'comment': comment})
def lock_offline(self, comment=None)
Executes a Lock-Offline operation on the specified node Bring back online by running :func:`go_online`. :param str comment: comment for audit :raises NodeCommandFailed: lock offline failed :return: None
13.944386
9.6386
1.446723
self.make_request( NodeCommandFailed, method='update', resource='reset_user_db', params={'comment': comment})
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
13.122217
8.478074
1.547783
params = {'filter_enabled': filter_enabled} result = self.make_request( NodeCommandFailed, resource='diagnostic', params=params) return Debug(result.get('diagnostics'))
def debug(self, filter_enabled=False)
View all debug settings for this node. This will return a debug object. View the debug object repr to identify settings to enable or disable and submit the object to :meth:`set_debug` to enable settings. Add filter_enabled=True argument to see only enabled settings :param bool filter_enabled: returns all enabled diagnostics :raises NodeCommandFailed: failure getting diagnostics :rtype: Debug .. seealso:: :class:`~Debug` for example usage
10.104628
6.888701
1.466841
self.make_request( NodeCommandFailed, method='create', resource='send_diagnostic', json=debug.serialize())
def set_debug(self, debug)
Set the debug settings for this node. This should be a modified :class:`~Debug` instance. This will take effect immediately on the specified node. :param Debug debug: debug object with specified settings :raises NodeCommandFailed: fail to communicate with node :return: None .. seealso:: :class:`~Debug` for example usage
35.626709
21.674301
1.64373
self.make_request( NodeCommandFailed, method='update', resource='reboot', params={'comment': comment})
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
14.711498
10.557408
1.393476
params = { 'include_core_files': include_core_files, 'include_slapcat_output': include_slapcat_output} result = self.make_request( NodeCommandFailed, raw_result=True, resource='sginfo', filename=filename, params=params) return result.content
def sginfo(self, include_core_files=False, include_slapcat_output=False, filename='sginfo.gz')
Get the SG Info of the specified node. Optionally provide a filename, otherwise default to 'sginfo.gz'. Once you run gzip -d <filename>, the inner contents will be in .tar format. :param include_core_files: flag to include or not core files :param include_slapcat_output: flag to include or not slapcat output :raises NodeCommandFailed: failed getting sginfo with reason :return: string path of download location :rtype: str
4.154179
4.05115
1.025432
self.make_request( NodeCommandFailed, method='update', resource='ssh', params={'enable': enable, 'comment': comment})
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
11.378252
7.693026
1.479035
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)
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
11.326008
8.432593
1.343123