sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def create(cls, name, members=None, comment=None): """ Create the TCP Service group :param str name: name of tcp service group :param list element: tcp services by element or href :type element: list(str,Element) :raises CreateElementFailed: element creation failed with reason :return: instance with meta :rtype: TCPServiceGroup """ element = [] if members is None else element_resolver(members) json = {'name': name, 'element': element, 'comment': comment} return ElementCreator(cls, json)
Create the TCP Service group :param str name: name of tcp service group :param list element: tcp services by element or href :type element: list(str,Element) :raises CreateElementFailed: element creation failed with reason :return: instance with meta :rtype: TCPServiceGroup
entailment
def generate(self, start_time=0, end_time=0, senders=None, wait_for_finish=False, timeout=5, **kw): # @ReservedAssignment """ Generate the report and optionally wait for results. You can optionally add filters to the report by providing the senders argument as a list of type Element:: report = ReportDesign('Firewall Weekly Summary') begin = datetime_to_ms(datetime.strptime("2018-02-03T00:00:00", "%Y-%m-%dT%H:%M:%S")) end = datetime_to_ms(datetime.strptime("2018-02-04T00:00:00", "%Y-%m-%dT%H:%M:%S")) report.generate(start_time=begin, end_time=end, senders=[Engine('vm')]) :param int period_begin: milliseconds time defining start time for report :param int period_end: milliseconds time defining end time for report :param senders: filter targets to use when generating report :type senders: list(Element) :param bool wait_for_finish: enable polling for results :param int timeout: timeout between polling :raises TaskRunFailed: refresh failed, possibly locked policy :rtype: TaskOperationPoller """ if start_time and end_time: kw.setdefault('params', {}).update( {'start_time': start_time, 'end_time': end_time}) if senders: kw.setdefault('json', {}).update({'senders': element_resolver(senders)}) return Task.execute(self, 'generate', timeout=timeout, wait_for_finish=wait_for_finish, **kw)
Generate the report and optionally wait for results. You can optionally add filters to the report by providing the senders argument as a list of type Element:: report = ReportDesign('Firewall Weekly Summary') begin = datetime_to_ms(datetime.strptime("2018-02-03T00:00:00", "%Y-%m-%dT%H:%M:%S")) end = datetime_to_ms(datetime.strptime("2018-02-04T00:00:00", "%Y-%m-%dT%H:%M:%S")) report.generate(start_time=begin, end_time=end, senders=[Engine('vm')]) :param int period_begin: milliseconds time defining start time for report :param int period_end: milliseconds time defining end time for report :param senders: filter targets to use when generating report :type senders: list(Element) :param bool wait_for_finish: enable polling for results :param int timeout: timeout between polling :raises TaskRunFailed: refresh failed, possibly locked policy :rtype: TaskOperationPoller
entailment
def create_design(self, name): """ Create a report design based on an existing template. :param str name: Name of new report design :raises CreateElementFailed: failed to create template :rtype: ReportDesign """ result = self.make_request( CreateElementFailed, resource='create_design', raw_result=True, method='create', params={'name': name}) return ReportDesign( href=result.href, type=self.typeof, name=name)
Create a report design based on an existing template. :param str name: Name of new report design :raises CreateElementFailed: failed to create template :rtype: ReportDesign
entailment
def export_pdf(self, filename): """ Export the report in PDF format. Specify a path for which to save the file, including the trailing filename. :param str filename: path including filename :return: None """ self.make_request( raw_result=True, resource='export', filename=filename, headers = {'accept': 'application/pdf'})
Export the report in PDF format. Specify a path for which to save the file, including the trailing filename. :param str filename: path including filename :return: None
entailment
def export_text(self, filename=None): """ Export in text format. Optionally provide a filename to save to. :param str filename: path including filename (optional) :return: None """ result = self.make_request( resource='export', params={'format': 'txt'}, filename=filename, raw_result=True, headers = {'accept': 'text/plain'}) if not filename: return result.content
Export in text format. Optionally provide a filename to save to. :param str filename: path including filename (optional) :return: None
entailment
def create_ipsec_tunnel(cls, name, local_endpoint, remote_endpoint, preshared_key=None, monitoring_group=None, vpn_profile=None, mtu=0, pmtu_discovery=True, ttl=0, enabled=True, comment=None): """ The VPN tunnel type negotiates IPsec tunnels in the same way as policy-based VPNs, but traffic is selected to be sent into the tunnel based on routing. :param str name: name of VPN :param TunnelEndpoint local_endpoint: the local side endpoint for this VPN. :param TunnelEndpoint remote_endpoint: the remote side endpoint for this VPN. :param str preshared_key: required if remote endpoint is an ExternalGateway :param TunnelMonitoringGroup monitoring_group: the group to place this VPN in for monitoring. Default: 'Uncategorized'. :param VPNProfile vpn_profile: VPN profile for this VPN. (default: VPN-A Suite) :param int mtu: Set MTU for this VPN tunnel (default: 0) :param boolean pmtu_discovery: enable pmtu discovery (default: True) :param int ttl: ttl for connections on the VPN (default: 0) :param bool enabled: enable the RBVPN or leave it disabled :param str comment: optional comment :raises CreateVPNFailed: failed to create the VPN with reason :rtype: RouteVPN """ group = monitoring_group or TunnelMonitoringGroup('Uncategorized') profile = vpn_profile or VPNProfile('VPN-A Suite') json = { 'name': name, 'mtu': mtu, 'ttl': ttl, 'enabled': enabled, 'monitoring_group_ref': group.href, 'pmtu_discovery': pmtu_discovery, 'preshared_key': preshared_key, 'rbvpn_tunnel_side_a': local_endpoint.data, 'rbvpn_tunnel_side_b': remote_endpoint.data, 'tunnel_mode': 'vpn', 'comment': comment, 'vpn_profile_ref': profile.href } try: return ElementCreator(cls, json) except CreateElementFailed as err: raise CreateVPNFailed(err)
The VPN tunnel type negotiates IPsec tunnels in the same way as policy-based VPNs, but traffic is selected to be sent into the tunnel based on routing. :param str name: name of VPN :param TunnelEndpoint local_endpoint: the local side endpoint for this VPN. :param TunnelEndpoint remote_endpoint: the remote side endpoint for this VPN. :param str preshared_key: required if remote endpoint is an ExternalGateway :param TunnelMonitoringGroup monitoring_group: the group to place this VPN in for monitoring. Default: 'Uncategorized'. :param VPNProfile vpn_profile: VPN profile for this VPN. (default: VPN-A Suite) :param int mtu: Set MTU for this VPN tunnel (default: 0) :param boolean pmtu_discovery: enable pmtu discovery (default: True) :param int ttl: ttl for connections on the VPN (default: 0) :param bool enabled: enable the RBVPN or leave it disabled :param str comment: optional comment :raises CreateVPNFailed: failed to create the VPN with reason :rtype: RouteVPN
entailment
def create_gre_tunnel_mode(cls, name, local_endpoint, remote_endpoint, policy_vpn, mtu=0, pmtu_discovery=True, ttl=0, enabled=True, comment=None): """ Create a GRE based tunnel mode route VPN. Tunnel mode GRE wraps the GRE tunnel in an IPSEC tunnel to provide encrypted end-to-end security. Therefore a policy based VPN is required to 'wrap' the GRE into IPSEC. :param str name: name of VPN :param TunnelEndpoint local_endpoint: the local side endpoint for this VPN. :param TunnelEndpoint remote_endpoint: the remote side endpoint for this VPN. :param PolicyVPN policy_vpn: reference to a policy VPN :param TunnelMonitoringGroup monitoring_group: the group to place this VPN in for monitoring. (default: 'Uncategorized') :param int mtu: Set MTU for this VPN tunnel (default: 0) :param boolean pmtu_discovery: enable pmtu discovery (default: True) :param int ttl: ttl for connections on the VPN (default: 0) :param str comment: optional comment :raises CreateVPNFailed: failed to create the VPN with reason :rtype: RouteVPN """ json = { 'name': name, 'ttl': ttl, 'mtu': mtu, 'pmtu_discovery': pmtu_discovery, 'tunnel_encryption': 'tunnel_mode', 'tunnel_mode': 'gre', 'enabled': enabled, 'comment': comment, 'rbvpn_tunnel_side_a': local_endpoint.data, 'rbvpn_tunnel_side_b': remote_endpoint.data } if policy_vpn is None: json['tunnel_encryption'] = 'no_encryption' else: json['tunnel_mode_vpn_ref'] = policy_vpn.href try: return ElementCreator(cls, json) except CreateElementFailed as err: raise CreateVPNFailed(err)
Create a GRE based tunnel mode route VPN. Tunnel mode GRE wraps the GRE tunnel in an IPSEC tunnel to provide encrypted end-to-end security. Therefore a policy based VPN is required to 'wrap' the GRE into IPSEC. :param str name: name of VPN :param TunnelEndpoint local_endpoint: the local side endpoint for this VPN. :param TunnelEndpoint remote_endpoint: the remote side endpoint for this VPN. :param PolicyVPN policy_vpn: reference to a policy VPN :param TunnelMonitoringGroup monitoring_group: the group to place this VPN in for monitoring. (default: 'Uncategorized') :param int mtu: Set MTU for this VPN tunnel (default: 0) :param boolean pmtu_discovery: enable pmtu discovery (default: True) :param int ttl: ttl for connections on the VPN (default: 0) :param str comment: optional comment :raises CreateVPNFailed: failed to create the VPN with reason :rtype: RouteVPN
entailment
def create_gre_tunnel_no_encryption(cls, name, local_endpoint, remote_endpoint, mtu=0, pmtu_discovery=True, ttl=0, enabled=True, comment=None): """ Create a GRE Tunnel with no encryption. See `create_gre_tunnel_mode` for constructor descriptions. """ return cls.create_gre_tunnel_mode( name, local_endpoint, remote_endpoint, policy_vpn=None, mtu=mtu, pmtu_discovery=pmtu_discovery, ttl=ttl, enabled=enabled, comment=comment)
Create a GRE Tunnel with no encryption. See `create_gre_tunnel_mode` for constructor descriptions.
entailment
def set_preshared_key(self, new_key): """ Set the preshared key for this VPN. A pre-shared key is only present when the tunnel type is 'VPN' or the encryption mode is 'transport'. :return: None """ if self.data.get('preshared_key'): self.update(preshared_key=new_key)
Set the preshared key for this VPN. A pre-shared key is only present when the tunnel type is 'VPN' or the encryption mode is 'transport'. :return: None
entailment
def endpoint(self): """ Endpoint is used to specify which interface is enabled for VPN. This is the InternalEndpoint property of the InternalGateway. :return: internal endpoint where VPN is enabled :rtype: InternalEndpoint,ExternalGateway """ if self.endpoint_ref and self.tunnel_interface_ref: return InternalEndpoint(href=self.endpoint_ref) return Element.from_href(self.endpoint_ref)
Endpoint is used to specify which interface is enabled for VPN. This is the InternalEndpoint property of the InternalGateway. :return: internal endpoint where VPN is enabled :rtype: InternalEndpoint,ExternalGateway
entailment
def create_gre_tunnel_endpoint(cls, endpoint=None, tunnel_interface=None, remote_address=None): """ Create the GRE tunnel mode or no encryption mode endpoint. If the GRE tunnel mode endpoint is an SMC managed device, both an endpoint and a tunnel interface is required. If the endpoint is externally managed, only an IP address is required. :param InternalEndpoint,ExternalEndpoint endpoint: the endpoint element for this tunnel endpoint. :param TunnelInterface tunnel_interface: the tunnel interface for this tunnel endpoint. Required for SMC managed devices. :param str remote_address: IP address, only required if the tunnel endpoint is a remote gateway. :rtype: TunnelEndpoint """ tunnel_interface = tunnel_interface.href if tunnel_interface else None endpoint = endpoint.href if endpoint else None return TunnelEndpoint( tunnel_interface_ref=tunnel_interface, endpoint_ref=endpoint, ip_address=remote_address)
Create the GRE tunnel mode or no encryption mode endpoint. If the GRE tunnel mode endpoint is an SMC managed device, both an endpoint and a tunnel interface is required. If the endpoint is externally managed, only an IP address is required. :param InternalEndpoint,ExternalEndpoint endpoint: the endpoint element for this tunnel endpoint. :param TunnelInterface tunnel_interface: the tunnel interface for this tunnel endpoint. Required for SMC managed devices. :param str remote_address: IP address, only required if the tunnel endpoint is a remote gateway. :rtype: TunnelEndpoint
entailment
def create_gre_transport_endpoint(cls, endpoint, tunnel_interface=None): """ Create the GRE transport mode endpoint. If the GRE transport mode endpoint is an SMC managed device, both an endpoint and a tunnel interface is required. If the GRE endpoint is an externally managed device, only an endpoint is required. :param InternalEndpoint,ExternalEndpoint endpoint: the endpoint element for this tunnel endpoint. :param TunnelInterface tunnel_interface: the tunnel interface for this tunnel endpoint. Required for SMC managed devices. :rtype: TunnelEndpoint """ tunnel_interface = tunnel_interface.href if tunnel_interface else None return TunnelEndpoint( endpoint_ref=endpoint.href, tunnel_interface_ref=tunnel_interface)
Create the GRE transport mode endpoint. If the GRE transport mode endpoint is an SMC managed device, both an endpoint and a tunnel interface is required. If the GRE endpoint is an externally managed device, only an endpoint is required. :param InternalEndpoint,ExternalEndpoint endpoint: the endpoint element for this tunnel endpoint. :param TunnelInterface tunnel_interface: the tunnel interface for this tunnel endpoint. Required for SMC managed devices. :rtype: TunnelEndpoint
entailment
def create_ipsec_endpoint(cls, gateway, tunnel_interface=None): """ Create the VPN tunnel endpoint. If the VPN tunnel endpoint is an SMC managed device, both a gateway and a tunnel interface is required. If the VPN endpoint is an externally managed device, only a gateway is required. :param InternalGateway,ExternalGateway gateway: the gateway for this tunnel endpoint :param TunnelInterface tunnel_interface: Tunnel interface for this RBVPN. This can be None if the gateway is a non-SMC managed gateway. :rtype: TunnelEndpoint """ tunnel_interface = tunnel_interface.href if tunnel_interface else None return TunnelEndpoint( gateway_ref=gateway.href, tunnel_interface_ref=tunnel_interface)
Create the VPN tunnel endpoint. If the VPN tunnel endpoint is an SMC managed device, both a gateway and a tunnel interface is required. If the VPN endpoint is an externally managed device, only a gateway is required. :param InternalGateway,ExternalGateway gateway: the gateway for this tunnel endpoint :param TunnelInterface tunnel_interface: Tunnel interface for this RBVPN. This can be None if the gateway is a non-SMC managed gateway. :rtype: TunnelEndpoint
entailment
def set_auth_request(self, interface_id, address=None): """ Set the authentication request field for the specified engine. """ self.interface.set_auth_request(interface_id, address) self._engine.update()
Set the authentication request field for the specified engine.
entailment
def set_primary_heartbeat(self, interface_id): """ Set this interface as the primary heartbeat for this engine. This will 'unset' the current primary heartbeat and move to specified interface_id. Clusters and Master NGFW Engines only. :param str,int interface_id: interface specified for primary mgmt :raises InterfaceNotFound: specified interface is not found :raises UpdateElementFailed: failed modifying interfaces :return: None """ self.interface.set_unset(interface_id, 'primary_heartbeat') self._engine.update()
Set this interface as the primary heartbeat for this engine. This will 'unset' the current primary heartbeat and move to specified interface_id. Clusters and Master NGFW Engines only. :param str,int interface_id: interface specified for primary mgmt :raises InterfaceNotFound: specified interface is not found :raises UpdateElementFailed: failed modifying interfaces :return: None
entailment
def set_backup_heartbeat(self, interface_id): """ Set this interface as the backup heartbeat interface. Clusters and Master NGFW Engines only. :param str,int interface_id: interface as backup :raises InterfaceNotFound: specified interface is not found :raises UpdateElementFailed: failure to update interface :return: None """ self.interface.set_unset(interface_id, 'backup_heartbeat') self._engine.update()
Set this interface as the backup heartbeat interface. Clusters and Master NGFW Engines only. :param str,int interface_id: interface as backup :raises InterfaceNotFound: specified interface is not found :raises UpdateElementFailed: failure to update interface :return: None
entailment
def set_primary_mgt(self, interface_id, auth_request=None, address=None): """ Specifies the Primary Control IP address for Management Server contact. For single FW and cluster FW's, this will enable 'Outgoing', 'Auth Request' and the 'Primary Control' interface. For clusters, the primary heartbeat will NOT follow this change and should be set separately using :meth:`.set_primary_heartbeat`. For virtual FW engines, only auth_request and outgoing will be set. For master engines, only primary control and outgoing will be set. Primary management can be set on an interface with single IP's, multiple IP's or VLANs. :: engine.interface_options.set_primary_mgt(1) Set primary management on a VLAN interface:: engine.interface_options.set_primary_mgt('1.100') Set primary management and different interface for auth_request:: engine.interface_options.set_primary_mgt( interface_id='1.100', auth_request=0) Set on specific IP address of interface VLAN with multiple addresses:: engine.interface_options.set_primary_mgt( interface_id='3.100', address='50.50.50.1') :param str,int interface_id: interface id to make management :param str address: if the interface for management has more than one ip address, this specifies which IP to bind to. :param str,int auth_request: if setting primary mgt on a cluster interface with no CVI, you must pick another interface to set the auth_request field to (default: None) :raises InterfaceNotFound: specified interface is not found :raises UpdateElementFailed: updating management fails :return: None .. note:: Setting primary management on a cluster interface with no CVI requires you to set the interface for auth_request. """ intfattr = ['primary_mgt', 'outgoing'] if self.interface.engine.type in ('virtual_fw',): intfattr.remove('primary_mgt') for attribute in intfattr: self.interface.set_unset(interface_id, attribute, address) if auth_request is not None: self.interface.set_auth_request(auth_request) else: self.interface.set_auth_request(interface_id, address) self._engine.update()
Specifies the Primary Control IP address for Management Server contact. For single FW and cluster FW's, this will enable 'Outgoing', 'Auth Request' and the 'Primary Control' interface. For clusters, the primary heartbeat will NOT follow this change and should be set separately using :meth:`.set_primary_heartbeat`. For virtual FW engines, only auth_request and outgoing will be set. For master engines, only primary control and outgoing will be set. Primary management can be set on an interface with single IP's, multiple IP's or VLANs. :: engine.interface_options.set_primary_mgt(1) Set primary management on a VLAN interface:: engine.interface_options.set_primary_mgt('1.100') Set primary management and different interface for auth_request:: engine.interface_options.set_primary_mgt( interface_id='1.100', auth_request=0) Set on specific IP address of interface VLAN with multiple addresses:: engine.interface_options.set_primary_mgt( interface_id='3.100', address='50.50.50.1') :param str,int interface_id: interface id to make management :param str address: if the interface for management has more than one ip address, this specifies which IP to bind to. :param str,int auth_request: if setting primary mgt on a cluster interface with no CVI, you must pick another interface to set the auth_request field to (default: None) :raises InterfaceNotFound: specified interface is not found :raises UpdateElementFailed: updating management fails :return: None .. note:: Setting primary management on a cluster interface with no CVI requires you to set the interface for auth_request.
entailment
def set_backup_mgt(self, interface_id): """ Set this interface as a backup management interface. Backup management interfaces cannot be placed on an interface with only a CVI (requires node interface/s). To 'unset' the specified interface address, set interface id to None :: engine.interface_options.set_backup_mgt(2) Set backup on interface 1, VLAN 201:: engine.interface_options.set_backup_mgt('1.201') Remove management backup from engine:: engine.interface_options.set_backup_mgt(None) :param str,int interface_id: interface identifier to make the backup management server. :raises InterfaceNotFound: specified interface is not found :raises UpdateElementFailed: failure to make modification :return: None """ self.interface.set_unset(interface_id, 'backup_mgt') self._engine.update()
Set this interface as a backup management interface. Backup management interfaces cannot be placed on an interface with only a CVI (requires node interface/s). To 'unset' the specified interface address, set interface id to None :: engine.interface_options.set_backup_mgt(2) Set backup on interface 1, VLAN 201:: engine.interface_options.set_backup_mgt('1.201') Remove management backup from engine:: engine.interface_options.set_backup_mgt(None) :param str,int interface_id: interface identifier to make the backup management server. :raises InterfaceNotFound: specified interface is not found :raises UpdateElementFailed: failure to make modification :return: None
entailment
def set_outgoing(self, interface_id): """ Specifies the IP address that the engine uses to initiate connections (such as for system communications and ping) through an interface that has no Node Dedicated IP Address. In clusters, you must select an interface that has an IP address defined for all nodes. Setting primary_mgt also sets the default outgoing address to the same interface. :param str,int interface_id: interface to set outgoing :raises InterfaceNotFound: specified interface is not found :raises UpdateElementFailed: failure to make modification :return: None """ self.interface.set_unset(interface_id, 'outgoing') self._engine.update()
Specifies the IP address that the engine uses to initiate connections (such as for system communications and ping) through an interface that has no Node Dedicated IP Address. In clusters, you must select an interface that has an IP address defined for all nodes. Setting primary_mgt also sets the default outgoing address to the same interface. :param str,int interface_id: interface to set outgoing :raises InterfaceNotFound: specified interface is not found :raises UpdateElementFailed: failure to make modification :return: None
entailment
def dscp_marking_and_throttling(self, qos_policy): """ Enable DSCP marking and throttling on the interface. This requires that you provide a QoS policy to which identifies DSCP tags and how to prioritize that traffic. :param QoSPolicy qos_policy: the qos policy to apply to the interface """ self._interface.data.update(qos_limit=-1, qos_mode='dscp', qos_policy_ref=qos_policy.href)
Enable DSCP marking and throttling on the interface. This requires that you provide a QoS policy to which identifies DSCP tags and how to prioritize that traffic. :param QoSPolicy qos_policy: the qos policy to apply to the interface
entailment
def delete(self): """ Override delete in parent class, this will also delete the routing configuration referencing this interface. :: engine = Engine('vm') interface = engine.interface.get(2) interface.delete() """ super(Interface, self).delete() for route in self._engine.routing: if route.to_delete: route.delete() self._engine._del_cache()
Override delete in parent class, this will also delete the routing configuration referencing this interface. :: engine = Engine('vm') interface = engine.interface.get(2) interface.delete()
entailment
def update(self, *args, **kw): """ Update/save this interface information back to SMC. When interface changes are made, especially to sub interfaces, call `update` on the top level interface. Example of changing the IP address of an interface:: >>> engine = Engine('sg_vm') >>> interface = engine.physical_interface.get(1) >>> interface.zone_ref = zone_helper('mynewzone') >>> interface.update() :raises UpdateElementFailed: failure to save changes :return: Interface """ super(Interface, self).update(*args, **kw) self._engine._del_cache() return self
Update/save this interface information back to SMC. When interface changes are made, especially to sub interfaces, call `update` on the top level interface. Example of changing the IP address of an interface:: >>> engine = Engine('sg_vm') >>> interface = engine.physical_interface.get(1) >>> interface.zone_ref = zone_helper('mynewzone') >>> interface.update() :raises UpdateElementFailed: failure to save changes :return: Interface
entailment
def addresses(self): """ Return 3-tuple with (address, network, nicid) :return: address related information of interface as 3-tuple list :rtype: list """ addresses = [] for i in self.all_interfaces: if isinstance(i, VlanInterface): for v in i.interfaces: addresses.append((v.address, v.network_value, v.nicid)) else: addresses.append((i.address, i.network_value, i.nicid)) return addresses
Return 3-tuple with (address, network, nicid) :return: address related information of interface as 3-tuple list :rtype: list
entailment
def sub_interfaces(self): """ Flatten out all top level interfaces and only return sub interfaces. It is recommended to use :meth:`~all_interfaces`, :meth:`~interfaces` or :meth:`~vlan_interfaces` which return collections with helper methods to get sub interfaces based on index or attribute value pairs. :rtype: list(SubInterface) """ interfaces = self.all_interfaces sub_interfaces = [] for interface in interfaces: if isinstance(interface, VlanInterface): if interface.has_interfaces: for subaddr in interface.interfaces: sub_interfaces.append(subaddr) else: sub_interfaces.append(interface) else: sub_interfaces.append(interface) return sub_interfaces
Flatten out all top level interfaces and only return sub interfaces. It is recommended to use :meth:`~all_interfaces`, :meth:`~interfaces` or :meth:`~vlan_interfaces` which return collections with helper methods to get sub interfaces based on index or attribute value pairs. :rtype: list(SubInterface)
entailment
def get_boolean(self, name): """ Get the boolean value for attribute specified from the sub interface/s. """ for interface in self.all_interfaces: if isinstance(interface, VlanInterface): if any(vlan for vlan in interface.interfaces if getattr(vlan, name)): return True else: if getattr(interface, name): return True return False
Get the boolean value for attribute specified from the sub interface/s.
entailment
def delete_invalid_route(self): """ Delete any invalid routes for this interface. An invalid route is a left over when an interface is changed to a different network. :return: None """ try: routing = self._engine.routing.get(self.interface_id) for route in routing: if route.invalid or route.to_delete: route.delete() except InterfaceNotFound: # Only VLAN identifiers, so no routing pass
Delete any invalid routes for this interface. An invalid route is a left over when an interface is changed to a different network. :return: None
entailment
def reset_interface(self): """ Reset the interface by removing all assigned addresses and VLANs. This will not delete the interface itself, only the sub interfaces that may have addresses assigned. This will not affect inline or capture interfaces. Note that if this interface is used as a primary control, auth request or outgoing interface, the update will fail. You should move that functionality to another interface before calling this. See also:: :class:`smc.core.engine.interface_options`. :raises UpdateElementFailed: failed to update the interfaces. This is usually caused when the interface is assigned as a control, outgoing, or auth_request interface. :return: None """ self.data['interfaces'] = [] if self.typeof != 'tunnel_interface': self.data['vlanInterfaces'] = [] self.update() self.delete_invalid_route()
Reset the interface by removing all assigned addresses and VLANs. This will not delete the interface itself, only the sub interfaces that may have addresses assigned. This will not affect inline or capture interfaces. Note that if this interface is used as a primary control, auth request or outgoing interface, the update will fail. You should move that functionality to another interface before calling this. See also:: :class:`smc.core.engine.interface_options`. :raises UpdateElementFailed: failed to update the interfaces. This is usually caused when the interface is assigned as a control, outgoing, or auth_request interface. :return: None
entailment
def change_interface_id(self, interface_id): """ Change the interface ID for this interface. This can be used on any interface type. If the interface is an Inline interface, you must provide the ``interface_id`` in format '1-2' to define both interfaces in the pair. The change is committed after calling this method. :: itf = engine.interface.get(0) itf.change_interface_id(10) Or inline interface pair 10-11:: itf = engine.interface.get(10) itf.change_interface_id('20-21') :param str,int interface_id: new interface ID. Format can be single value for non-inline interfaces or '1-2' format for inline. :raises UpdateElementFailed: changing the interface failed with reason :return: None """ splitted = str(interface_id).split('-') if1 = splitted[0] for interface in self.all_interfaces: # Set top level interface, this only uses a single value which # will be the leftmost interface if isinstance(interface, VlanInterface): interface.interface_id = '{}.{}'.format(if1, interface.interface_id.split('.')[-1]) if interface.has_interfaces: for sub_interface in interface.interfaces: if isinstance(sub_interface, InlineInterface): sub_interface.change_interface_id(interface_id) else: # VLAN interface only (i.e. CVI, NDI, etc) sub_interface.change_interface_id(if1) else: if isinstance(interface, InlineInterface): interface.change_interface_id(interface_id) else: interface.update(nicid=if1) self.interface_id = if1 self.update()
Change the interface ID for this interface. This can be used on any interface type. If the interface is an Inline interface, you must provide the ``interface_id`` in format '1-2' to define both interfaces in the pair. The change is committed after calling this method. :: itf = engine.interface.get(0) itf.change_interface_id(10) Or inline interface pair 10-11:: itf = engine.interface.get(10) itf.change_interface_id('20-21') :param str,int interface_id: new interface ID. Format can be single value for non-inline interfaces or '1-2' format for inline. :raises UpdateElementFailed: changing the interface failed with reason :return: None
entailment
def _update_interface(self, other_interface): """ Update the physical interface base settings with another interface. Only set updated if a value has changed. You must also call `update` on the interface if modifications are made. This is called from other interfaces (i.e. PhysicalInterface, ClusterPhysicalInterface, etc) to update the top layer. :param other_interface PhysicalInterface: an instance of an interface where values in this interface will overwrite values that are different. :raises UpdateElementFailed: Failed to update the element :rtype: bool """ updated = False for name, value in other_interface.data.items(): if isinstance(value, string_types) and getattr(self, name, None) != value: self.data[name] = value updated = True elif value is None and getattr(self, name, None): self.data[name] = None updated = True return updated
Update the physical interface base settings with another interface. Only set updated if a value has changed. You must also call `update` on the interface if modifications are made. This is called from other interfaces (i.e. PhysicalInterface, ClusterPhysicalInterface, etc) to update the top layer. :param other_interface PhysicalInterface: an instance of an interface where values in this interface will overwrite values that are different. :raises UpdateElementFailed: Failed to update the element :rtype: bool
entailment
def update_interface(self, other_interface, ignore_mgmt=True): """ Update an existing interface by comparing values between two interfaces. If a VLAN interface is defined in the other interface and it doesn't exist on the existing interface, it will be created. :param other_interface Interface: an instance of an interface where values in this interface will be used to as the template to determine changes. This only has to provide attributes that need to change (or not). :param bool ignore_mgmt: ignore resetting management fields. These are generally better set after creation using `engine.interface_options` :raises UpdateElementFailed: Failed to update the element :return: (Interface, modified, created) :rtype: tuple .. note:: Interfaces with multiple IP addresses are ignored """ base_updated = self._update_interface(other_interface) mgmt = ('auth_request', 'backup_heartbeat', 'backup_mgt', 'primary_mgt', 'primary_heartbeat', 'outgoing') updated = False invalid_routes = [] def process_interfaces(current, interface): updated = False invalid_routes = [] # Ignore interfaces with multiple addresses if current.has_multiple_addresses: return updated, invalid_routes local_interfaces = current.interfaces # Existing interface for interface in interface.interfaces: # New values local_interface = None if not getattr(interface, 'nodeid', None): # CVI cvi = [itf for itf in local_interfaces if not getattr(itf, 'nodeid', None)] local_interface = cvi[0] if cvi else None else: local_interface = local_interfaces.get(nodeid=interface.nodeid) if local_interface: # CVI or NDI sub interfaces for name, value in interface.data.items(): if getattr(local_interface, name) != value: if ignore_mgmt and name in mgmt: pass else: local_interface[name] = value updated = True if 'network_value' in name: # Only reset routes if network changed invalid_routes.append(interface.nicid) else: current.data.setdefault('interfaces', []).append( {interface.typeof: interface.data}) updated = True return updated, invalid_routes # Handle VLANs is_vlan = other_interface.has_vlan if is_vlan: vlan_interfaces = self.vlan_interface for pvlan in other_interface.vlan_interface: current = vlan_interfaces.get(pvlan.vlan_id) if current: # PhysicalVlanInterface, set any parent interface values if current._update_interface(pvlan): updated = True else: # Create new interface self.data.setdefault('vlanInterfaces', []).append(pvlan.data) updated = True continue # Skip sub interface check _updated, routes = process_interfaces(current, pvlan) if _updated: updated = True invalid_routes.extend(routes) else: _updated, routes = process_interfaces(self, other_interface) if _updated: updated = True invalid_routes.extend(routes) interface = self if updated or base_updated: interface = self.update() if invalid_routes: # Interface updated, check the routes del_invalid_routes(self._engine, invalid_routes) return interface, base_updated or updated
Update an existing interface by comparing values between two interfaces. If a VLAN interface is defined in the other interface and it doesn't exist on the existing interface, it will be created. :param other_interface Interface: an instance of an interface where values in this interface will be used to as the template to determine changes. This only has to provide attributes that need to change (or not). :param bool ignore_mgmt: ignore resetting management fields. These are generally better set after creation using `engine.interface_options` :raises UpdateElementFailed: Failed to update the element :return: (Interface, modified, created) :rtype: tuple .. note:: Interfaces with multiple IP addresses are ignored
entailment
def name(self): """ Read only name tag """ name = super(Interface, self).name return name if name else self.data.get('name')
Read only name tag
entailment
def _add_interface(self, interface_id, **kw): """ Create a tunnel interface. Kw argument list is as follows """ base_interface = ElementCache() base_interface.update( interface_id=str(interface_id), interfaces=[]) if 'zone_ref' in kw: zone_ref = kw.pop('zone_ref') base_interface.update(zone_ref=zone_helper(zone_ref) if zone_ref else None) if 'comment' in kw: base_interface.update(comment=kw.pop('comment')) self.data = base_interface interfaces = kw.pop('interfaces', []) if interfaces: for interface in interfaces: if interface.get('cluster_virtual', None) or \ len(interface.get('nodes', [])) > 1: # Cluster kw.update(interface_id=interface_id, interfaces=interfaces) cvi = ClusterPhysicalInterface(**kw) cvi.data.pop('vlanInterfaces', None) self.data.update(cvi.data) else: # Single interface FW for node in interface.get('nodes', []): node.update(nodeid=1) sni = SingleNodeInterface.create(interface_id, **node) base_interface.setdefault('interfaces', []).append( {sni.typeof: sni.data})
Create a tunnel interface. Kw argument list is as follows
entailment
def ndi_interfaces(self): """ Return a formatted dict list of NDI interfaces on this engine. This will ignore CVI or any inline or layer 2 interface types. This can be used to identify to indicate available IP addresses for a given interface which can be used to run services such as SNMP or DNS Relay. :return: list of dict items [{'address':x, 'nicid':y}] :rtype: list(dict) """ return [{'address': interface.address, 'nicid': interface.nicid} for interface in self.interfaces if isinstance(interface, (NodeInterface, SingleNodeInterface))]
Return a formatted dict list of NDI interfaces on this engine. This will ignore CVI or any inline or layer 2 interface types. This can be used to identify to indicate available IP addresses for a given interface which can be used to run services such as SNMP or DNS Relay. :return: list of dict items [{'address':x, 'nicid':y}] :rtype: list(dict)
entailment
def change_vlan_id(self, original, new): """ Change VLAN ID for a single VLAN, cluster VLAN or inline interface. When changing a single or cluster FW vlan, you can specify the original VLAN and new VLAN as either single int or str value. If modifying an inline interface VLAN when the interface pair has two different VLAN identifiers per interface, use a str value in form: '10-11' (original), and '20-21' (new). Single VLAN id:: >>> engine = Engine('singlefw') >>> itf = engine.interface.get(1) >>> itf.vlan_interfaces() [PhysicalVlanInterface(vlan_id=11), PhysicalVlanInterface(vlan_id=10)] >>> itf.change_vlan_id(11, 100) >>> itf.vlan_interfaces() [PhysicalVlanInterface(vlan_id=100), PhysicalVlanInterface(vlan_id=10)] Inline interface with unique VLAN on each interface pair:: >>> itf = engine.interface.get(2) >>> itf.vlan_interfaces() [PhysicalVlanInterface(vlan_id=2-3)] >>> itf.change_vlan_id('2-3', '20-30') >>> itf.vlan_interfaces() [PhysicalVlanInterface(vlan_id=20-30)] :param str,int original: original VLAN to change. :param str,int new: new VLAN identifier/s. :raises InterfaceNotFound: VLAN not found :raises UpdateElementFailed: failed updating the VLAN id :return: None """ vlan = self.vlan_interface.get_vlan(original) newvlan = str(new).split('-') splitted = vlan.interface_id.split('.') vlan.interface_id = '{}.{}'.format(splitted[0], newvlan[0]) for interface in vlan.interfaces: if isinstance(interface, InlineInterface): interface.change_vlan_id(new) else: interface.change_vlan_id(newvlan[0]) self.update()
Change VLAN ID for a single VLAN, cluster VLAN or inline interface. When changing a single or cluster FW vlan, you can specify the original VLAN and new VLAN as either single int or str value. If modifying an inline interface VLAN when the interface pair has two different VLAN identifiers per interface, use a str value in form: '10-11' (original), and '20-21' (new). Single VLAN id:: >>> engine = Engine('singlefw') >>> itf = engine.interface.get(1) >>> itf.vlan_interfaces() [PhysicalVlanInterface(vlan_id=11), PhysicalVlanInterface(vlan_id=10)] >>> itf.change_vlan_id(11, 100) >>> itf.vlan_interfaces() [PhysicalVlanInterface(vlan_id=100), PhysicalVlanInterface(vlan_id=10)] Inline interface with unique VLAN on each interface pair:: >>> itf = engine.interface.get(2) >>> itf.vlan_interfaces() [PhysicalVlanInterface(vlan_id=2-3)] >>> itf.change_vlan_id('2-3', '20-30') >>> itf.vlan_interfaces() [PhysicalVlanInterface(vlan_id=20-30)] :param str,int original: original VLAN to change. :param str,int new: new VLAN identifier/s. :raises InterfaceNotFound: VLAN not found :raises UpdateElementFailed: failed updating the VLAN id :return: None
entailment
def enable_aggregate_mode(self, mode, interfaces): """ Enable Aggregate (LAGG) mode on this interface. Possible LAGG types are 'ha' and 'lb' (load balancing). For HA, only one secondary interface ID is required. For load balancing mode, up to 7 additional are supported (8 max interfaces). :param str mode: 'lb' or 'ha' :param list interfaces: secondary interfaces for this LAGG :type interfaces: list(str,int) :raises UpdateElementFailed: failed adding aggregate :return: None """ if mode in ['lb', 'ha']: self.data['aggregate_mode'] = mode self.data['second_interface_id'] = ','.join(map(str, interfaces)) self.save()
Enable Aggregate (LAGG) mode on this interface. Possible LAGG types are 'ha' and 'lb' (load balancing). For HA, only one secondary interface ID is required. For load balancing mode, up to 7 additional are supported (8 max interfaces). :param str mode: 'lb' or 'ha' :param list interfaces: secondary interfaces for this LAGG :type interfaces: list(str,int) :raises UpdateElementFailed: failed adding aggregate :return: None
entailment
def static_arp_entry(self, ipaddress, macaddress, arp_type='static', netmask=32): """ Add an arp entry to this physical interface. :: interface = engine.physical_interface.get(0) interface.static_arp_entry( ipaddress='23.23.23.23', arp_type='static', macaddress='02:02:02:02:04:04') interface.save() :param str ipaddress: ip address for entry :param str macaddress: macaddress for ip address :param str arp_type: type of entry, 'static' or 'proxy' (default: static) :param str,int netmask: netmask for entry (default: 32) :return: None """ self.data['arp_entry'].append({ 'ipaddress': ipaddress, 'macaddress': macaddress, 'netmask': netmask, 'type': arp_type})
Add an arp entry to this physical interface. :: interface = engine.physical_interface.get(0) interface.static_arp_entry( ipaddress='23.23.23.23', arp_type='static', macaddress='02:02:02:02:04:04') interface.save() :param str ipaddress: ip address for entry :param str macaddress: macaddress for ip address :param str arp_type: type of entry, 'static' or 'proxy' (default: static) :param str,int netmask: netmask for entry (default: 32) :return: None
entailment
def _add_interface(self, interface_id, mgt=None, **kw): """ Add the Cluster interface. If adding a cluster interface to an existing node, retrieve the existing interface and call this method. Use the supported format for defining an interface. """ _kw = copy.deepcopy(kw) # Preserve original kw, especially lists mgt = mgt if mgt else {} if 'cvi_mode' in _kw: self.data.update(cvi_mode=_kw.pop('cvi_mode')) if 'macaddress' in _kw: self.data.update( macaddress=_kw.pop('macaddress')) if 'cvi_mode' not in self.data: self.data.update(cvi_mode='packetdispatch') if 'zone_ref' in _kw: zone_ref = _kw.pop('zone_ref') self.data.update(zone_ref=zone_helper(zone_ref) if zone_ref else None) if 'comment' in _kw: self.data.update(comment=_kw.pop('comment')) interfaces = _kw.pop('interfaces', []) for interface in interfaces: vlan_id = interface.pop('vlan_id', None) if vlan_id: _interface_id = '{}.{}'.format(interface_id, vlan_id) else: _interface_id = interface_id _interface = [] if_mgt = {k: str(v) == str(_interface_id) for k, v in mgt.items()} if 'cluster_virtual' in interface and 'network_value' in interface: cluster_virtual = interface.pop('cluster_virtual') network_value = interface.pop('network_value') if cluster_virtual and network_value: cvi = ClusterVirtualInterface.create( _interface_id, cluster_virtual, network_value, auth_request=True if if_mgt.get('primary_mgt') else False) _interface.append({cvi.typeof: cvi.data}) for node in interface.pop('nodes', []): _node = if_mgt.copy() _node.update(outgoing=True if if_mgt.get('primary_mgt') else False) # Add node specific key/value pairs set on the node. This can # also be used to override management settings _node.update(node) ndi = NodeInterface.create( interface_id=_interface_id, **_node) _interface.append({ndi.typeof: ndi.data}) if vlan_id: vlan_interface = { 'interface_id': _interface_id, 'zone_ref': zone_helper(interface.pop('zone_ref', None)), 'comment': interface.pop('comment', None), 'interfaces': _interface} # Add remaining kwargs on vlan level to VLAN physical interface for name, value in interface.items(): vlan_interface[name] = value self.data.setdefault('vlanInterfaces', []).append( vlan_interface) else: self.data.setdefault('interfaces', []).extend( _interface) # Remaining kw go to base level interface for name, value in _kw.items(): self.data[name] = value
Add the Cluster interface. If adding a cluster interface to an existing node, retrieve the existing interface and call this method. Use the supported format for defining an interface.
entailment
def delete(self): """ Delete this Vlan interface from the parent interface. This will also remove stale routes if the interface has networks associated with it. :return: None """ if self in self._parent.vlan_interface: self._parent.data['vlanInterfaces'] = [ v for v in self._parent.vlan_interface if v != self] self.update() for route in self._parent._engine.routing: if route.to_delete: route.delete()
Delete this Vlan interface from the parent interface. This will also remove stale routes if the interface has networks associated with it. :return: None
entailment
def change_vlan_id(self, vlan_id): """ Change the VLAN id for this VLAN interface. If this is an inline interface, you can specify two interface values to create unique VLANs on both sides of the inline pair. Or provide a single to use the same VLAN id. :param str vlan_id: string value for new VLAN id. :raises UpdateElementFailed: failed to update the VLAN id :return: None """ intf_id, _ = self.interface_id.split('.') self.interface_id = '{}.{}'.format(intf_id, vlan_id) for interface in self.interfaces: interface.change_vlan_id(vlan_id) self.update()
Change the VLAN id for this VLAN interface. If this is an inline interface, you can specify two interface values to create unique VLANs on both sides of the inline pair. Or provide a single to use the same VLAN id. :param str vlan_id: string value for new VLAN id. :raises UpdateElementFailed: failed to update the VLAN id :return: None
entailment
def get(self, *args, **kwargs): """ Get from the interface collection. It is more accurate to use kwargs to specify an attribute of the sub interface to retrieve rather than using an index value. If retrieving using an index, the collection will first check vlan interfaces and standard interfaces second. In most cases, if VLANs exist, standard interface definitions will be nested below the VLAN with exception of Inline Interfaces which may have both. :param int args: index to retrieve :param kwargs: key value for sub interface :rtype: SubInterface or None """ for collection in self.items: if args: index = args[0] if len(collection) and (index <= len(collection)-1): return collection[index] else: # Collection with get result = collection.get(**kwargs) if result is not None: return result return None
Get from the interface collection. It is more accurate to use kwargs to specify an attribute of the sub interface to retrieve rather than using an index value. If retrieving using an index, the collection will first check vlan interfaces and standard interfaces second. In most cases, if VLANs exist, standard interface definitions will be nested below the VLAN with exception of Inline Interfaces which may have both. :param int args: index to retrieve :param kwargs: key value for sub interface :rtype: SubInterface or None
entailment
def get_vlan(self, *args, **kwargs): """ Get the VLAN from this PhysicalInterface. Use args if you want to specify only the VLAN id. Otherwise you can specify a valid attribute for the VLAN sub interface such as `address` for example:: >>> vlan = itf.vlan_interface.get_vlan(4) >>> vlan Layer3PhysicalInterfaceVlan(name=VLAN 3.4) >>> vlan.addresses [(u'32.32.32.36', u'32.32.32.0/24', u'3.4'), (u'32.32.32.33', u'32.32.32.0/24', u'3.4')] :param int args: args are translated to vlan_id=args[0] :param kwargs: key value for sub interface :raises InterfaceNotFound: VLAN interface could not be found :rtype: VlanInterface """ if args: kwargs = {'vlan_id': str(args[0])} key, value = kwargs.popitem() for vlan in self: if getattr(vlan, key, None) == value: return vlan raise InterfaceNotFound('VLAN ID {} was not found on this engine.' .format(value))
Get the VLAN from this PhysicalInterface. Use args if you want to specify only the VLAN id. Otherwise you can specify a valid attribute for the VLAN sub interface such as `address` for example:: >>> vlan = itf.vlan_interface.get_vlan(4) >>> vlan Layer3PhysicalInterfaceVlan(name=VLAN 3.4) >>> vlan.addresses [(u'32.32.32.36', u'32.32.32.0/24', u'3.4'), (u'32.32.32.33', u'32.32.32.0/24', u'3.4')] :param int args: args are translated to vlan_id=args[0] :param kwargs: key value for sub interface :raises InterfaceNotFound: VLAN interface could not be found :rtype: VlanInterface
entailment
def get(self, *args, **kwargs): """ Get the sub interfaces for this VlanInterface >>> itf = engine.interface.get(3) >>> list(itf.vlan_interface) [Layer3PhysicalInterfaceVlan(name=VLAN 3.3), Layer3PhysicalInterfaceVlan(name=VLAN 3.5), Layer3PhysicalInterfaceVlan(name=VLAN 3.4)] :param int args: args are translated to vlan_id=args[0] :param kwargs: key value for sub interface :rtype: VlanInterface or None """ if args: kwargs = {'vlan_id': str(args[0])} key, value = kwargs.popitem() for item in self: if 'vlan_id' in key and getattr(item, key, None) == value: return item for vlan in item.interfaces: if getattr(vlan, key, None) == value: return item
Get the sub interfaces for this VlanInterface >>> itf = engine.interface.get(3) >>> list(itf.vlan_interface) [Layer3PhysicalInterfaceVlan(name=VLAN 3.3), Layer3PhysicalInterfaceVlan(name=VLAN 3.5), Layer3PhysicalInterfaceVlan(name=VLAN 3.4)] :param int args: args are translated to vlan_id=args[0] :param kwargs: key value for sub interface :rtype: VlanInterface or None
entailment
def find_mgmt_interface(self, mgmt): """ Find the management interface specified and return either the string representation of the interface_id. Valid options: primary_mgt, backup_mgt, primary_heartbeat, backup_heartbeat, outgoing, auth_request :return: str interface_id """ for intf in self: for allitf in intf.all_interfaces: if isinstance(allitf, VlanInterface): for vlan in allitf.interfaces: if getattr(vlan, mgmt, None): return allitf.interface_id else: if getattr(allitf, mgmt, None): return intf.interface_id
Find the management interface specified and return either the string representation of the interface_id. Valid options: primary_mgt, backup_mgt, primary_heartbeat, backup_heartbeat, outgoing, auth_request :return: str interface_id
entailment
def get(self, interface_id): """ Get the interface from engine json :param str interface_id: interface ID to find :raises InterfaceNotFound: Cannot find interface """ # From within engine, skips nested iterators for this find # Make sure were dealing with a string interface_id = str(interface_id) for intf in self: if intf.interface_id == interface_id: intf._engine = self.engine return intf else: # Check for inline interfaces if '.' in interface_id: # It's a VLAN interface vlan = interface_id.split('.') # Check that we're on the right interface if intf.interface_id == vlan[0]: if intf.has_vlan: return intf.vlan_interface.get_vlan(vlan[-1]) elif intf.has_interfaces: for interface in intf.interfaces: if isinstance(interface, InlineInterface): split_intf = interface.nicid.split('-') if interface_id == interface.nicid or \ str(interface_id) in split_intf: intf._engine = self.engine return intf raise InterfaceNotFound( 'Interface id {} was not found on this engine.'.format(interface_id))
Get the interface from engine json :param str interface_id: interface ID to find :raises InterfaceNotFound: Cannot find interface
entailment
def set_unset(self, interface_id, attribute, address=None): """ Set attribute to True and unset the same attribute for all other interfaces. This is used for interface options that can only be set on one engine interface. :raises InterfaceNotFound: raise if specified address does not exist or if the interface is not supported for this management role (i.e. you cannot set primary mgt to a CVI interface with no nodes). """ interface = self.get(interface_id) if interface_id is not None else None if address is not None: target_network = None sub_interface = interface.all_interfaces.get(address=address) if sub_interface: target_network = sub_interface.network_value if not target_network: raise InterfaceNotFound('Address specified: %s was not found on interface ' '%s' % (address, interface_id)) for interface in self: all_subs = interface.sub_interfaces() for sub_interface in all_subs: # Skip VLAN only interfaces (no addresses) if not isinstance(sub_interface, (VlanInterface, InlineInterface)): if getattr(sub_interface, attribute) is not None: if sub_interface.nicid == str(interface_id): if address is not None: if sub_interface.network_value == target_network: sub_interface[attribute] = True else: sub_interface[attribute] = False else: sub_interface[attribute] = True else: #unset sub_interface[attribute] = False
Set attribute to True and unset the same attribute for all other interfaces. This is used for interface options that can only be set on one engine interface. :raises InterfaceNotFound: raise if specified address does not exist or if the interface is not supported for this management role (i.e. you cannot set primary mgt to a CVI interface with no nodes).
entailment
def set_auth_request(self, interface_id, address=None): """ Set auth request, there can only be one per engine so unset all other interfaces. If this is a cluster, auth request can only be set on an interface with a CVI (not valid on NDI only cluster interfaces). If this is a cluster interface, address should be CVI IP. """ for engine_type in ['master', 'layer2', 'ips']: if engine_type in self.engine.type: return interface = self.get(interface_id) if 'cluster' in self.engine.type: # Auth request on a cluster interface must have at least a CVI. # It cannot bind to NDI only interfaces if not any(isinstance(itf, ClusterVirtualInterface) for itf in interface.all_interfaces): raise InterfaceNotFound('The interface specified: %s does not have ' 'a CVI interface defined and therefore cannot be used as an ' 'interface for auth_requests. If setting the primary_mgt interface ' 'provide an interface id for auth_request.' % interface_id) current_interface = self.get( self.engine.interface_options.auth_request) for itf in current_interface.all_interfaces: if getattr(itf, 'auth_request', False): itf['auth_request'] = False # Set sub_if = interface.all_interfaces if any(isinstance(itf, ClusterVirtualInterface) for itf in sub_if): for itf in sub_if: if isinstance(itf, ClusterVirtualInterface): if address: if getattr(itf, 'address', None) == address: itf['auth_request'] = True else: itf['auth_request'] = True else: for itf in sub_if: if getattr(itf, 'auth_request', None) is not None: if address: if getattr(itf, 'address', None) == address: itf['auth_request'] = True else: itf['auth_request'] = True
Set auth request, there can only be one per engine so unset all other interfaces. If this is a cluster, auth request can only be set on an interface with a CVI (not valid on NDI only cluster interfaces). If this is a cluster interface, address should be CVI IP.
entailment
def as_dotted(dotted_str): """ Implement RFC 5396 to support 'asdotted' notation for BGP AS numbers. Provide a string in format of '1.10', '65000.65015' and this will return a 4-byte decimal representation of the AS number. Get the binary values for the int's and pad to 16 bits if necessary (values <255). Concatenate the first 2 bytes with second 2 bytes then convert back to decimal. The maximum for low and high order values is 65535 (i.e. 65535.65535). :param str dotted_str: asdotted notation for BGP ASN :rtype: int """ #max_asn = 4294967295 (65535 * 65535) if '.' not in dotted_str: return dotted_str max_byte = 65535 left, right = map(int, dotted_str.split('.')) if left > max_byte or right > max_byte: raise ValueError('The max low and high order value for ' 'a 32-bit ASN is 65535') binval = "{0:016b}".format(left) binval += "{0:016b}".format(right) return int(binval, 2)
Implement RFC 5396 to support 'asdotted' notation for BGP AS numbers. Provide a string in format of '1.10', '65000.65015' and this will return a 4-byte decimal representation of the AS number. Get the binary values for the int's and pad to 16 bits if necessary (values <255). Concatenate the first 2 bytes with second 2 bytes then convert back to decimal. The maximum for low and high order values is 65535 (i.e. 65535.65535). :param str dotted_str: asdotted notation for BGP ASN :rtype: int
entailment
def update_antispoofing(self, networks=None): """ Pass a list of networks to update antispoofing networks with. You can clear networks by providing an empty list. If networks are provided but already exist, no update is made. :param list networks: networks, groups or hosts for antispoofing :rtype: bool """ if not networks and len(self.data.get('antispoofing_ne_ref')): self.data.update(antispoofing_ne_ref=[]) return True _networks = element_resolver(networks) if set(_networks) ^ set(self.data.get('antispoofing_ne_ref')): self.data.update(antispoofing_ne_ref=_networks) return True return False
Pass a list of networks to update antispoofing networks with. You can clear networks by providing an empty list. If networks are provided but already exist, no update is made. :param list networks: networks, groups or hosts for antispoofing :rtype: bool
entailment
def enable(self, autonomous_system, announced_networks, router_id=None, bgp_profile=None): """ Enable BGP on this engine. On master engine, enable BGP on the virtual firewall. When adding networks to `announced_networks`, the element types can be of type :class:`smc.elements.network.Host`, :class:`smc.elements.network.Network` or :class:`smc.elements.group.Group`. If passing a Group, it must have element types of host or network. Within announced_networks, you can pass a 2-tuple that provides an optional :class:`smc.routing.route_map.RouteMap` if additional policy is required for a given network. :: engine.dynamic_routing.bgp.enable( autonomous_system=AutonomousSystem('aws_as'), announced_networks=[Network('bgpnet'),Network('inside')], router_id='10.10.10.10') :param str,AutonomousSystem autonomous_system: provide the AS element or str href for the element :param str,BGPProfile bgp_profile: provide the BGPProfile element or str href for the element; if None, use system default :param list announced_networks: list of networks to advertise via BGP Announced networks can be single networks,host or group elements or a 2-tuple with the second tuple item being a routemap element :param str router_id: router id for BGP, should be an IP address. If not set, automatic discovery will use default bound interface as ID. :raises ElementNotFound: OSPF, AS or Networks not found :return: None .. note:: For arguments that take str or Element, the str value should be the href of the element. """ autonomous_system = element_resolver(autonomous_system) bgp_profile = element_resolver(bgp_profile) or \ BGPProfile('Default BGP Profile').href announced = self._unwrap(announced_networks) self.data.update( enabled=True, bgp_as_ref=autonomous_system, bgp_profile_ref=bgp_profile, announced_ne_setting=announced, router_id=router_id)
Enable BGP on this engine. On master engine, enable BGP on the virtual firewall. When adding networks to `announced_networks`, the element types can be of type :class:`smc.elements.network.Host`, :class:`smc.elements.network.Network` or :class:`smc.elements.group.Group`. If passing a Group, it must have element types of host or network. Within announced_networks, you can pass a 2-tuple that provides an optional :class:`smc.routing.route_map.RouteMap` if additional policy is required for a given network. :: engine.dynamic_routing.bgp.enable( autonomous_system=AutonomousSystem('aws_as'), announced_networks=[Network('bgpnet'),Network('inside')], router_id='10.10.10.10') :param str,AutonomousSystem autonomous_system: provide the AS element or str href for the element :param str,BGPProfile bgp_profile: provide the BGPProfile element or str href for the element; if None, use system default :param list announced_networks: list of networks to advertise via BGP Announced networks can be single networks,host or group elements or a 2-tuple with the second tuple item being a routemap element :param str router_id: router id for BGP, should be an IP address. If not set, automatic discovery will use default bound interface as ID. :raises ElementNotFound: OSPF, AS or Networks not found :return: None .. note:: For arguments that take str or Element, the str value should be the href of the element.
entailment
def update_configuration(self, **kwargs): """ Update configuration using valid kwargs as defined in the enable constructor. :param dict kwargs: kwargs to satisfy valid args from `enable` :rtype: bool """ updated = False if 'announced_networks' in kwargs: kwargs.update(announced_ne_setting=kwargs.pop('announced_networks')) if 'bgp_profile' in kwargs: kwargs.update(bgp_profile_ref=kwargs.pop('bgp_profile')) if 'autonomous_system' in kwargs: kwargs.update(bgp_as_ref=kwargs.pop('autonomous_system')) announced_ne = kwargs.pop('announced_ne_setting', None) for name, value in kwargs.items(): _value = element_resolver(value) if self.data.get(name) != _value: self.data[name] = _value updated = True if announced_ne is not None: s = self.data.get('announced_ne_setting') ne = self._unwrap(announced_ne) if len(announced_ne) != len(s) or not self._equal(ne, s): self.data.update(announced_ne_setting=ne) updated = True return updated
Update configuration using valid kwargs as defined in the enable constructor. :param dict kwargs: kwargs to satisfy valid args from `enable` :rtype: bool
entailment
def announced_networks(self): """ Show all announced networks for the BGP configuration. Returns tuple of advertised network, routemap. Route map may be None. :: for advertised in engine.bgp.advertisements: net, route_map = advertised :return: list of tuples (advertised_network, route_map). """ return [(Element.from_href(ne.get('announced_ne_ref')), Element.from_href(ne.get('announced_rm_ref'))) for ne in self.data.get('announced_ne_setting')]
Show all announced networks for the BGP configuration. Returns tuple of advertised network, routemap. Route map may be None. :: for advertised in engine.bgp.advertisements: net, route_map = advertised :return: list of tuples (advertised_network, route_map).
entailment
def create(cls, name, as_number, comment=None): """ Create an AS to be applied on the engine BGP configuration. An AS is a required parameter when creating an ExternalBGPPeer. You can also provide an AS number using an 'asdot' syntax:: AutonomousSystem.create(name='myas', as_number='200.600') :param str name: name of this AS :param int as_number: AS number preferred :param str comment: optional string comment :raises CreateElementFailed: unable to create AS :raises ValueError: If providing AS number in dotted format and low/high order bytes are > 65535. :return: instance with meta :rtype: AutonomousSystem """ as_number = as_dotted(str(as_number)) json = {'name': name, 'as_number': as_number, 'comment': comment} return ElementCreator(cls, json)
Create an AS to be applied on the engine BGP configuration. An AS is a required parameter when creating an ExternalBGPPeer. You can also provide an AS number using an 'asdot' syntax:: AutonomousSystem.create(name='myas', as_number='200.600') :param str name: name of this AS :param int as_number: AS number preferred :param str comment: optional string comment :raises CreateElementFailed: unable to create AS :raises ValueError: If providing AS number in dotted format and low/high order bytes are > 65535. :return: instance with meta :rtype: AutonomousSystem
entailment
def create(cls, name, port=179, external_distance=20, internal_distance=200, local_distance=200, subnet_distance=None): """ Create a custom BGP Profile :param str name: name of profile :param int port: port for BGP process :param int external_distance: external administrative distance; (1-255) :param int internal_distance: internal administrative distance (1-255) :param int local_distance: local administrative distance (aggregation) (1-255) :param list subnet_distance: configure specific subnet's with respective distances :type tuple subnet_distance: (subnet element(Network), distance(int)) :raises CreateElementFailed: reason for failure :return: instance with meta :rtype: BGPProfile """ json = {'name': name, 'external': external_distance, 'internal': internal_distance, 'local': local_distance, 'port': port} if subnet_distance: d = [{'distance': distance, 'subnet': subnet.href} for subnet, distance in subnet_distance] json.update(distance_entry=d) return ElementCreator(cls, json)
Create a custom BGP Profile :param str name: name of profile :param int port: port for BGP process :param int external_distance: external administrative distance; (1-255) :param int internal_distance: internal administrative distance (1-255) :param int local_distance: local administrative distance (aggregation) (1-255) :param list subnet_distance: configure specific subnet's with respective distances :type tuple subnet_distance: (subnet element(Network), distance(int)) :raises CreateElementFailed: reason for failure :return: instance with meta :rtype: BGPProfile
entailment
def subnet_distance(self): """ Specific subnet administrative distances :return: list of tuple (subnet, distance) """ return [(Element.from_href(entry.get('subnet')), entry.get('distance')) for entry in self.data.get('distance_entry')]
Specific subnet administrative distances :return: list of tuple (subnet, distance)
entailment
def create(cls, name, neighbor_as, neighbor_ip, neighbor_port=179, comment=None): """ Create an external BGP Peer. :param str name: name of peer :param str,AutonomousSystem neighbor_as_ref: AutonomousSystem element or href. :param str neighbor_ip: ip address of BGP peer :param int neighbor_port: port for BGP, default 179. :raises CreateElementFailed: failed creating :return: instance with meta :rtype: ExternalBGPPeer """ json = {'name': name, 'neighbor_ip': neighbor_ip, 'neighbor_port': neighbor_port, 'comment': comment} neighbor_as_ref = element_resolver(neighbor_as) json.update(neighbor_as=neighbor_as_ref) return ElementCreator(cls, json)
Create an external BGP Peer. :param str name: name of peer :param str,AutonomousSystem neighbor_as_ref: AutonomousSystem element or href. :param str neighbor_ip: ip address of BGP peer :param int neighbor_port: port for BGP, default 179. :raises CreateElementFailed: failed creating :return: instance with meta :rtype: ExternalBGPPeer
entailment
def create(cls, name, connection_profile_ref=None, md5_password=None, local_as_option='not_set', max_prefix_option='not_enabled', send_community='no', connected_check='disabled', orf_option='disabled', next_hop_self=True, override_capability=False, dont_capability_negotiate=False, remote_private_as=False, route_reflector_client=False, soft_reconfiguration=True, ttl_option='disabled', comment=None): """ Create a new BGPPeering configuration. :param str name: name of peering :param str,BGPConnectionProfile connection_profile_ref: required BGP connection profile. System default used if not provided. :param str md5_password: optional md5_password :param str local_as_option: the local AS mode. Valid options are: 'not_set', 'prepend', 'no_prepend', 'replace_as' :param str max_prefix_option: The max prefix mode. Valid options are: 'not_enabled', 'enabled', 'warning_only' :param str send_community: the send community mode. Valid options are: 'no', 'standard', 'extended', 'standard_and_extended' :param str connected_check: the connected check mode. Valid options are: 'disabled', 'enabled', 'automatic' :param str orf_option: outbound route filtering mode. Valid options are: 'disabled', 'send', 'receive', 'both' :param bool next_hop_self: next hop self setting :param bool override_capability: is override received capabilities :param bool dont_capability_negotiate: do not send capabilities :param bool remote_private_as: is remote a private AS :param bool route_reflector_client: Route Reflector Client (iBGP only) :param bool soft_reconfiguration: do soft reconfiguration inbound :param str ttl_option: ttl check mode. Valid options are: 'disabled', 'ttl-security' :raises CreateElementFailed: failed creating profile :return: instance with meta :rtype: BGPPeering """ json = {'name': name, 'local_as_option': local_as_option, 'max_prefix_option': max_prefix_option, 'send_community': send_community, 'connected_check': connected_check, 'orf_option': orf_option, 'next_hop_self': next_hop_self, 'override_capability': override_capability, 'dont_capability_negotiate': dont_capability_negotiate, 'soft_reconfiguration': soft_reconfiguration, 'remove_private_as': remote_private_as, 'route_reflector_client': route_reflector_client, 'ttl_option': ttl_option, 'comment': comment} if md5_password: json.update(md5_password=md5_password) connection_profile_ref = element_resolver(connection_profile_ref) or \ BGPConnectionProfile('Default BGP Connection Profile').href json.update(connection_profile=connection_profile_ref) return ElementCreator(cls, json)
Create a new BGPPeering configuration. :param str name: name of peering :param str,BGPConnectionProfile connection_profile_ref: required BGP connection profile. System default used if not provided. :param str md5_password: optional md5_password :param str local_as_option: the local AS mode. Valid options are: 'not_set', 'prepend', 'no_prepend', 'replace_as' :param str max_prefix_option: The max prefix mode. Valid options are: 'not_enabled', 'enabled', 'warning_only' :param str send_community: the send community mode. Valid options are: 'no', 'standard', 'extended', 'standard_and_extended' :param str connected_check: the connected check mode. Valid options are: 'disabled', 'enabled', 'automatic' :param str orf_option: outbound route filtering mode. Valid options are: 'disabled', 'send', 'receive', 'both' :param bool next_hop_self: next hop self setting :param bool override_capability: is override received capabilities :param bool dont_capability_negotiate: do not send capabilities :param bool remote_private_as: is remote a private AS :param bool route_reflector_client: Route Reflector Client (iBGP only) :param bool soft_reconfiguration: do soft reconfiguration inbound :param str ttl_option: ttl check mode. Valid options are: 'disabled', 'ttl-security' :raises CreateElementFailed: failed creating profile :return: instance with meta :rtype: BGPPeering
entailment
def create(cls, name, md5_password=None, connect_retry=120, session_hold_timer=180, session_keep_alive=60): """ Create a new BGP Connection Profile. :param str name: name of profile :param str md5_password: optional md5 password :param int connect_retry: The connect retry timer, in seconds :param int session_hold_timer: The session hold timer, in seconds :param int session_keep_alive: The session keep alive timer, in seconds :raises CreateElementFailed: failed creating profile :return: instance with meta :rtype: BGPConnectionProfile """ json = {'name': name, 'connect': connect_retry, 'session_hold_timer': session_hold_timer, 'session_keep_alive': session_keep_alive} if md5_password: json.update(md5_password=md5_password) return ElementCreator(cls, json)
Create a new BGP Connection Profile. :param str name: name of profile :param str md5_password: optional md5 password :param int connect_retry: The connect retry timer, in seconds :param int session_hold_timer: The session hold timer, in seconds :param int session_keep_alive: The session keep alive timer, in seconds :raises CreateElementFailed: failed creating profile :return: instance with meta :rtype: BGPConnectionProfile
entailment
def enable(self, values): """ Enable specific permissions on this role. Use :py:attr:`~permissions` to view valid permission settings and current value/s. Change is committed immediately. :param list values: list of values by allowed types :return: None """ for value in values: if value in self.data: self.data[value] = True
Enable specific permissions on this role. Use :py:attr:`~permissions` to view valid permission settings and current value/s. Change is committed immediately. :param list values: list of values by allowed types :return: None
entailment
def disable(self, values): """ Disable specific permissions on this role. Use :py:attr:`~permissions` to view valid permission settings and current value/s. Change is committed immediately. :param list values: list of values by allowed types :return: None """ for value in values: if value in self.data: self.data[value] = False
Disable specific permissions on this role. Use :py:attr:`~permissions` to view valid permission settings and current value/s. Change is committed immediately. :param list values: list of values by allowed types :return: None
entailment
def permissions(self): """ Return valid permissions and setting for this role. Permissions are returned as a list of dict items, {permission: state}. State for the permission is either True or False. Use :meth:`~enable` and :meth:`~disable` to toggle role settings. :return: list of permission settings :rtype: list(dict) """ permissions = [] for permission, value in self.data.items(): if permission not in self._reserved: permissions.append({permission: value}) return permissions
Return valid permissions and setting for this role. Permissions are returned as a list of dict items, {permission: state}. State for the permission is either True or False. Use :meth:`~enable` and :meth:`~disable` to toggle role settings. :return: list of permission settings :rtype: list(dict)
entailment
def _extract_ports(port_string): """ Return a dict for translated_value based on a string or int value. Value could be 80, or '80' or '80-90'. Will be returned as {'min_port': 80, 'max_port': 80} or {'min_port': 80, 'max_port': 90} :rtype: dict """ _ports = str(port_string) if '-' in _ports: start, end = _ports.split('-') return {'min_port': start, 'max_port': end} return {'min_port': _ports, 'max_port': _ports}
Return a dict for translated_value based on a string or int value. Value could be 80, or '80' or '80-90'. Will be returned as {'min_port': 80, 'max_port': 80} or {'min_port': 80, 'max_port': 90} :rtype: dict
entailment
def _update_nat_field(self, source_or_dest): """ If the source or destination field of a rule is changed and the rule is a NAT rule, this method will check to see if the changed field maps to a NAT type and modifies the `original_value` field within the NAT dict to reflect the new element reference. It is possible that a NAT rule doesn't actually define a NAT type, i.e. meaning do not NAT. :param Source,Destination source_or_dest: source or destination element changed. This would be called from update_field on the Source or Destination object. """ original_value = source_or_dest.all_as_href() if original_value: nat_element = None if 'src' in source_or_dest.typeof and self.static_src_nat.has_nat: nat_element = self.static_src_nat elif 'dst' in source_or_dest.typeof and self.static_dst_nat.has_nat: nat_element = self.static_dst_nat if nat_element: nat_element.setdefault(nat_element.typeof, {}).update( original_value={'element': original_value[0]})
If the source or destination field of a rule is changed and the rule is a NAT rule, this method will check to see if the changed field maps to a NAT type and modifies the `original_value` field within the NAT dict to reflect the new element reference. It is possible that a NAT rule doesn't actually define a NAT type, i.e. meaning do not NAT. :param Source,Destination source_or_dest: source or destination element changed. This would be called from update_field on the Source or Destination object.
entailment
def _update_field(self, natvalue): """ Update this NATValue if values are different :rtype: bool """ updated = False if natvalue.element and natvalue.element != self.element: self.update(element=natvalue.element) self.pop('ip_descriptor', None) updated = True elif natvalue.ip_descriptor and self.ip_descriptor and \ natvalue.ip_descriptor != self.ip_descriptor: self.update(ip_descriptor=natvalue.ip_descriptor) self.pop('element', None) updated = True for port in ('min_port', 'max_port'): _port = getattr(natvalue, port, None) if _port is not None and getattr(self, port, None) != _port: self[port] = _port updated = True return updated
Update this NATValue if values are different :rtype: bool
entailment
def update_field(self, element_or_ip_address=None, start_port=None, end_port=None, **kw): """ Update the source NAT translation on this rule. You must call `save` or `update` on the rule to make this modification. To update the source target for this NAT rule, update the source field directly using rule.sources.update_field(...). This will automatically update the NAT value. This method should be used when you want to change the translated value or the port mappings for dynamic source NAT. Starting and ending ports are only used for dynamic source NAT and define the available ports for doing PAT on the outbound connection. :param str,Element element_or_ip_address: Element or IP address that is the NAT target :param int start_port: starting port value, only used for dynamic source NAT :param int end_port: ending port value, only used for dynamic source NAT :param bool automatic_proxy: whether to enable proxy ARP (default: True) :return: boolean indicating whether the rule was modified :rtype: bool """ updated = False src = _resolve_nat_element(element_or_ip_address) if \ element_or_ip_address else {} automatic_proxy = kw.pop('automatic_proxy', None) # Original value is only used when creating a rule for static src NAT. # This should be the href of the source field to properly create # TODO: The SMC API should autofill this based on source field _original_value = kw.pop('original_value', None) src.update(kw) if not self.translated_value: # Adding to a rule if 'dynamic_src_nat' in self.typeof: src.update( min_port=start_port or 1024, max_port=end_port or 65535) self.setdefault(self.typeof, {}).update( automatic_proxy=automatic_proxy if automatic_proxy else True, **self._translated_value(src)) if 'static_src_nat' in self.typeof: if self.rule and self.rule.sources.all_as_href(): original_value={'element': self.rule.sources.all_as_href()[0]} else: original_value={'element': _original_value} self.setdefault(self.typeof, {}).update(original_value=original_value) updated = True else: if 'dynamic_src_nat' in self.typeof: src.update(min_port=start_port, max_port=end_port) if self.translated_value._update_field(NATValue(src)): updated = True if automatic_proxy is not None and self.automatic_proxy \ != automatic_proxy: self.automatic_proxy = automatic_proxy updated = True return updated
Update the source NAT translation on this rule. You must call `save` or `update` on the rule to make this modification. To update the source target for this NAT rule, update the source field directly using rule.sources.update_field(...). This will automatically update the NAT value. This method should be used when you want to change the translated value or the port mappings for dynamic source NAT. Starting and ending ports are only used for dynamic source NAT and define the available ports for doing PAT on the outbound connection. :param str,Element element_or_ip_address: Element or IP address that is the NAT target :param int start_port: starting port value, only used for dynamic source NAT :param int end_port: ending port value, only used for dynamic source NAT :param bool automatic_proxy: whether to enable proxy ARP (default: True) :return: boolean indicating whether the rule was modified :rtype: bool
entailment
def translated_value(self): """ The translated value for this NAT type. If this rule does not have a NAT value defined, this will return None. :return: NATValue or None :rtype: NATValue """ if self.typeof in self: return NATValue(self.get(self.typeof, {}).get( 'translated_value'))
The translated value for this NAT type. If this rule does not have a NAT value defined, this will return None. :return: NATValue or None :rtype: NATValue
entailment
def update_field(self, element_or_ip_address=None, original_port=None, translated_port=None, **kw): """ Update the destination NAT translation on this rule. You must call `save` or `update` on the rule to make this modification. The destination field in the NAT rule determines which destination is the target of the NAT. To change the target, call the rule.destinations.update_field(...) method. This will automatically update the NAT value. This method should be used when you want to change the translated value port mappings for the service. Translated Port values can be used to provide port redirection for the service specified in the NAT rule. These should be provided as a string format either in single port format, or as a port range. For example, providing redirection from port 80 to port 8080:: original_port='80' translated_port='8080' You can also use a range format although port range sizes much then match in size. The format for range of ports is: '80-100', '6000-6020' - port 80 translates to 6000, etc. For example, doing port range redirection using a range of ports:: original_port='80-90' translated_port='200-210' .. note:: When using a range of ports for static destination translation, you must use a port range of equal length or the update will be ignored. :param str,Element element_or_ip_address: Element or IP address that is the NAT target :param str,int original_port: The original port is based on the service port :param str,int translated_port: The port to translate the original port to :param bool automatic_proxy: whether to enable proxy ARP (default: True) :return: boolean indicating whether the rule was modified :rtype: bool """ updated = False src = _resolve_nat_element(element_or_ip_address) if \ element_or_ip_address else {} automatic_proxy = kw.pop('automatic_proxy', None) # Original value is only used when creating a rule for static src NAT. # This should be the href of the source field to properly create # TODO: The SMC API should autofill this based on source field _original_value = kw.pop('original_value', None) src.update(kw) if translated_port is not None: src.update(_extract_ports(translated_port)) if not self.translated_value: # Adding to a rule self.setdefault(self.typeof, {}).update( automatic_proxy=automatic_proxy if automatic_proxy else True, **self._translated_value(src)) if self.rule and self.rule.destinations.all_as_href(): original_value={'element': self.rule.destinations.all_as_href()[0]} else: # If creating, original_value should be href of resource original_value={'element': _original_value} if original_port is not None: original_value.update(_extract_ports(original_port)) self.setdefault(self.typeof, {}).update( original_value=original_value) updated = True else: if self.translated_value._update_field(NATValue(src)): updated = True if original_port: if self.original_value._update_field(NATValue( _extract_ports(original_port))): updated = True if automatic_proxy is not None and self.automatic_proxy \ != automatic_proxy: self.automatic_proxy = automatic_proxy updated = True return updated
Update the destination NAT translation on this rule. You must call `save` or `update` on the rule to make this modification. The destination field in the NAT rule determines which destination is the target of the NAT. To change the target, call the rule.destinations.update_field(...) method. This will automatically update the NAT value. This method should be used when you want to change the translated value port mappings for the service. Translated Port values can be used to provide port redirection for the service specified in the NAT rule. These should be provided as a string format either in single port format, or as a port range. For example, providing redirection from port 80 to port 8080:: original_port='80' translated_port='8080' You can also use a range format although port range sizes much then match in size. The format for range of ports is: '80-100', '6000-6020' - port 80 translates to 6000, etc. For example, doing port range redirection using a range of ports:: original_port='80-90' translated_port='200-210' .. note:: When using a range of ports for static destination translation, you must use a port range of equal length or the update will be ignored. :param str,Element element_or_ip_address: Element or IP address that is the NAT target :param str,int original_port: The original port is based on the service port :param str,int translated_port: The port to translate the original port to :param bool automatic_proxy: whether to enable proxy ARP (default: True) :return: boolean indicating whether the rule was modified :rtype: bool
entailment
def create(self, name, sources=None, destinations=None, services=None, dynamic_src_nat=None, dynamic_src_nat_ports=(1024, 65535), static_src_nat=None, static_dst_nat=None, static_dst_nat_ports=None, is_disabled=False, used_on=None, add_pos=None, after=None, before=None, comment=None): """ Create a NAT rule. When providing sources/destinations or services, you can provide the element href, network element or services from ``smc.elements``. You can also mix href strings with Element types in these fields. :param str name: name of NAT rule :param list sources: list of sources by href or Element :type sources: list(str,Element) :param list destinations: list of destinations by href or Element :type destinations: list(str,Element) :param list services: list of services by href or Element :type services: list(str,Element) :param dynamic_src_nat: str ip or Element for dest NAT :type dynamic_src_nat: str,Element :param tuple dynamic_src_nat_ports: starting and ending ports for PAT. Default: (1024, 65535) :param str static_src_nat: ip or element href of used for source NAT :param str static_dst_nat: destination NAT IP address or element href :param tuple static_dst_nat_ports: ports or port range used for original and destination ports (only needed if a different destination port is used and does not match the rules service port) :param bool is_disabled: whether to disable rule or not :param str,href used_on: Can be a str href of an Element or Element of type AddressRange('ANY'), AddressRange('NONE') or an engine element. :type used_on: str,Element :param int add_pos: position to insert the rule, starting with position 1. If the position value is greater than the number of rules, the rule is inserted at the bottom. If add_pos is not provided, rule is inserted in position 1. Mutually exclusive with ``after`` and ``before`` params. :param str after: Rule tag to add this rule after. Mutually exclusive with ``add_pos`` and ``before`` params. :param str before: Rule tag to add this rule before. Mutually exclusive with ``add_pos`` and ``after`` params. :param str comment: optional comment for the NAT rule :raises InvalidRuleValue: if rule requirements are not met :raises CreateRuleFailed: rule creation failure :return: newly created NAT rule :rtype: IPv4NATRule """ rule_values = self.update_targets(sources, destinations, services) rule_values.update(name=name, comment=comment) rule_values.update(is_disabled=is_disabled) rule_values.update(used_on=element_resolver(used_on) if used_on else used_on) #rule_values.update(used_on=element_resolver(AddressRange('ANY') if not \ # used_on else element_resolver(used_on))) if dynamic_src_nat: nat = DynamicSourceNAT() start_port, end_port = dynamic_src_nat_ports nat.update_field(dynamic_src_nat, start_port=start_port, end_port=end_port) rule_values.update(options=nat) elif static_src_nat: sources = rule_values['sources'] if 'any' in sources or 'none' in sources: raise InvalidRuleValue('Source field cannot be none or any for ' 'static source NAT.') nat = StaticSourceNAT() nat.update_field(static_src_nat, original_value=sources.get('src')[0]) rule_values.update(options=nat) if static_dst_nat: destinations = rule_values['destinations'] if 'any' in destinations or 'none' in destinations: raise InvalidRuleValue('Destination field cannot be none or any for ' 'destination NAT.') nat = StaticDestNAT() original_port, translated_port = None, None if static_dst_nat_ports: original_port, translated_port = static_dst_nat_ports nat.update_field(static_dst_nat, original_value=destinations.get('dst')[0], original_port=original_port, translated_port=translated_port) rule_values.setdefault('options', {}).update(nat) if 'options' not in rule_values: # No NAT rule_values.update(options=LogOptions()) params = None href = self.href if add_pos is not None: href = self.add_at_position(add_pos) elif before or after: params = self.add_before_after(before, after) return ElementCreator( self.__class__, exception=CreateRuleFailed, href=href, params=params, json=rule_values)
Create a NAT rule. When providing sources/destinations or services, you can provide the element href, network element or services from ``smc.elements``. You can also mix href strings with Element types in these fields. :param str name: name of NAT rule :param list sources: list of sources by href or Element :type sources: list(str,Element) :param list destinations: list of destinations by href or Element :type destinations: list(str,Element) :param list services: list of services by href or Element :type services: list(str,Element) :param dynamic_src_nat: str ip or Element for dest NAT :type dynamic_src_nat: str,Element :param tuple dynamic_src_nat_ports: starting and ending ports for PAT. Default: (1024, 65535) :param str static_src_nat: ip or element href of used for source NAT :param str static_dst_nat: destination NAT IP address or element href :param tuple static_dst_nat_ports: ports or port range used for original and destination ports (only needed if a different destination port is used and does not match the rules service port) :param bool is_disabled: whether to disable rule or not :param str,href used_on: Can be a str href of an Element or Element of type AddressRange('ANY'), AddressRange('NONE') or an engine element. :type used_on: str,Element :param int add_pos: position to insert the rule, starting with position 1. If the position value is greater than the number of rules, the rule is inserted at the bottom. If add_pos is not provided, rule is inserted in position 1. Mutually exclusive with ``after`` and ``before`` params. :param str after: Rule tag to add this rule after. Mutually exclusive with ``add_pos`` and ``before`` params. :param str before: Rule tag to add this rule before. Mutually exclusive with ``add_pos`` and ``after`` params. :param str comment: optional comment for the NAT rule :raises InvalidRuleValue: if rule requirements are not met :raises CreateRuleFailed: rule creation failure :return: newly created NAT rule :rtype: IPv4NATRule
entailment
def request(self, uri, method='GET', body=None, headers=None, **kwargs): """Implementation of httplib2's Http.request.""" _credential_refresh_attempt = kwargs.pop( '_credential_refresh_attempt', 0) # Make a copy of the headers. They will be modified by the credentials # and we want to pass the original headers if we recurse. request_headers = headers.copy() if headers is not None else {} self.credentials.before_request( self._request, method, uri, request_headers) # Check if the body is a file-like stream, and if so, save the body # stream position so that it can be restored in case of refresh. body_stream_position = None if all(getattr(body, stream_prop, None) for stream_prop in _STREAM_PROPERTIES): body_stream_position = body.tell() # Make the request. response, content = self.http.request( uri, method, body=body, headers=request_headers, **kwargs) # If the response indicated that the credentials needed to be # refreshed, then refresh the credentials and re-attempt the # request. # A stored token may expire between the time it is retrieved and # the time the request is made, so we may need to try twice. if (response.status in self._refresh_status_codes and _credential_refresh_attempt < self._max_refresh_attempts): _LOGGER.info( 'Refreshing credentials due to a %s response. Attempt %s/%s.', response.status, _credential_refresh_attempt + 1, self._max_refresh_attempts) self.credentials.refresh(self._request) # Restore the body's stream position if needed. if body_stream_position is not None: body.seek(body_stream_position) # Recurse. Pass in the original headers, not our modified set. return self.request( uri, method, body=body, headers=headers, _credential_refresh_attempt=_credential_refresh_attempt + 1, **kwargs) return response, content
Implementation of httplib2's Http.request.
entailment
def connect(self, broker, port=1883, client_id="", clean_session=True): """ Connect to an MQTT broker. This is a pre-requisite step for publish and subscribe keywords. `broker` MQTT broker host `port` broker port (default 1883) `client_id` if not specified, a random id is generated `clean_session` specifies the clean session flag for the connection Examples: Connect to a broker with default port and client id | Connect | 127.0.0.1 | Connect to a broker by specifying the port and client id explicitly | Connect | 127.0.0.1 | 1883 | test.client | Connect to a broker with clean session flag set to false | Connect | 127.0.0.1 | clean_session=${false} | """ logger.info('Connecting to %s at port %s' % (broker, port)) self._connected = False self._unexpected_disconnect = False self._mqttc = mqtt.Client(client_id, clean_session) # set callbacks self._mqttc.on_connect = self._on_connect self._mqttc.on_disconnect = self._on_disconnect if self._username: self._mqttc.username_pw_set(self._username, self._password) self._mqttc.connect(broker, int(port)) timer_start = time.time() while time.time() < timer_start + self._loop_timeout: if self._connected or self._unexpected_disconnect: break; self._mqttc.loop() if self._unexpected_disconnect: raise RuntimeError("The client disconnected unexpectedly") logger.debug('client_id: %s' % self._mqttc._client_id) return self._mqttc
Connect to an MQTT broker. This is a pre-requisite step for publish and subscribe keywords. `broker` MQTT broker host `port` broker port (default 1883) `client_id` if not specified, a random id is generated `clean_session` specifies the clean session flag for the connection Examples: Connect to a broker with default port and client id | Connect | 127.0.0.1 | Connect to a broker by specifying the port and client id explicitly | Connect | 127.0.0.1 | 1883 | test.client | Connect to a broker with clean session flag set to false | Connect | 127.0.0.1 | clean_session=${false} |
entailment
def publish(self, topic, message=None, qos=0, retain=False): """ Publish a message to a topic with specified qos and retained flag. It is required that a connection has been established using `Connect` keyword before using this keyword. `topic` topic to which the message will be published `message` message payload to publish `qos` qos of the message `retain` retained flag Examples: | Publish | test/test | test message | 1 | ${false} | """ logger.info('Publish topic: %s, message: %s, qos: %s, retain: %s' % (topic, message, qos, retain)) self._mid = -1 self._mqttc.on_publish = self._on_publish result, mid = self._mqttc.publish(topic, message, int(qos), retain) if result != 0: raise RuntimeError('Error publishing: %s' % result) timer_start = time.time() while time.time() < timer_start + self._loop_timeout: if mid == self._mid: break; self._mqttc.loop() if mid != self._mid: logger.warn('mid wasn\'t matched: %s' % mid)
Publish a message to a topic with specified qos and retained flag. It is required that a connection has been established using `Connect` keyword before using this keyword. `topic` topic to which the message will be published `message` message payload to publish `qos` qos of the message `retain` retained flag Examples: | Publish | test/test | test message | 1 | ${false} |
entailment
def subscribe(self, topic, qos, timeout=1, limit=1): """ Subscribe to a topic and return a list of message payloads received within the specified time. `topic` topic to subscribe to `qos` quality of service for the subscription `timeout` duration of subscription. Specify 0 to enable background looping (async) `limit` the max number of payloads that will be returned. Specify 0 for no limit Examples: Subscribe and get a list of all messages received within 5 seconds | ${messages}= | Subscribe | test/test | qos=1 | timeout=5 | limit=0 | Subscribe and get 1st message received within 60 seconds | @{messages}= | Subscribe | test/test | qos=1 | timeout=60 | limit=1 | | Length should be | ${messages} | 1 | """ seconds = convert_time(timeout) self._messages[topic] = [] limit = int(limit) self._subscribed = False logger.info('Subscribing to topic: %s' % topic) self._mqttc.on_subscribe = self._on_subscribe self._mqttc.subscribe(str(topic), int(qos)) self._mqttc.on_message = self._on_message_list if seconds == 0: logger.info('Starting background loop') self._background_mqttc = self._mqttc self._background_mqttc.loop_start() return self._messages[topic] timer_start = time.time() while time.time() < timer_start + seconds: if limit == 0 or len(self._messages[topic]) < limit: self._mqttc.loop() else: # workaround for client to ack the publish. Otherwise, # it seems that if client disconnects quickly, broker # will not get the ack and publish the message again on # next connect. time.sleep(1) break return self._messages[topic]
Subscribe to a topic and return a list of message payloads received within the specified time. `topic` topic to subscribe to `qos` quality of service for the subscription `timeout` duration of subscription. Specify 0 to enable background looping (async) `limit` the max number of payloads that will be returned. Specify 0 for no limit Examples: Subscribe and get a list of all messages received within 5 seconds | ${messages}= | Subscribe | test/test | qos=1 | timeout=5 | limit=0 | Subscribe and get 1st message received within 60 seconds | @{messages}= | Subscribe | test/test | qos=1 | timeout=60 | limit=1 | | Length should be | ${messages} | 1 |
entailment
def listen(self, topic, timeout=1, limit=1): """ Listen to a topic and return a list of message payloads received within the specified time. Requires an async Subscribe to have been called previously. `topic` topic to listen to `timeout` duration to listen `limit` the max number of payloads that will be returned. Specify 0 for no limit Examples: Listen and get a list of all messages received within 5 seconds | ${messages}= | Listen | test/test | timeout=5 | limit=0 | Listen and get 1st message received within 60 seconds | @{messages}= | Listen | test/test | timeout=60 | limit=1 | | Length should be | ${messages} | 1 | """ if not self._subscribed: logger.warn('Cannot listen when not subscribed to a topic') return [] if topic not in self._messages: logger.warn('Cannot listen when not subscribed to topic: %s' % topic) return [] # If enough messages have already been gathered, return them if limit != 0 and len(self._messages[topic]) >= limit: messages = self._messages[topic][:] # Copy the list's contents self._messages[topic] = [] return messages[-limit:] seconds = convert_time(timeout) limit = int(limit) logger.info('Listening on topic: %s' % topic) timer_start = time.time() while time.time() < timer_start + seconds: if limit == 0 or len(self._messages[topic]) < limit: # If the loop is running in the background # merely sleep here for a second or so and continue # otherwise, do the loop ourselves if self._background_mqttc: time.sleep(1) else: self._mqttc.loop() else: # workaround for client to ack the publish. Otherwise, # it seems that if client disconnects quickly, broker # will not get the ack and publish the message again on # next connect. time.sleep(1) break messages = self._messages[topic][:] # Copy the list's contents self._messages[topic] = [] return messages[-limit:] if limit != 0 else messages
Listen to a topic and return a list of message payloads received within the specified time. Requires an async Subscribe to have been called previously. `topic` topic to listen to `timeout` duration to listen `limit` the max number of payloads that will be returned. Specify 0 for no limit Examples: Listen and get a list of all messages received within 5 seconds | ${messages}= | Listen | test/test | timeout=5 | limit=0 | Listen and get 1st message received within 60 seconds | @{messages}= | Listen | test/test | timeout=60 | limit=1 | | Length should be | ${messages} | 1 |
entailment
def subscribe_and_validate(self, topic, qos, payload, timeout=1): """ Subscribe to a topic and validate that the specified payload is received within timeout. It is required that a connection has been established using `Connect` keyword. The payload can be specified as a python regular expression. If the specified payload is not received within timeout, an AssertionError is thrown. `topic` topic to subscribe to `qos` quality of service for the subscription `payload` payload (message) that is expected to arrive `timeout` time to wait for the payload to arrive Examples: | Subscribe And Validate | test/test | 1 | test message | """ seconds = convert_time(timeout) self._verified = False logger.info('Subscribing to topic: %s' % topic) self._mqttc.subscribe(str(topic), int(qos)) self._payload = str(payload) self._mqttc.on_message = self._on_message timer_start = time.time() while time.time() < timer_start + seconds: if self._verified: break self._mqttc.loop() if not self._verified: raise AssertionError("The expected payload didn't arrive in the topic")
Subscribe to a topic and validate that the specified payload is received within timeout. It is required that a connection has been established using `Connect` keyword. The payload can be specified as a python regular expression. If the specified payload is not received within timeout, an AssertionError is thrown. `topic` topic to subscribe to `qos` quality of service for the subscription `payload` payload (message) that is expected to arrive `timeout` time to wait for the payload to arrive Examples: | Subscribe And Validate | test/test | 1 | test message |
entailment
def unsubscribe(self, topic): """ Unsubscribe the client from the specified topic. `topic` topic to unsubscribe from Example: | Unsubscribe | test/mqtt_test | """ try: tmp = self._mqttc except AttributeError: logger.info('No MQTT Client instance found so nothing to unsubscribe from.') return if self._background_mqttc: logger.info('Closing background loop') self._background_mqttc.loop_stop() self._background_mqttc = None if topic in self._messages: del self._messages[topic] logger.info('Unsubscribing from topic: %s' % topic) self._unsubscribed = False self._mqttc.on_unsubscribe = self._on_unsubscribe self._mqttc.unsubscribe(str(topic)) timer_start = time.time() while (not self._unsubscribed and time.time() < timer_start + self._loop_timeout): self._mqttc.loop() if not self._unsubscribed: logger.warn('Client didn\'t receive an unsubscribe callback')
Unsubscribe the client from the specified topic. `topic` topic to unsubscribe from Example: | Unsubscribe | test/mqtt_test |
entailment
def disconnect(self): """ Disconnect from MQTT Broker. Example: | Disconnect | """ try: tmp = self._mqttc except AttributeError: logger.info('No MQTT Client instance found so nothing to disconnect from.') return self._disconnected = False self._unexpected_disconnect = False self._mqttc.on_disconnect = self._on_disconnect self._mqttc.disconnect() timer_start = time.time() while time.time() < timer_start + self._loop_timeout: if self._disconnected or self._unexpected_disconnect: break; self._mqttc.loop() if self._unexpected_disconnect: raise RuntimeError("The client disconnected unexpectedly")
Disconnect from MQTT Broker. Example: | Disconnect |
entailment
def publish_single(self, topic, payload=None, qos=0, retain=False, hostname="localhost", port=1883, client_id="", keepalive=60, will=None, auth=None, tls=None, protocol=mqtt.MQTTv31): """ Publish a single message and disconnect. This keyword uses the [http://eclipse.org/paho/clients/python/docs/#single|single] function of publish module. `topic` topic to which the message will be published `payload` message payload to publish (default None) `qos` qos of the message (default 0) `retain` retain flag (True or False, default False) `hostname` MQTT broker host (default localhost) `port` broker port (default 1883) `client_id` if not specified, a random id is generated `keepalive` keepalive timeout value for client `will` a dict containing will parameters for client: will = {'topic': "<topic>", 'payload':"<payload">, 'qos':<qos>, 'retain':<retain>} `auth` a dict containing authentication parameters for the client: auth = {'username':"<username>", 'password':"<password>"} `tls` a dict containing TLS configuration parameters for the client: dict = {'ca_certs':"<ca_certs>", 'certfile':"<certfile>", 'keyfile':"<keyfile>", 'tls_version':"<tls_version>", 'ciphers':"<ciphers">} `protocol` MQTT protocol version (MQTTv31 or MQTTv311) Example: Publish a message on specified topic and disconnect: | Publish Single | topic=t/mqtt | payload=test | hostname=127.0.0.1 | """ logger.info('Publishing to: %s:%s, topic: %s, payload: %s, qos: %s' % (hostname, port, topic, payload, qos)) publish.single(topic, payload, qos, retain, hostname, port, client_id, keepalive, will, auth, tls, protocol)
Publish a single message and disconnect. This keyword uses the [http://eclipse.org/paho/clients/python/docs/#single|single] function of publish module. `topic` topic to which the message will be published `payload` message payload to publish (default None) `qos` qos of the message (default 0) `retain` retain flag (True or False, default False) `hostname` MQTT broker host (default localhost) `port` broker port (default 1883) `client_id` if not specified, a random id is generated `keepalive` keepalive timeout value for client `will` a dict containing will parameters for client: will = {'topic': "<topic>", 'payload':"<payload">, 'qos':<qos>, 'retain':<retain>} `auth` a dict containing authentication parameters for the client: auth = {'username':"<username>", 'password':"<password>"} `tls` a dict containing TLS configuration parameters for the client: dict = {'ca_certs':"<ca_certs>", 'certfile':"<certfile>", 'keyfile':"<keyfile>", 'tls_version':"<tls_version>", 'ciphers':"<ciphers">} `protocol` MQTT protocol version (MQTTv31 or MQTTv311) Example: Publish a message on specified topic and disconnect: | Publish Single | topic=t/mqtt | payload=test | hostname=127.0.0.1 |
entailment
def publish_multiple(self, msgs, hostname="localhost", port=1883, client_id="", keepalive=60, will=None, auth=None, tls=None, protocol=mqtt.MQTTv31): """ Publish multiple messages and disconnect. This keyword uses the [http://eclipse.org/paho/clients/python/docs/#multiple|multiple] function of publish module. `msgs` a list of messages to publish. Each message is either a dict or a tuple. If a dict, it must be of the form: msg = {'topic':"<topic>", 'payload':"<payload>", 'qos':<qos>, 'retain':<retain>} Only the topic must be present. Default values will be used for any missing arguments. If a tuple, then it must be of the form: ("<topic>", "<payload>", qos, retain) See `publish single` for the description of hostname, port, client_id, keepalive, will, auth, tls, protocol. Example: | ${msg1} | Create Dictionary | topic=${topic} | payload=message 1 | | ${msg2} | Create Dictionary | topic=${topic} | payload=message 2 | | ${msg3} | Create Dictionary | topic=${topic} | payload=message 3 | | @{msgs} | Create List | ${msg1} | ${msg2} | ${msg3} | | Publish Multiple | msgs=${msgs} | hostname=127.0.0.1 | """ logger.info('Publishing to: %s:%s, msgs: %s' % (hostname, port, msgs)) publish.multiple(msgs, hostname, port, client_id, keepalive, will, auth, tls, protocol)
Publish multiple messages and disconnect. This keyword uses the [http://eclipse.org/paho/clients/python/docs/#multiple|multiple] function of publish module. `msgs` a list of messages to publish. Each message is either a dict or a tuple. If a dict, it must be of the form: msg = {'topic':"<topic>", 'payload':"<payload>", 'qos':<qos>, 'retain':<retain>} Only the topic must be present. Default values will be used for any missing arguments. If a tuple, then it must be of the form: ("<topic>", "<payload>", qos, retain) See `publish single` for the description of hostname, port, client_id, keepalive, will, auth, tls, protocol. Example: | ${msg1} | Create Dictionary | topic=${topic} | payload=message 1 | | ${msg2} | Create Dictionary | topic=${topic} | payload=message 2 | | ${msg3} | Create Dictionary | topic=${topic} | payload=message 3 | | @{msgs} | Create List | ${msg1} | ${msg2} | ${msg3} | | Publish Multiple | msgs=${msgs} | hostname=127.0.0.1 |
entailment
def user_to_request(handler): '''Add user to request if user logged in''' @wraps(handler) async def decorator(*args): request = _get_request(args) request[cfg.REQUEST_USER_KEY] = await get_cur_user(request) return await handler(*args) return decorator
Add user to request if user logged in
entailment
def add_synonym(self, other): """Every word in a group of synonyms shares the same list.""" self.synonyms.extend(other.synonyms) other.synonyms = self.synonyms
Every word in a group of synonyms shares the same list.
entailment
def find_one_sql(table, filter, fields=None): ''' >>> find_one_sql('tbl', {'foo': 10, 'bar': 'baz'}) ('SELECT * FROM tbl WHERE bar=$1 AND foo=$2', ['baz', 10]) >>> find_one_sql('tbl', {'id': 10}, fields=['foo', 'bar']) ('SELECT foo, bar FROM tbl WHERE id=$1', [10]) ''' keys, values = _split_dict(filter) fields = ', '.join(fields) if fields else '*' where = _pairs(keys) sql = 'SELECT {} FROM {} WHERE {}'.format(fields, table, where) return sql, values
>>> find_one_sql('tbl', {'foo': 10, 'bar': 'baz'}) ('SELECT * FROM tbl WHERE bar=$1 AND foo=$2', ['baz', 10]) >>> find_one_sql('tbl', {'id': 10}, fields=['foo', 'bar']) ('SELECT foo, bar FROM tbl WHERE id=$1', [10])
entailment
def insert_sql(table, data, returning='id'): ''' >>> insert_sql('tbl', {'foo': 'bar', 'id': 1}) ('INSERT INTO tbl (foo, id) VALUES ($1, $2) RETURNING id', ['bar', 1]) >>> insert_sql('tbl', {'foo': 'bar', 'id': 1}, returning=None) ('INSERT INTO tbl (foo, id) VALUES ($1, $2)', ['bar', 1]) >>> insert_sql('tbl', {'foo': 'bar', 'id': 1}, returning='pk') ('INSERT INTO tbl (foo, id) VALUES ($1, $2) RETURNING pk', ['bar', 1]) ''' keys, values = _split_dict(data) sql = 'INSERT INTO {} ({}) VALUES ({}){}'.format( table, ', '.join(keys), ', '.join(_placeholders(data)), ' RETURNING {}'.format(returning) if returning else '') return sql, values
>>> insert_sql('tbl', {'foo': 'bar', 'id': 1}) ('INSERT INTO tbl (foo, id) VALUES ($1, $2) RETURNING id', ['bar', 1]) >>> insert_sql('tbl', {'foo': 'bar', 'id': 1}, returning=None) ('INSERT INTO tbl (foo, id) VALUES ($1, $2)', ['bar', 1]) >>> insert_sql('tbl', {'foo': 'bar', 'id': 1}, returning='pk') ('INSERT INTO tbl (foo, id) VALUES ($1, $2) RETURNING pk', ['bar', 1])
entailment
def update_sql(table, filter, updates): ''' >>> update_sql('tbl', {'foo': 'a', 'bar': 1}, {'bar': 2, 'baz': 'b'}) ('UPDATE tbl SET bar=$1, baz=$2 WHERE bar=$3 AND foo=$4', [2, 'b', 1, 'a']) ''' where_keys, where_vals = _split_dict(filter) up_keys, up_vals = _split_dict(updates) changes = _pairs(up_keys, sep=', ') where = _pairs(where_keys, start=len(up_keys) + 1) sql = 'UPDATE {} SET {} WHERE {}'.format( table, changes, where) return sql, up_vals + where_vals
>>> update_sql('tbl', {'foo': 'a', 'bar': 1}, {'bar': 2, 'baz': 'b'}) ('UPDATE tbl SET bar=$1, baz=$2 WHERE bar=$3 AND foo=$4', [2, 'b', 1, 'a'])
entailment
def delete_sql(table, filter): ''' >>> delete_sql('tbl', {'foo': 10, 'bar': 'baz'}) ('DELETE FROM tbl WHERE bar=$1 AND foo=$2', ['baz', 10]) ''' keys, values = _split_dict(filter) where = _pairs(keys) sql = 'DELETE FROM {} WHERE {}'.format(table, where) return sql, values
>>> delete_sql('tbl', {'foo': 10, 'bar': 'baz'}) ('DELETE FROM tbl WHERE bar=$1 AND foo=$2', ['baz', 10])
entailment
def _pairs(keys, *, start=1, sep=' AND '): ''' >>> _pairs(['foo', 'bar', 'baz'], sep=', ') 'foo=$1, bar=$2, baz=$3' >>> _pairs(['foo', 'bar', 'baz'], start=2) 'foo=$2 AND bar=$3 AND baz=$4' ''' return sep.join('{}=${}'.format(k, i) for i, k in enumerate(keys, start))
>>> _pairs(['foo', 'bar', 'baz'], sep=', ') 'foo=$1, bar=$2, baz=$3' >>> _pairs(['foo', 'bar', 'baz'], start=2) 'foo=$2 AND bar=$3 AND baz=$4'
entailment
def _split_dict(dic): '''Split dict into sorted keys and values >>> _split_dict({'b': 2, 'a': 1}) (['a', 'b'], [1, 2]) ''' keys = sorted(dic.keys()) return keys, [dic[k] for k in keys]
Split dict into sorted keys and values >>> _split_dict({'b': 2, 'a': 1}) (['a', 'b'], [1, 2])
entailment
def play(seed=None): """Turn the Python prompt into an Adventure game. With optional the `seed` argument the caller can supply an integer to start the Python random number generator at a known state. """ global _game from .game import Game from .prompt import install_words _game = Game(seed) load_advent_dat(_game) install_words(_game) _game.start() print(_game.output[:-1])
Turn the Python prompt into an Adventure game. With optional the `seed` argument the caller can supply an integer to start the Python random number generator at a known state.
entailment
def write(self, more): """Append the Unicode representation of `s` to our output.""" if more: self.output += str(more).upper() self.output += '\n'
Append the Unicode representation of `s` to our output.
entailment
def yesno(self, s, yesno_callback, casual=False): """Ask a question and prepare to receive a yes-or-no answer.""" self.write(s) self.yesno_callback = yesno_callback self.yesno_casual = casual
Ask a question and prepare to receive a yes-or-no answer.
entailment
def start(self): """Start the game.""" # For old-fashioned players, accept five-letter truncations like # "inven" instead of insisting on full words like "inventory". for key, value in list(self.vocabulary.items()): if isinstance(key, str) and len(key) > 5: self.vocabulary[key[:5]] = value # Set things going. self.chest_room = self.rooms[114] self.bottle.contents = self.water self.yesno(self.messages[65], self.start2)
Start the game.
entailment
def start2(self, yes): """Display instructions if the user wants them.""" if yes: self.write_message(1) self.hints[3].used = True self.lamp_turns = 1000 self.oldloc2 = self.oldloc = self.loc = self.rooms[1] self.dwarves = [ Dwarf(self.rooms[n]) for n in (19, 27, 33, 44, 64) ] self.pirate = Pirate(self.chest_room) treasures = self.treasures self.treasures_not_found = len(treasures) for treasure in treasures: treasure.prop = -1 self.describe_location()
Display instructions if the user wants them.
entailment
def do_command(self, words): """Parse and act upon the command in the list of strings `words`.""" self.output = '' self._do_command(words) return self.output
Parse and act upon the command in the list of strings `words`.
entailment
def resume(self, obj): """Returns an Adventure game saved to the given file.""" if isinstance(obj, str): savefile = open(obj, 'rb') else: savefile = obj game = pickle.loads(zlib.decompress(savefile.read())) if savefile is not obj: savefile.close() # Reinstate the random number generator. game.random_generator = random.Random() game.random_generator.setstate(game.random_state) del game.random_state return game
Returns an Adventure game saved to the given file.
entailment
def parse(data, datafile): """Read the Adventure data file and return a ``Data`` object.""" data._last_travel = [0, [0]] # x and verbs used by section 3 while True: section_number = int(datafile.readline()) if not section_number: # no further sections break store = globals().get('section%d' % section_number) while True: fields = [ (int(field) if field.lstrip('-').isdigit() else field) for field in datafile.readline().strip().split('\t') ] if fields[0] == -1: # end-of-section marker break store(data, *fields) del data._last_travel # state used by section 3 del data._object # state used by section 5 data.object_list = sorted(set(data.objects.values()), key=attrgetter('n')) #data.room_list = sorted(set(data.rooms.values()), key=attrgetter('n')) for obj in data.object_list: name = obj.names[0] if hasattr(data, name): name = name + '2' # create identifiers like ROD2, PLANT2 setattr(data, name, obj) return data
Read the Adventure data file and return a ``Data`` object.
entailment
def _map_smtp_headers_to_api_parameters(self, email_message): """ Map the values passed in SMTP headers to API-ready 2-item tuples present in HEADERS_MAP header values must be a single string or list or tuple of strings :return: 2-item tuples of the form (api_name, api_values) """ api_data = [] for smtp_key, api_transformer in six.iteritems(self._headers_map): data_to_transform = email_message.extra_headers.pop(smtp_key, None) if data_to_transform is not None: if isinstance(data_to_transform, (list, tuple)): # map each value in the tuple/list for data in data_to_transform: api_data.append((api_transformer[0], api_transformer[1](data))) elif isinstance(data_to_transform, dict): for data in six.iteritems(data_to_transform): api_data.append(api_transformer(data)) else: # we only have one value api_data.append((api_transformer[0], api_transformer[1](data_to_transform))) return api_data
Map the values passed in SMTP headers to API-ready 2-item tuples present in HEADERS_MAP header values must be a single string or list or tuple of strings :return: 2-item tuples of the form (api_name, api_values)
entailment
def _send(self, email_message): """A helper method that does the actual sending.""" if not email_message.recipients(): return False from_email = sanitize_address(email_message.from_email, email_message.encoding) to_recipients = [sanitize_address(addr, email_message.encoding) for addr in email_message.to] try: post_data = [] post_data.append(('to', (",".join(to_recipients)),)) if email_message.bcc: bcc_recipients = [sanitize_address(addr, email_message.encoding) for addr in email_message.bcc] post_data.append(('bcc', (",".join(bcc_recipients)),)) if email_message.cc: cc_recipients = [sanitize_address(addr, email_message.encoding) for addr in email_message.cc] post_data.append(('cc', (",".join(cc_recipients)),)) post_data.append(('text', email_message.body,)) post_data.append(('subject', email_message.subject,)) post_data.append(('from', from_email,)) # get our recipient variables if they were passed in recipient_variables = email_message.extra_headers.pop('recipient_variables', None) if recipient_variables is not None: post_data.append(('recipient-variables', recipient_variables, )) for name, value in self._map_smtp_headers_to_api_parameters(email_message): post_data.append((name, value, )) if hasattr(email_message, 'alternatives') and email_message.alternatives: for alt in email_message.alternatives: if alt[1] == 'text/html': post_data.append(('html', alt[0],)) break # Map Reply-To header if present try: if email_message.reply_to: post_data.append(( "h:Reply-To", ", ".join(map(force_text, email_message.reply_to)), )) except AttributeError: pass if email_message.attachments: for attachment in email_message.attachments: post_data.append(('attachment', (attachment[0], attachment[1],))) content, header = encode_multipart_formdata(post_data) headers = {'Content-Type': header} else: content = post_data headers = None response = requests.post(self._api_url + "messages", auth=("api", self._access_key), data=content, headers=headers) except: if not self.fail_silently: raise return False if response.status_code != 200: if not self.fail_silently: raise MailgunAPIError(response) return False return True
A helper method that does the actual sending.
entailment
def send_messages(self, email_messages): """Sends one or more EmailMessage objects and returns the number of email messages sent. """ if not email_messages: return num_sent = 0 for message in email_messages: if self._send(message): num_sent += 1 return num_sent
Sends one or more EmailMessage objects and returns the number of email messages sent.
entailment
def student_view(self, context=None): """ Build the fragment for the default student view """ context = context or {} context.update({ 'display_name': self.display_name, 'image_url': self.image_url, 'thumbnail_url': self.thumbnail_url or self.image_url, 'description': self.description, 'xblock_id': text_type(self.scope_ids.usage_id), 'alt_text': self.alt_text or self.display_name, }) fragment = self.build_fragment( template='view.html', context=context, css=[ 'view.less.css', URL_FONT_AWESOME_CSS, ], js=[ 'draggabilly.pkgd.js', 'view.js', ], js_init='ImageModalView', ) return fragment
Build the fragment for the default student view
entailment
def build_fragment( self, template='', context=None, css=None, js=None, js_init=None, ): """ Creates a fragment for display. """ template = 'templates/' + template context = context or {} css = css or [] js = js or [] rendered_template = '' if template: rendered_template = self.loader.render_django_template( template, context=Context(context), i18n_service=self.runtime.service(self, 'i18n'), ) fragment = Fragment(rendered_template) for item in css: if item.startswith('/'): url = item else: item = 'public/' + item url = self.runtime.local_resource_url(self, item) fragment.add_css_url(url) for item in js: item = 'public/' + item url = self.runtime.local_resource_url(self, item) fragment.add_javascript_url(url) if js_init: fragment.initialize_js(js_init) return fragment
Creates a fragment for display.
entailment
def _parse_title(file_path): """ Parse a title from a file name """ title = file_path title = title.split('/')[-1] title = '.'.join(title.split('.')[:-1]) title = ' '.join(title.split('-')) title = ' '.join([ word.capitalize() for word in title.split(' ') ]) return title
Parse a title from a file name
entailment
def _read_files(files): """ Read the contents of a list of files """ file_contents = [ ( _parse_title(file_path), _read_file(file_path), ) for file_path in files ] return file_contents
Read the contents of a list of files
entailment