code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
rule_values = self.update_targets(sources, destinations, services) rule_values.update(name=name, comment=comment) rule_values.update(is_disabled=is_disabled) if isinstance(action, Action): rule_action = action else: rule_action = Action() rule_action.action = action if not rule_action.action in self._actions: raise CreateRuleFailed('Action specified is not valid for this ' 'rule type; action: {}' .format(rule_action.action)) rule_values.update(action=rule_action.data) rule_values.update(self.update_logical_if(logical_interfaces)) params = None href = self.href if add_pos is not None: href = self.add_at_position(add_pos) else: params = self.add_before_after(before, after) return ElementCreator( self.__class__, exception=CreateRuleFailed, href=href, params=params, json=rule_values)
def create(self, name, sources=None, destinations=None, services=None, action='allow', is_disabled=False, logical_interfaces=None, add_pos=None, after=None, before=None, comment=None)
Create an Ethernet rule :param str name: name of rule :param sources: source/s for rule :type sources: list[str, Element] :param destinations: destination/s for rule :type destinations: list[str, Element] :param services: service/s for rule :type services: list[str, Element] :param str action: \|allow\|continue\|discard\|refuse\|blacklist :param bool is_disabled: whether to disable rule or not :param list logical_interfaces: logical interfaces by name :param int add_pos: position to insert the rule, starting with position 1. If the position value is greater than the number of rules, the rule is inserted at the bottom. If add_pos is not provided, rule is inserted in position 1. Mutually exclusive with ``after`` and ``before`` params. :param str after: Rule tag to add this rule after. Mutually exclusive with ``add_pos`` and ``before`` params. :param str before: Rule tag to add this rule before. Mutually exclusive with ``add_pos`` and ``after`` params. :raises MissingReuqiredInput: when options are specified the need additional setting, i.e. use_vpn action requires a vpn policy be specified. :raises CreateRuleFailed: rule creation failure :return: newly created rule :rtype: EthernetRule
3.532212
3.634791
0.971778
for intvalue, sevname in SEVERITY.items(): if name.lower() == sevname: return intvalue return 1
def _severity_by_name(name)
Return the severity integer value by it's name. If not found, return 'information'. :rtype: int
5.337548
5.423367
0.984176
for param in self.data.get('situation_parameters', []): cache = ElementCache(data=self.make_request(href=param)) yield type('SituationParameter', (SituationParameter,), { 'data': cache})(name=cache.name, type=cache.type, href=param)
def situation_parameters(self)
Situation parameters defining detection logic for the context. This will return a list of SituationParameter indicating how the detection is made, i.e. regular expression, integer value, etc. :rtype: list(SituationParameter)
7.38067
8.979151
0.821979
for param in self.data.get('parameter_values', []): cache = ElementCache(data=self.make_request(href=param)) name = '{}'.format(cache.type.title()).replace('_', '') yield type(name, (SituationParameterValue,), { 'data': cache})(name=cache.name, type=cache.type, href=param)
def parameter_values(self)
Parameter values for this inspection situation. This correlate to the the situation_context. :rtype: list(SituationParameterValue)
9.377131
8.598848
1.09051
try: json = { 'name': name, 'comment': comment, 'description': description, 'situation_context_ref': situation_context.href, 'attacker': attacker, 'victim': target, 'severity': _severity_by_name(severity)} element = ElementCreator(cls, json) tag = situation_type or SituationTag('User Defined Situations') tag.add_element(element) return element except ElementNotFound as e: raise CreateElementFailed('{}. Inspection Situation Contexts require SMC ' 'version 6.5 and above.'.format(str(e)))
def create(cls, name, situation_context, attacker=None, target=None, severity='information', situation_type=None, description=None, comment=None)
Create an inspection situation. :param str name: name of the situation :param InspectionSituationContext situation_context: The situation context type used to define this situation. Identifies the proper parameter that identifies how the situation is defined (i.e. regex, etc). :param str attacker: Attacker information, used to identify last packet the triggers attack and is only used for blacklisting. Values can be packet_source, packet_destination, connection_source, or connection_destination :param str target: Target information, used to identify the last packet that triggers the attack and is only used for blacklisting. Values can be packet_source, packet_destination, connection_source, or connection_destination :param str severity: severity for this situation. Valid values are critical, high, low, information :param str description: optional description :param str comment: optional comment
6.397536
6.47761
0.987638
for parameter in self.situation_context.situation_parameters: if parameter.type == 'regexp': return self.add_parameter_value( 'reg_exp_situation_parameter_values', **{'parameter_ref': parameter.href, 'reg_exp': regexp}) # Treat as raw string raise CreateElementFailed('The situation does not support a regular ' 'expression as a context value.')
def create_regular_expression(self, regexp)
Create a regular expression for this inspection situation context. The inspection situation must be using an inspection context that supports regex. :param str regexp: regular expression string :raises CreateElementFailed: failed to modify the situation
10.443574
8.92519
1.170123
if not filename: filename = '{}{}'.format(self.name, '.zip') try: self.make_request( EngineCommandFailed, resource='content', filename=filename) except IOError as e: raise EngineCommandFailed("Snapshot download failed: {}" .format(e))
def download(self, filename=None)
Download snapshot to filename :param str filename: fully qualified path including filename .zip :raises EngineCommandFailed: IOError occurred downloading snapshot :return: None
8.598282
6.010433
1.43056
return Task.execute(self, 'upload', params={'filter': engine}, timeout=timeout, wait_for_finish=wait_for_finish, **kw)
def upload(self, engine, timeout=5, wait_for_finish=False, **kw)
Upload policy to specific device. Using wait for finish returns a poller thread for monitoring progress:: policy = FirewallPolicy('_NSX_Master_Default') poller = policy.upload('myfirewall', wait_for_finish=True) while not poller.done(): poller.wait(3) print(poller.task.progress) print("Task finished: %s" % poller.message()) :param str engine: name of device to upload policy to :raises: TaskRunFailed :return: TaskOperationPoller
5.562015
6.390201
0.870397
result = self.make_request( resource='search_rule', params={'filter': search}) if result: results = [] for data in result: typeof = data.get('type') if 'ethernet' in typeof: klazz = lookup_class('ethernet_rule') elif typeof in [ 'ips_ipv4_access_rule', 'l2_interface_ipv4_access_rule']: klazz = lookup_class('layer2_ipv4_access_rule') else: klazz = lookup_class(typeof) results.append(klazz(**data)) return results return []
def search_rule(self, search)
Search a rule for a rule tag or name value Result will be the meta data for rule (name, href, type) Searching for a rule in specific policy:: f = FirewallPolicy(policy) search = f.search_rule(searchable) :param str search: search string :return: rule elements matching criteria :rtype: list(Element)
4.406803
4.713205
0.934991
json = {'target_ref': engine.href, 'duration_type': duration_type} return [RuleCounter(**rule) for rule in self.make_request( method='create', resource='rule_counter', json=json)]
def rule_counters(self, engine, duration_type='one_week', duration=0, start_time=0)
.. versionadded:: 0.5.6 Obtain rule counters for this policy. Requires SMC >= 6.2 Rule counters can be obtained for a given policy and duration for those counters can be provided in duration_type. A custom start range can also be provided. :param Engine engine: the target engine to obtain rule counters from :param str duration_type: duration for obtaining rule counters. Valid options are: one_day, one_week, one_month, six_months, one_year, custom, since_last_upload :param int duration: if custom set for duration type, specify the duration in seconds (Default: 0) :param int start_time: start time in milliseconds (Default: 0) :raises: ActionCommandFailed :return: list of rule counter objects :rtype: RuleCounter
7.377041
7.736112
0.953585
vpn_profile = element_resolver(vpn_profile) or \ VPNProfile('VPN-A Suite').href json = {'mobile_vpn_topology_mode': mobile_vpn_toplogy_mode, 'name': name, 'nat': nat, 'vpn_profile': vpn_profile} try: return ElementCreator(cls, json) except CreateElementFailed as err: raise CreatePolicyFailed(err)
def create(cls, name, nat=False, mobile_vpn_toplogy_mode=None, vpn_profile=None)
Create a new policy based VPN :param name: name of vpn policy :param bool nat: whether to apply NAT to the VPN (default False) :param mobile_vpn_toplogy_mode: whether to allow remote vpn :param VPNProfile vpn_profile: reference to VPN profile, or uses default :rtype: PolicyVPN
5.469472
5.86033
0.933304
if self.nat: self.data['nat'] = False else: self.data['nat'] = True
def enable_disable_nat(self)
Enable or disable NAT on this policy. If NAT is disabled, it will be enabled and vice versa. :return: None
3.973869
4.839147
0.821192
try: gateway = gateway.vpn.internal_gateway.href # Engine except AttributeError: gateway = element_resolver(gateway) # External Gateway self.make_request( PolicyCommandFailed, method='create', resource='mobile_gateway_node', json={'gateway': gateway, 'node_usage': 'mobile'})
def add_mobile_gateway(self, gateway)
Add a mobile VPN gateway to this policy VPN. Example of adding or removing a mobile VPN gateway:: policy_vpn = PolicyVPN('myvpn') policy_vpn.open() policy_vpn.add_mobile_vpn_gateway(ExternalGateway('extgw3')) for mobile_gateway in policy_vpn.mobile_gateway_node: if mobile_gateway.gateway == ExternalGateway('extgw3'): mobile_gateway.delete() policy_vpn.save() policy_vpn.close() :param Engine,ExternalGateway gateway: An external gateway, engine or href for the mobile gateway :raises PolicyCommandFailed: could not add gateway
21.067366
10.675525
1.973427
try: vpn = PolicyVPN(vpn_policy) vpn.open() if vpn_role == 'central': vpn.add_central_gateway(internal_gateway_href) else: vpn.add_satellite_gateway(internal_gateway_href) vpn.save() vpn.close() except ElementNotFound: return False return True
def add_internal_gateway_to_vpn(internal_gateway_href, vpn_policy, vpn_role='central')
Add an internal gateway (managed engine node) to a VPN policy based on the internal gateway href. :param str internal_gateway_href: href for engine internal gw :param str vpn_policy: name of vpn policy :param str vpn_role: central|satellite :return: True for success :rtype: bool
2.704595
2.561956
1.055676
if self.enabled: self.update(enabled=False) else: self.update(enabled=True)
def enable_disable(self)
Enable or disable the tunnel link between endpoints. :raises UpdateElementFailed: failed with reason :return: None
3.400212
3.41918
0.994453
json = {} directions = {src: 'end_point1', dst: 'end_point2'} for direction, key in directions.items(): json[key] = {'address_mode': 'any'} if \ 'any' in direction.lower() else {'address_mode': 'address', 'ip_network': direction} if src_port1: json.setdefault('end_point1').update( port1=src_port1, port2=src_port2 or src_port1, port_mode=src_proto) if dst_port1: json.setdefault('end_point2').update( port1=dst_port1, port2=dst_port2 or dst_port1, port_mode=dst_proto) json.update(duration=duration) return json
def prepare_blacklist(src, dst, duration=3600, src_port1=None, src_port2=None, src_proto='predefined_tcp', dst_port1=None, dst_port2=None, dst_proto='predefined_tcp')
Create a blacklist entry. A blacklist can be added directly from the engine node, or from the system context. If submitting from the system context, it becomes a global blacklist. This will return the properly formatted json to submit. :param src: source address, with cidr, i.e. 10.10.10.10/32 or 'any' :param dst: destination address with cidr, i.e. 1.1.1.1/32 or 'any' :param int duration: length of time to blacklist Both the system and engine context blacklist allow kw to be passed to provide additional functionality such as adding source and destination ports or port ranges and specifying the protocol. The following parameters define the ``kw`` that can be passed. The following example shows creating an engine context blacklist using additional kw:: engine.blacklist('1.1.1.1/32', '2.2.2.2/32', duration=3600, src_port1=1000, src_port2=1500, src_proto='predefined_udp', dst_port1=3, dst_port2=3000, dst_proto='predefined_udp') :param int src_port1: start source port to limit blacklist :param int src_port2: end source port to limit blacklist :param str src_proto: source protocol. Either 'predefined_tcp' or 'predefined_udp'. (default: 'predefined_tcp') :param int dst_port1: start dst port to limit blacklist :param int dst_port2: end dst port to limit blacklist :param str dst_proto: dst protocol. Either 'predefined_tcp' or 'predefined_udp'. (default: 'predefined_tcp') .. note:: if blocking a range of ports, use both src_port1 and src_port2, otherwise providing only src_port1 is adequate. The same applies to dst_port1 / dst_port2. In addition, if you provide src_portX but not dst_portX (or vice versa), the undefined port side definition will default to all ports.
3.115662
3.288182
0.947533
element = element_resolver(element) self.make_request( ModificationFailed, method='create', resource='category_add_element', json={'value': element})
def add_element(self, element)
Element can be href or type :py:class:`smc.base.model.Element` :: >>> from smc.elements.other import Category >>> category = Category('foo') >>> category.add_element(Host('kali')) :param str,Element element: element to add to tag :raises: ModificationFailed: failed adding element :return: None
19.591761
19.233313
1.018637
tags = element_resolver(tags) self.update( category_parent_ref=tags, append_lists=append_lists)
def add_category_tag(self, tags, append_lists=True)
Add this category to a category tag (group). This provides drop down filters in the SMC UI by category tag. :param list tags: category tag by name :param bool append_lists: append to existing tags or overwrite default: append) :type tags: list(str) :return: None
12.433796
15.082115
0.824407
categories = element_resolver(categories) diff = [category for category in self.data['category_child_ref'] if category not in categories] self.update(category_child_ref=diff)
def remove_category(self, categories)
Remove a category from this Category Tag (group). :param list categories: categories to remove :type categories: list(str,Element) :return: None
7.813067
8.384337
0.931865
self.entries.setdefault('entries', []).append(prepare_blacklist( src, dst, duration, src_port1, src_port2, src_proto, dst_port1, dst_port2, dst_proto))
def add_entry(self, src, dst, duration=3600, src_port1=None, src_port2=None, src_proto='predefined_tcp', dst_port1=None, dst_port2=None, dst_proto='predefined_tcp')
Create a blacklist entry. A blacklist can be added directly from the engine node, or from the system context. If submitting from the system context, it becomes a global blacklist. This will return the properly formatted json to submit. :param src: source address, with cidr, i.e. 10.10.10.10/32 or 'any' :param dst: destination address with cidr, i.e. 1.1.1.1/32 or 'any' :param int duration: length of time to blacklist Both the system and engine context blacklist allow kw to be passed to provide additional functionality such as adding source and destination ports or port ranges and specifying the protocol. The following parameters define the ``kw`` that can be passed. The following example shows creating an engine context blacklist using additional kw:: engine.blacklist('1.1.1.1/32', '2.2.2.2/32', duration=3600, src_port1=1000, src_port2=1500, src_proto='predefined_udp', dst_port1=3, dst_port2=3000, dst_proto='predefined_udp') :param int src_port1: start source port to limit blacklist :param int src_port2: end source port to limit blacklist :param str src_proto: source protocol. Either 'predefined_tcp' or 'predefined_udp'. (default: 'predefined_tcp') :param int dst_port1: start dst port to limit blacklist :param int dst_port2: end dst port to limit blacklist :param str dst_proto: dst protocol. Either 'predefined_tcp' or 'predefined_udp'. (default: 'predefined_tcp') .. note:: if blocking a range of ports, use both src_port1 and src_port2, otherwise providing only src_port1 is adequate. The same applies to dst_port1 / dst_port2. In addition, if you provide src_portX but not dst_portX (or vice versa), the undefined port side definition will default to all ports.
3.396958
3.404655
0.997739
was_created, was_modified = False, False element = None try: element = cls.get(kwargs.get('name')) was_modified = element.update_members( kwargs.get('members', []), append_lists=append_lists, remove_members=remove_members) except ElementNotFound: element = cls.create( kwargs.get('name'), members = kwargs.get('members', [])) was_created = True if with_status: return element, was_modified, was_created return element
def update_or_create(cls, append_lists=True, with_status=False, remove_members=False, **kwargs)
Update or create group entries. If the group exists, the members will be updated. Set append_lists=True to add new members to the list, or False to reset the list to the provided members. If setting remove_members, this will override append_lists if set. :param bool append_lists: add to existing members, if any :param bool remove_members: remove specified members instead of appending or overwriting :paran dict kwargs: keyword arguments to satisfy the `create` constructor if the group needs to be created. :raises CreateElementFailed: could not create element with reason :return: element instance by type :rtype: Element
3.053502
2.785161
1.096347
if members: elements = [element_resolver(element) for element in members] if remove_members: element = [e for e in self.members if e not in elements] if set(element) == set(self.members): remove_members = element = False append_lists = False elif append_lists: element = [e for e in elements if e not in self.members] else: element = list(set(elements)) if element or remove_members: self.update( element=element, append_lists=append_lists) return True return False
def update_members(self, members, append_lists=False, remove_members=False)
Update group members with member list. Set append=True to append to existing members, or append=False to overwrite. :param list members: new members for group by href or Element :type members: list[str, Element] :param bool append_lists: whether to append :param bool remove_members: remove members from the group :return: bool was modified or not
3.307923
3.388077
0.976342
element = [] if members is None else element_resolver(members) json = {'name': name, 'element': element, 'comment': comment} return ElementCreator(cls, json)
def create(cls, name, members=None, comment=None)
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
8.056517
7.090465
1.136247
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)
def generate(self, start_time=0, end_time=0, senders=None, wait_for_finish=False, timeout=5, **kw): # @ReservedAssignment if start_time and end_time
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
4.130214
4.593247
0.899193
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)
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
13.168143
9.819635
1.341001
self.make_request( raw_result=True, resource='export', filename=filename, headers = {'accept': 'application/pdf'})
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
9.087857
10.193156
0.891565
result = self.make_request( resource='export', params={'format': 'txt'}, filename=filename, raw_result=True, headers = {'accept': 'text/plain'}) if not filename: return result.content
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
5.59273
6.206647
0.901087
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)
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
3.436191
2.530943
1.357672
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)
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
3.123752
2.865558
1.090103
return cls.create_gre_tunnel_mode( name, local_endpoint, remote_endpoint, policy_vpn=None, mtu=mtu, pmtu_discovery=pmtu_discovery, ttl=ttl, enabled=enabled, comment=comment)
def create_gre_tunnel_no_encryption(cls, name, local_endpoint, remote_endpoint, mtu=0, pmtu_discovery=True, ttl=0, enabled=True, comment=None)
Create a GRE Tunnel with no encryption. See `create_gre_tunnel_mode` for constructor descriptions.
2.621252
2.477072
1.058206
if self.data.get('preshared_key'): self.update(preshared_key=new_key)
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
3.920507
4.319486
0.907633
if self.endpoint_ref and self.tunnel_interface_ref: return InternalEndpoint(href=self.endpoint_ref) return Element.from_href(self.endpoint_ref)
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
10.594459
8.04716
1.316546
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)
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
3.049352
3.356816
0.908406
tunnel_interface = tunnel_interface.href if tunnel_interface else None return TunnelEndpoint( endpoint_ref=endpoint.href, tunnel_interface_ref=tunnel_interface)
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
4.324216
5.072681
0.852452
tunnel_interface = tunnel_interface.href if tunnel_interface else None return TunnelEndpoint( gateway_ref=gateway.href, tunnel_interface_ref=tunnel_interface)
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
4.15316
4.62704
0.897585
self.interface.set_auth_request(interface_id, address) self._engine.update()
def set_auth_request(self, interface_id, address=None)
Set the authentication request field for the specified engine.
5.705154
6.426922
0.887696
self.interface.set_unset(interface_id, 'primary_heartbeat') self._engine.update()
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
11.032043
11.195998
0.985356
self.interface.set_unset(interface_id, 'backup_heartbeat') self._engine.update()
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
11.351171
12.672351
0.895743
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()
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.
5.068781
4.467801
1.134514
self.interface.set_unset(interface_id, 'backup_mgt') self._engine.update()
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
10.58088
10.302416
1.027029
self.interface.set_unset(interface_id, 'outgoing') self._engine.update()
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
12.243402
12.883636
0.950306
self._interface.data.update(qos_limit=-1, qos_mode='dscp', qos_policy_ref=qos_policy.href)
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
13.229636
11.665018
1.134129
super(Interface, self).delete() for route in self._engine.routing: if route.to_delete: route.delete() self._engine._del_cache()
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()
9.897369
6.848115
1.445269
super(Interface, self).update(*args, **kw) self._engine._del_cache() return self
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
9.359992
13.189214
0.70967
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
def addresses(self)
Return 3-tuple with (address, network, nicid) :return: address related information of interface as 3-tuple list :rtype: list
3.764827
2.913836
1.292052
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
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)
2.8217
2.847647
0.990888
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
def get_boolean(self, name)
Get the boolean value for attribute specified from the sub interface/s.
4.26403
3.756059
1.13524
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
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
11.927411
10.998805
1.084428
self.data['interfaces'] = [] if self.typeof != 'tunnel_interface': self.data['vlanInterfaces'] = [] self.update() self.delete_invalid_route()
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
12.384481
12.173185
1.017358
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()
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
4.636794
4.598841
1.008253
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
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
2.628862
2.531402
1.038501
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
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
4.565935
4.492297
1.016392
name = super(Interface, self).name return name if name else self.data.get('name')
def name(self)
Read only name tag
8.939985
9.072352
0.98541
base_interface = ElementCache() base_interface.update( interface_id=str(interface_id), interfaces=[]) if 'zone_ref' in kw: zone_ref = kw.pop('zone_ref') base_interface.update(zone_ref=zone_helper(zone_ref) if zone_ref else None) if 'comment' in kw: base_interface.update(comment=kw.pop('comment')) self.data = base_interface interfaces = kw.pop('interfaces', []) if interfaces: for interface in interfaces: if interface.get('cluster_virtual', None) or \ len(interface.get('nodes', [])) > 1: # Cluster kw.update(interface_id=interface_id, interfaces=interfaces) cvi = ClusterPhysicalInterface(**kw) cvi.data.pop('vlanInterfaces', None) self.data.update(cvi.data) else: # Single interface FW for node in interface.get('nodes', []): node.update(nodeid=1) sni = SingleNodeInterface.create(interface_id, **node) base_interface.setdefault('interfaces', []).append( {sni.typeof: sni.data})
def _add_interface(self, interface_id, **kw)
Create a tunnel interface. Kw argument list is as follows
4.964882
4.990888
0.994789
return [{'address': interface.address, 'nicid': interface.nicid} for interface in self.interfaces if isinstance(interface, (NodeInterface, SingleNodeInterface))]
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)
9.231957
5.264088
1.753762
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()
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
3.636562
3.651923
0.995794
if mode in ['lb', 'ha']: self.data['aggregate_mode'] = mode self.data['second_interface_id'] = ','.join(map(str, interfaces)) self.save()
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
7.213736
4.750671
1.518467
self.data['arp_entry'].append({ 'ipaddress': ipaddress, 'macaddress': macaddress, 'netmask': netmask, 'type': arp_type})
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
2.604284
2.789983
0.933441
_kw = copy.deepcopy(kw) # Preserve original kw, especially lists mgt = mgt if mgt else {} if 'cvi_mode' in _kw: self.data.update(cvi_mode=_kw.pop('cvi_mode')) if 'macaddress' in _kw: self.data.update( macaddress=_kw.pop('macaddress')) if 'cvi_mode' not in self.data: self.data.update(cvi_mode='packetdispatch') if 'zone_ref' in _kw: zone_ref = _kw.pop('zone_ref') self.data.update(zone_ref=zone_helper(zone_ref) if zone_ref else None) if 'comment' in _kw: self.data.update(comment=_kw.pop('comment')) interfaces = _kw.pop('interfaces', []) for interface in interfaces: vlan_id = interface.pop('vlan_id', None) if vlan_id: _interface_id = '{}.{}'.format(interface_id, vlan_id) else: _interface_id = interface_id _interface = [] if_mgt = {k: str(v) == str(_interface_id) for k, v in mgt.items()} if 'cluster_virtual' in interface and 'network_value' in interface: cluster_virtual = interface.pop('cluster_virtual') network_value = interface.pop('network_value') if cluster_virtual and network_value: cvi = ClusterVirtualInterface.create( _interface_id, cluster_virtual, network_value, auth_request=True if if_mgt.get('primary_mgt') else False) _interface.append({cvi.typeof: cvi.data}) for node in interface.pop('nodes', []): _node = if_mgt.copy() _node.update(outgoing=True if if_mgt.get('primary_mgt') else False) # Add node specific key/value pairs set on the node. This can # also be used to override management settings _node.update(node) ndi = NodeInterface.create( interface_id=_interface_id, **_node) _interface.append({ndi.typeof: ndi.data}) if vlan_id: vlan_interface = { 'interface_id': _interface_id, 'zone_ref': zone_helper(interface.pop('zone_ref', None)), 'comment': interface.pop('comment', None), 'interfaces': _interface} # Add remaining kwargs on vlan level to VLAN physical interface for name, value in interface.items(): vlan_interface[name] = value self.data.setdefault('vlanInterfaces', []).append( vlan_interface) else: self.data.setdefault('interfaces', []).extend( _interface) # Remaining kw go to base level interface for name, value in _kw.items(): self.data[name] = value
def _add_interface(self, interface_id, mgt=None, **kw)
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.
3.280192
3.286864
0.99797
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()
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
7.002006
5.931305
1.180517
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()
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
3.334127
3.440066
0.969204
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
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
5.281527
5.413441
0.975632
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))
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
5.153558
4.480151
1.150309
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
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
4.136168
3.718023
1.112464
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
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
3.485358
3.702012
0.941477
# 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))
def get(self, interface_id)
Get the interface from engine json :param str interface_id: interface ID to find :raises InterfaceNotFound: Cannot find interface
5.143394
4.994239
1.029865
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
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).
3.673331
3.649391
1.00656
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
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.
3.988688
3.502555
1.138794
#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)
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
3.708137
2.791645
1.328298
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
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
3.564087
3.411535
1.044716
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)
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.
5.408726
4.830171
1.119779
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
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
3.138318
3.167759
0.990706
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')]
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).
10.38208
9.774696
1.062138
as_number = as_dotted(str(as_number)) json = {'name': name, 'as_number': as_number, 'comment': comment} return ElementCreator(cls, json)
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
4.766408
5.129431
0.929228
json = {'name': name, 'external': external_distance, 'internal': internal_distance, 'local': local_distance, 'port': port} if subnet_distance: d = [{'distance': distance, 'subnet': subnet.href} for subnet, distance in subnet_distance] json.update(distance_entry=d) return ElementCreator(cls, json)
def create(cls, name, port=179, external_distance=20, internal_distance=200, local_distance=200, subnet_distance=None)
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
3.659241
3.852021
0.949954
return [(Element.from_href(entry.get('subnet')), entry.get('distance')) for entry in self.data.get('distance_entry')]
def subnet_distance(self)
Specific subnet administrative distances :return: list of tuple (subnet, distance)
15.332497
11.874412
1.291222
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)
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
3.736791
3.668082
1.018732
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)
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
1.868121
1.868463
0.999817
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)
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
2.594286
2.889758
0.897752
for value in values: if value in self.data: self.data[value] = True
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
3.701562
5.614092
0.659334
for value in values: if value in self.data: self.data[value] = False
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
3.66739
5.92368
0.619107
permissions = [] for permission, value in self.data.items(): if permission not in self._reserved: permissions.append({permission: value}) return permissions
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)
4.686952
4.774618
0.981639
_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}
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
2.845208
2.321775
1.225445
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]})
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.
4.054525
3.748878
1.08153
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
def _update_field(self, natvalue)
Update this NATValue if values are different :rtype: bool
2.599475
2.537833
1.024289
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
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
4.864305
4.424984
1.099282
if self.typeof in self: return NATValue(self.get(self.typeof, {}).get( 'translated_value'))
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
23.400253
11.99895
1.950192
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
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
5.177242
4.929099
1.050342
_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
def request(self, uri, method='GET', body=None, headers=None, **kwargs)
Implementation of httplib2's Http.request.
3.162194
3.103806
1.018812
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
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} |
2.298057
2.496342
0.92057
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)
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} |
2.883952
3.149928
0.915561
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]
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 |
3.801386
4.105473
0.925931
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
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 |
4.110615
4.414039
0.931259
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")
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 |
3.387929
3.699933
0.915673
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')
def unsubscribe(self, topic)
Unsubscribe the client from the specified topic. `topic` topic to unsubscribe from Example: | Unsubscribe | test/mqtt_test |
3.402013
3.475858
0.978755
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")
def disconnect(self)
Disconnect from MQTT Broker. Example: | Disconnect |
4.087214
4.146779
0.985636
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)
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 |
2.024328
2.38631
0.848309
logger.info('Publishing to: %s:%s, msgs: %s' % (hostname, port, msgs)) publish.multiple(msgs, hostname, port, client_id, keepalive, will, auth, tls, protocol)
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 |
2.505308
3.067239
0.816796
'''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
def user_to_request(handler)
Add user to request if user logged in
4.698852
4.152031
1.1317
self.synonyms.extend(other.synonyms) other.synonyms = self.synonyms
def add_synonym(self, other)
Every word in a group of synonyms shares the same list.
3.344
3.072982
1.088194