text
stringlengths
81
112k
Return resolving IP address(es) from host name. async def resolve( self, host, port=80, family=None, qtype='A', logging=True ): """Return resolving IP address(es) from host name.""" if self.host_is_ip(host): return host _host = self._cached_hosts.get(host) if _h...
Asynchronously create a :class:`Proxy` object. :param str host: A passed host can be a domain or IP address. If the host is a domain, try to resolve it :param str \*args: (optional) Positional arguments that :class:`Proxy` takes :param str \*\*kwargs: ...
Error rate: from 0 to 1. For example: 0.7 = 70% requests ends with error. :rtype: float .. versionadded:: 0.2.0 def error_rate(self): """Error rate: from 0 to 1. For example: 0.7 = 70% requests ends with error. :rtype: float .. versionadded:: 0.2.0 ...
Return supported schemes. def schemes(self): """Return supported schemes.""" if not self._schemes: _schemes = [] if self.types.keys() & _HTTP_PROTOS: _schemes.append('HTTP') if self.types.keys() & _HTTPS_PROTOS: _schemes.append('HTTPS'...
The average connection/response time. :rtype: float def avg_resp_time(self): """The average connection/response time. :rtype: float """ if not self._runtimes: return 0 return round(sum(self._runtimes) / len(self._runtimes), 2)
Return the proxy's properties in JSON format. :rtype: dict def as_json(self): """Return the proxy's properties in JSON format. :rtype: dict """ info = { 'host': self.host, 'port': self.port, 'geo': { 'country': {'code': self....
Receive proxies from the provider and return them. :return: :attr:`.proxies` async def get_proxies(self): """Receive proxies from the provider and return them. :return: :attr:`.proxies` """ log.debug('Try to get proxies from %s' % self.domain) async with aiohttp.Clien...
Save proxies to a file. async def save(proxies, filename): """Save proxies to a file.""" with open(filename, 'w') as f: while True: proxy = await proxies.get() if proxy is None: break proto = 'https' if 'HTTPS' in proxy.types else 'http' r...
Updates global configuration settings with given values. First checks if given configuration values differ from current values. If any of the configuration values changed, generates a change event. Currently we generate change event for any configuration change. Note: This method is ide...
Converts binary representation label to integer. :param buf: Binary representation of label. :return: MPLS Label and BoS bit. def label_from_bin(buf): """ Converts binary representation label to integer. :param buf: Binary representation of label. :return: MPLS Label and BoS bit. """ ...
Removes VRF table associated with given `vrf_conf`. Cleans up other links to this table as well. def on_remove_vrf_conf(self, evt): """Removes VRF table associated with given `vrf_conf`. Cleans up other links to this table as well. """ vrf_conf = evt.value # Detach Vrf...
Event handler for new VrfConf. Creates a VrfTable to store routing information related to new Vrf. Also arranges for related paths to be imported to this VrfTable. def on_add_vrf_conf(self, evt): """Event handler for new VrfConf. Creates a VrfTable to store routing information related...
Parses family and prefix in Zebra format. def _parse_zebra_family_prefix(buf): """ Parses family and prefix in Zebra format. """ (family,) = struct.unpack_from(_ZEBRA_FAMILY_FMT, buf) rest = buf[_ZEBRA_FAMILY_SIZE:] if socket.AF_INET == family: (prefix, p_len) = struct.unpack_from(_ZEB...
Serializes family and prefix in Zebra format. def _serialize_zebra_family_prefix(prefix): """ Serializes family and prefix in Zebra format. """ if ip.valid_ipv4(prefix): family = socket.AF_INET # fixup prefix_addr, prefix_num = prefix.split('/') return family, struct.pack( ...
Returns True if the given MAC address is valid. The given MAC address should be a colon hexadecimal notation string. Samples: - valid address: aa:bb:cc:dd:ee:ff, 11:22:33:44:55:66 - invalid address: aa:bb:cc:dd, 11-22-33-44-55-66, etc. def is_valid_mac(mac): """Returns True if the given M...
Returns True if *prefix* is a valid IPv4 or IPv6 address prefix. *prefix* should be a number between 0 to *bits* length. def is_valid_ip_prefix(prefix, bits): """Returns True if *prefix* is a valid IPv4 or IPv6 address prefix. *prefix* should be a number between 0 to *bits* length. """ try: ...
Returns True if *ipv4_prefix* is a valid prefix with mask. Samples: - valid prefix: 1.1.1.0/32, 244.244.244.1/10 - invalid prefix: 255.2.2.2/2, 2.2.2/22, etc. def is_valid_ipv4_prefix(ipv4_prefix): """Returns True if *ipv4_prefix* is a valid prefix with mask. Samples: - valid pref...
Returns True if given `ipv6_prefix` is a valid IPv6 prefix. def is_valid_ipv6_prefix(ipv6_prefix): """Returns True if given `ipv6_prefix` is a valid IPv6 prefix.""" # Validate input type if not isinstance(ipv6_prefix, str): return False tokens = ipv6_prefix.split('/') if len(tokens) != 2:...
Returns True if given prefix is a string represent vpnv4 prefix. Vpnv4 prefix is made up of RD:Ipv4, where RD is represents route distinguisher and Ipv4 represents valid dot-decimal ipv4 notation string. def is_valid_vpnv4_prefix(prefix): """Returns True if given prefix is a string represent vpnv4 prefix....
Returns True if given prefix is a string represent vpnv6 prefix. Vpnv6 prefix is made up of RD:Ipv6, where RD is represents route distinguisher and Ipv6 represents valid colon hexadecimal notation string. def is_valid_vpnv6_prefix(prefix): """Returns True if given prefix is a string represent vpnv6 prefix...
Validates `label` according to MPLS label rules RFC says: This 20-bit field. A value of 0 represents the "IPv4 Explicit NULL Label". A value of 1 represents the "Router Alert Label". A value of 2 represents the "IPv6 Explicit NULL Label". A value of 3 represents the "Implicit NULL Label". V...
Returns True if the given value is a list of valid MPLS labels. def is_valid_mpls_labels(labels): """Returns True if the given value is a list of valid MPLS labels. """ if not isinstance(labels, (list, tuple)): return False for label in labels: if not is_valid_mpls_label(label): ...
Validates *attr* as string representation of RT or SOO. Returns True if *attr* is as per our convention of RT or SOO, else False. Our convention is to represent RT/SOO is a string with format: *global_admin_part:local_admin_path* def is_valid_ext_comm_attr(attr): """Validates *attr* as string represen...
Returns True if the given EVPN Ethernet SegmentEthernet ID is valid. def is_valid_esi(esi): """Returns True if the given EVPN Ethernet SegmentEthernet ID is valid.""" if isinstance(esi, numbers.Integral): return 0 <= esi <= 0xffffffffffffffffff return isinstance(esi, dict)
dissect messages from a raw stream data. disp_table[type] should be a callable for the corresponding MessageType. def get_and_dispatch_messages(self, data, disp_table): """dissect messages from a raw stream data. disp_table[type] should be a callable for the corresponding Messag...
Send a request def send_request(self, method, params): """Send a request """ msg, msgid = self._encoder.create_request(method, params) self._send_message(msg) self._pending_requests.add(msgid) return msgid
Send a response def send_response(self, msgid, error=None, result=None): """Send a response """ msg = self._encoder.create_response(msgid, error, result) self._send_message(msg)
Send a notification def send_notification(self, method, params): """Send a notification """ msg = self._encoder.create_notification(method, params) self._send_message(msg)
Try to receive some messages. Received messages are put on the internal queues. They can be retrieved using get_xxx() methods. Returns True if there's something queued for get_xxx() methods. def receive_messages(self, all=False): """Try to receive some messages. Received message...
synchronous call. send a request and wait for a response. return a result. or raise RPCError exception if the peer sends us an error. def call(self, method, params): """synchronous call. send a request and wait for a response. return a result. or raise RPCError excepti...
wait for the next incoming message. intended to be used when we have nothing to send but want to receive notifications. def receive_notification(self): """wait for the next incoming message. intended to be used when we have nothing to send but want to receive notifications. ...
Start running pre-set function every interval seconds. def start(self, interval, now=True): """Start running pre-set function every interval seconds. """ if interval < 0: raise ValueError('interval must be >= 0') if self._running: self.stop() self._runn...
Stop running scheduled function. def stop(self): """Stop running scheduled function. """ self._running = False if self._self_thread is not None: self._self_thread.cancel() self._self_thread = None
Skip the next iteration and reset timer. def reset(self): """Skip the next iteration and reset timer. """ if self._self_thread is not None: # Cancel currently scheduled call self._self_thread.cancel() self._self_thread = None # Schedule a new call ...
Returns *conf_name* settings if provided in *all_config*, else returns *default_value*. Validates *conf_name* value if provided. def compute_optional_conf(conf_name, default_value, **all_config): """Returns *conf_name* settings if provided in *all_config*, else returns *default_value*. Validate...
Encode a BFD Control packet without authentication section. def pack(self): """ Encode a BFD Control packet without authentication section. """ diag = (self.ver << 5) + self.diag flags = (self.state << 6) + self.flags length = len(self) return struct.pack(self._...
Authenticate this packet. Returns a boolean indicates whether the packet can be authenticated or not. Returns ``False`` if the Authentication Present (A) is not set in the flag of this packet. Returns ``False`` if the Authentication Section for this packet is not prese...
Parser for common part of authentication section. def parser_hdr(cls, buf): """ Parser for common part of authentication section. """ return struct.unpack_from(cls._PACK_HDR_STR, buf[:cls._PACK_HDR_STR_LEN])
Serialization function for common part of authentication section. def serialize_hdr(self): """ Serialization function for common part of authentication section. """ return struct.pack(self._PACK_HDR_STR, self.auth_type, self.auth_len)
class decorator to register msg parser def _register_parser(cls): '''class decorator to register msg parser''' assert cls.cls_msg_type is not None assert cls.cls_msg_type not in _MSG_PARSERS _MSG_PARSERS[cls.cls_msg_type] = cls.parser return cls
iterate object attributes for stringify purposes def obj_python_attrs(msg_): """iterate object attributes for stringify purposes """ # a special case for namedtuple which seems widely used in # ofp parser implementations. if hasattr(msg_, '_fields'): for k in msg_._fields: yiel...
similar to obj_python_attrs() but deals with python reserved keywords def obj_attrs(msg_): """similar to obj_python_attrs() but deals with python reserved keywords """ if isinstance(msg_, StringifyMixin): itr = msg_.stringify_attrs() else: # probably called by msg_str_attr itr ...
This method returns a JSON style dict to describe this object. The returned dict is compatible with json.dumps() and json.loads(). Suppose ClassName object inherits StringifyMixin. For an object like the following:: ClassName(Param1=100, Param2=200) this method would prod...
r"""Create an instance from a JSON style dict. Instantiate this class with parameters specified by the dict. This method takes the following arguments. .. tabularcolumns:: |l|L| =============== ===================================================== Argument Descrpition ...
Emulate jsonrpc.Connection.transact_block without blocking eventlet. def transact_block(request, connection): """Emulate jsonrpc.Connection.transact_block without blocking eventlet. """ error = connection.send(request) reply = None if error: return error, reply ovs_poller = poller.Pol...
Wrapper method for _filter_schema to filter multiple schemas. def _filter_schemas(schemas, schema_tables, exclude_table_columns): """Wrapper method for _filter_schema to filter multiple schemas.""" return [_filter_schema(s, schema_tables, exclude_table_columns) for s in schemas]
Filters a schema to only include the specified tables in the schema_tables parameter. This will also filter out any colums for included tables that reference tables that are not included in the schema_tables parameter :param schema: Schema dict to be filtered :param schema_tables: List of...
Sends Zebra message. :param msg: Instance of py:class: `ryu.lib.packet.zebra.ZebraMessage`. :return: Serialized msg if succeeded, otherwise None. def send_msg(self, msg): """ Sends Zebra message. :param msg: Instance of py:class: `ryu.lib.packet.zebra.ZebraMessage`. :r...
Peer down handler. Cleans up the paths in global tables that was received from this peer. def on_peer_down(self, peer): """Peer down handler. Cleans up the paths in global tables that was received from this peer. """ LOG.debug('Cleaning obsolete paths whose source/version: %s/...
Returns list of peers in established state. def get_peers_in_established(self): """Returns list of peers in established state.""" est_peers = [] for peer in self._peers.values(): if peer.in_established: est_peers.append(peer) return est_peers
For given `peer` re-send sent paths. Parameters: - `route-family`: (RouteFamily) of the sent paths to re-send - `peer`: (Peer) peer for which we need to re-send sent paths def resend_sent(self, route_family, peer): """For given `peer` re-send sent paths. Parameters: ...
Makes refresh request to all peers for given address family. Skips making request to peer that have valid RTC capability. def req_rr_to_non_rtc_peers(self, route_family): """Makes refresh request to all peers for given address family. Skips making request to peer that have valid RTC capabilit...
Request route-refresh for peer with `peer_ip` for given `route_families`. Will make route-refresh request for a given `route_family` only if such capability is supported and if peer is in ESTABLISHED state. Else, such requests are ignored. Raises appropriate error in other cases. If ...
Shares/communicates current best rt_nlri paths with this peers. Can be used to send initial updates after we have established session with `peer` with which RTC capability is valid. Takes into account peers RTC_AS setting and filters all RT NLRIs whose origin AS do not match this settin...
Shares/communicates current best paths with this peers. Can be used to send initial updates after we have established session with `peer`. def comm_all_best_paths(self, peer): """Shares/communicates current best paths with this peers. Can be used to send initial updates after we have ...
Communicates/enqueues given best path to be sent to all qualifying bgp peers. If this path came from iBGP peers, it is not sent to other iBGP peers. If this path has community-attribute, and if settings for recognize- well-know attributes is set, we do as per [RFC1997], and queue outgoi...
Collect all peers that qualify for sharing a path with given RTs. def _collect_peers_of_interest(self, new_best_path): """Collect all peers that qualify for sharing a path with given RTs. """ path_rts = new_best_path.get_rts() qualified_peers = set(self._peers.values()) # Filte...
Generator function going deep in tree-like structures (i.e. dicts in dicts or lists in lists etc.) and returning all elements as a flat list. It's flattening only lists and dicts which are subclasses of RdyToFlattenCollection. Regular lists and dicts are treated as a single items. :param l: some it...
Constructs prefix notification with data from given outgoing message. Given RPC session is used to create RPC notification message. def _create_prefix_notification(outgoing_msg, rpc_session): """Constructs prefix notification with data from given outgoing message. Given RPC session is used to create RPC ...
Validates give port for use as rpc server port. def _validate_rpc_port(port): """Validates give port for use as rpc server port. """ if not port: raise NetworkControllerError(desc='Invalid rpc port number.') if isinstance(port, str): port = int(port) if port <= 0: raise Net...
For every message we construct a corresponding RPC message to be sent over the given socket inside given RPC session. This function should be launched in a new green thread as it loops forever. def _process_outgoing_msg(self, sink_iter): """For every message we construct a correspondin...
Runs RPC server. Wait for peer to connect and start rpc session with it. For every connection we start and new rpc session. def _run(self, *args, **kwargs): """Runs RPC server. Wait for peer to connect and start rpc session with it. For every connection we start and new rpc se...
Starts a new RPC session with given connection. def _start_rpc_session(self, sock): """Starts a new RPC session with given connection. """ session_name = RpcSession.NAME_FMT % str(sock.getpeername()) self._stop_child_activities(session_name) rpc_session = RpcSession(sock, self)...
Returns a `Notification` message corresponding to given codes. Parameters: - `code`: (int) BGP error code - `subcode`: (int) BGP error sub-code def notification_factory(code, subcode): """Returns a `Notification` message corresponding to given codes. Parameters: - `code`: (int) BGP error code...
Compares *True* if local router id is greater when compared to peer bgp id. Should only be called after protocol has reached OpenConfirm state. def is_local_router_id_greater(self): """Compares *True* if local router id is greater when compared to peer bgp id. Should only be c...
Checks is enhanced route refresh capability is enabled/valid. Checks sent and received `Open` messages to see if this session with peer is capable of enhanced route refresh capability. def is_enhanced_rr_cap_valid(self): """Checks is enhanced route refresh capability is enabled/valid. ...
Sends open message to peer and handles received messages. Parameters: - `peer`: the peer to which this protocol instance is connected to. def _run(self, peer): """Sends open message to peer and handles received messages. Parameters: - `peer`: the peer to which this pro...
Maintains buffer of bytes received from peer and extracts bgp message from this buffer if enough data is received. Validates bgp message marker, length, type and data and constructs appropriate bgp message instance and calls handler. :Parameters: - `next_bytes`: next set of...
Utility to send notification message. Closes the socket after sending the message. :Parameters: - `socket`: (socket) - socket over which to send notification message. - `code`: (int) - BGP Notification code - `subcode`: (int) - BGP Notification sub-code ...
Validates BGP OPEN message according from application context. Parsing modules takes care of validating OPEN message that need no context. But here we validate it according to current application settings. RTC or RR/ERR are MUST capability if peer does not support either one of them we ...
When a BGP message is received, send it to peer. Open messages are validated here. Peer handler is called to handle each message except for *Open* and *Notification* message. On receiving *Notification* message we close connection with peer. def _handle_msg(self, msg): """When a BGP me...
Starts keepalive and expire timers. Hold time is set to min. of peer and configured/default hold time. Starts keep alive timer and expire timer based on this value. def _start_timers(self, peer_holdtime): """Starts keepalive and expire timers. Hold time is set to min. of peer and conf...
Hold timer expired event handler. def _expired(self): """Hold timer expired event handler. """ LOG.info('Negotiated hold time %s expired.', self._holdtime) code = BGP_ERROR_HOLD_TIMER_EXPIRED subcode = BGP_ERROR_SUB_HOLD_TIMER_EXPIRED self.send_notification(code, subcode...
Sits in tight loop collecting data received from peer and processing it. def _recv_loop(self): """Sits in tight loop collecting data received from peer and processing it. """ required_len = BGP_MIN_MSG_LEN conn_lost_reason = "Connection lost as protocol is no longer acti...
Connection to peer handler. We send bgp open message to peer and initialize related attributes. def connection_made(self): """Connection to peer handler. We send bgp open message to peer and initialize related attributes. """ assert self.state == BGP_FSM_CONNECT # We h...
Stops all timers and notifies peer that connection is lost. def connection_lost(self, reason): """Stops all timers and notifies peer that connection is lost. """ if self._peer: state = self._peer.state.bgp_state if self._is_bound or state == BGP_FSM_OPEN_SENT: ...
interval is in seconds def start(self, interval): """interval is in seconds""" if self._thread: self.cancel() self._event.clear() self._thread = hub.spawn(self._timer, interval)
Returns configured capabilities. def get_configured_capabilities(self): """Returns configured capabilities.""" capabilities = OrderedDict() mbgp_caps = [] if self.cap_mbgp_ipv4: mbgp_caps.append( BGPOptParamCapabilityMultiprotocol( RF_IPv...
Returns current RTC AS configured for current neighbors. def rtc_as_set(self): """Returns current RTC AS configured for current neighbors. """ rtc_as_set = set() for neigh in self._neighbors.values(): rtc_as_set.add(neigh.rtc_as) return rtc_as_set
Encode a packet and store the resulted bytearray in self.data. This method is legal only when encoding a packet. def serialize(self): """Encode a packet and store the resulted bytearray in self.data. This method is legal only when encoding a packet. """ self.data = bytearray(...
Returns a list of protocols that matches to the specified protocol. def get_protocols(self, protocol): """Returns a list of protocols that matches to the specified protocol. """ if isinstance(protocol, packet_base.PacketBase): protocol = protocol.__class__ assert issubclass(...
Returns the firstly found protocol that matches to the specified protocol. def get_protocol(self, protocol): """Returns the firstly found protocol that matches to the specified protocol. """ result = self.get_protocols(protocol) if len(result) > 0: return res...
add a setting of a bonding i/f. 'add' method takes the corresponding args in this order. ========= ===================================================== Attribute Description ========= ===================================================== dpid datapath id. ports ...
PacketIn event handler. when the received packet was LACP, proceed it. otherwise, send a event. def packet_in_handler(self, evt): """PacketIn event handler. when the received packet was LACP, proceed it. otherwise, send a event.""" req_pkt = packet.Packet(evt.msg.data) if slow.l...
FlowRemoved event handler. when the removed flow entry was for LACP, set the status of the slave i/f to disabled, and send a event. def flow_removed_handler(self, evt): """FlowRemoved event handler. when the removed flow entry was for LACP, set the status of the slave i/f to disabled, a...
packet-in process when the received packet is LACP. def _do_lacp(self, req_lacp, src, msg): """packet-in process when the received packet is LACP.""" datapath = msg.datapath dpid = datapath.id ofproto = datapath.ofproto parser = datapath.ofproto_parser if ofproto.OFP_VER...
create a packet including LACP. def _create_response(self, datapath, port, req): """create a packet including LACP.""" src = datapath.ports[port].hw_addr res_ether = ethernet.ethernet( slow.SLOW_PROTOCOL_MULTICAST, src, ether.ETH_TYPE_SLOW) res_lacp = self._create_lacp(datap...
create a LACP packet. def _create_lacp(self, datapath, port, req): """create a LACP packet.""" actor_system = datapath.ports[datapath.ofproto.OFPP_LOCAL].hw_addr res = slow.lacp( actor_system_priority=0xffff, actor_system=actor_system, actor_key=req.actor_key...
get whether a slave i/f at some port of some datapath is enable or not. def _get_slave_enabled(self, dpid, port): """get whether a slave i/f at some port of some datapath is enable or not.""" slave = self._get_slave(dpid, port) if slave: return slave['enabled'] ...
set whether a slave i/f at some port of some datapath is enable or not. def _set_slave_enabled(self, dpid, port, enabled): """set whether a slave i/f at some port of some datapath is enable or not.""" slave = self._get_slave(dpid, port) if slave: slave['enabled'] = e...
get the timeout time at some port of some datapath. def _get_slave_timeout(self, dpid, port): """get the timeout time at some port of some datapath.""" slave = self._get_slave(dpid, port) if slave: return slave['timeout'] else: return 0
set the timeout time at some port of some datapath. def _set_slave_timeout(self, dpid, port, timeout): """set the timeout time at some port of some datapath.""" slave = self._get_slave(dpid, port) if slave: slave['timeout'] = timeout
get slave i/f at some port of some datapath. def _get_slave(self, dpid, port): """get slave i/f at some port of some datapath.""" result = None for bond in self._bonds: if dpid in bond: if port in bond[dpid]: result = bond[dpid][port] ...
enter a flow entry for the packet from the slave i/f with idle_timeout. for OpenFlow ver1.0. def _add_flow_v1_0(self, src, port, timeout, datapath): """enter a flow entry for the packet from the slave i/f with idle_timeout. for OpenFlow ver1.0.""" ofproto = datapath.ofproto pars...
enter a flow entry for the packet from the slave i/f with idle_timeout. for OpenFlow ver1.2 and ver1.3. def _add_flow_v1_2(self, src, port, timeout, datapath): """enter a flow entry for the packet from the slave i/f with idle_timeout. for OpenFlow ver1.2 and ver1.3.""" ofproto = datapat...
Returns a selected route record matching the given filtering rules. The arguments are similar to "ip route showdump" command of iproute2. :param session: Session instance connecting to database. :param destination: Destination prefix. :param device: Source device. :param kwargs: Filtering rules to...
Adds a route record into Zebra protocol service database. The arguments are similar to "ip route add" command of iproute2. If "is_selected=True", disables the existing selected route for the given destination. :param session: Session instance connecting to database. :param destination: Destinatio...
Deletes route record(s) from Zebra protocol service database. The arguments are similar to "ip route delete" command of iproute2. :param session: Session instance connecting to database. :param destination: Destination prefix. :param kwargs: Filtering rules to query. :return: Records which are del...
Filter config parsed from a setup.cfg to inject our defaults. def setup_hook(config): """Filter config parsed from a setup.cfg to inject our defaults.""" metadata = config['metadata'] if sys.platform == 'win32': requires = metadata.get('requires_dist', '').split('\n') metadata['requires_dis...
Returns the current/latest learned path. Checks if given paths are from same source/peer and then compares their version number to determine which path is received later. If paths are from different source/peer return None. def _compare_by_version(path1, path2): """Returns the current/latest learned p...