INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
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: yield(k, getattr(msg_, k)) return base = g...
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 = obj_python_attrs(msg_) for k, v in itr: if k.endswith('_'...
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...
def to_jsondict(self, encode_string=base64.b64encode): """ 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:: ...
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 ...
def from_jsondict(cls, dict_, decode_string=base64.b64decode, **additional_args): 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| ...
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.Poller() while not error: ovs_poller.immediate_wake() ...
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...
def _filter_schema(schema, schema_tables, exclude_table_columns): """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 :p...
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`. :return: Serialized msg if succeeded, otherwise None. """ if not self.is_active: self.logger.debug( 'Cannot send message: ...
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/%s', peer.ip_address, peer.version_num) # Launch clean-up for each global ...
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: - `route-family`: (RouteFamily) of the sent paths to re-send - `peer`: (Peer) peer for which we need to re-send sent paths """ if peer not in self._peers.values(): ...
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 capability. """ assert route_family != RF_RTC_UC for peer in self._peers.values(): # First check if peer ...
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 ...
def make_route_refresh_request(self, peer_ip, *route_families): """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 ...
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...
def comm_all_rt_nlris(self, peer): """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 wh...
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 established session with `peer`. """ LOG.debug('Communicating current best path for all afi/safi except' ' 1/132') ...
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...
def comm_new_best_to_bgp_peers(self, new_best_path): """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-...
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()) # Filter out peers based on RTC_AS setting if path is for RT_NLRI ...
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...
def _flatten(l, max_level=10): """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 ...
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 notification message. """ assert outgoing_msg path = outgoing_msg.path assert path vpn_nlri = path.nlri assert pa...
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 NetworkControllerError(desc='Invalid rpc port number...
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 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. """ LOG.debug('NetworkControll...
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 session. """ apgw_rpc_bind_ip = _validate_rpc_ip(kwargs.pop(NC_RPC_BIND_IP)) apgw_rpc_bind_port = _validate_rpc_port(kwa...
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) self._spawn_activity(rpc_session)
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 - `subcode`: (int) BGP error sub-code """ notification = BGPNotification(code, subcode) if not notification.reason: raise ValueError(...
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 called after protocol has reached OpenConfirm state. """ from ryu.services.protocols.bgp.utils.bgp import from_inet_ptoi if not self.state...
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. Checks sent and received `Open` messages to see if this session with peer is capable of enhanced route refresh capability. """ if not self.recv_open_msg: raise ValueE...
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 protocol instance is connected to. """ # We know the peer we are connected to, we send open message. self._peer = peer self.connect...
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...
def _data_received(self, next_bytes): """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. :Pa...
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 ...
def send_notification(self, code, subcode): """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 ...
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 ...
def _validate_open_msg(self, open_msg): """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 p...
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 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. """ ...
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 configured/default hold time. Starts keep alive timer and expire timer based on this value. """ neg_timer = min(self._holdtime, peer_holdtime) if neg_timer...
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) self.connection_lost('Neg...
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 active" try: while True: next_bytes = self._socket...
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 have a connection with peer we send open message. open_msg = self._peer.create_open_msg() s...
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: self._peer.connection_lost(reason) self._...
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_IPv4_UC.afi, RF_IPv4_UC.safi)) ...
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() r = self.protocols[::-1] for i, p in enumerate(r): if isinstance(p, packet_base.PacketBase): ...
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(protocol, packet_base.PacketBase) return [p for p in self.pro...
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 result[0] return None
add a setting of a bonding i/f. 'add' method takes the corresponding args in this order. ========= ===================================================== Attribute Description ========= ===================================================== dpid datapath id. ports ...
def add(self, dpid, ports): """add a setting of a bonding i/f. 'add' method takes the corresponding args in this order. ========= ===================================================== Attribute Description ========= ===================================================== d...
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.lacp in req_pkt: (req_lacp, ) = req_pkt.get_protocols(slow.lacp) (req_eth, ) = req...
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, and send a event.""" msg = evt.msg datapath = msg.datapath ofproto = datapath.ofproto dpid = datapath.id ...
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_VERSION == ofproto_v1_0.OFP_VERSION: port = ...
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(datapath, port, req) res_pkt =...
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, actor_por...
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'] else: return False
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'] = enabled
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] break return result
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 parser = datapath.ofproto_parser match = parser.OFPMatch( in_port=port, dl_src=addrco...
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 = datapath.ofproto parser = datapath.ofproto_parser match = parser.OFPMatch( in_port=port, et...
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...
def ip_route_show(session, destination, device, **kwargs): """ 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. ...
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...
def ip_route_add(session, destination, device=None, gateway='', source='', ifindex=0, route_type=zebra.ZEBRA_ROUTE_KERNEL, is_selected=True): """ Adds a route record into Zebra protocol service database. The arguments are similar to "ip route add" command of iproute2. ...
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...
def ip_route_delete(session, destination, **kwargs): """ 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 kwa...
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_dist'] = "\n".join(requires) config['metadata'] = metadata ...
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 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. """ if path1.source == path2....
Compares given paths and returns best path. Parameters: -`local_asn`: asn of local bgpspeaker -`path1`: first path to compare -`path2`: second path to compare Best path processing will involve following steps: 1. Select a path with a reachable next hop. 2. Select the path wit...
def compute_best_path(local_asn, path1, path2): """Compares given paths and returns best path. Parameters: -`local_asn`: asn of local bgpspeaker -`path1`: first path to compare -`path2`: second path to compare Best path processing will involve following steps: 1. Select a path...
Selects a path with highest local-preference. Unlike the weight attribute, which is only relevant to the local router, local preference is an attribute that routers exchange in the same AS. Highest local-pref is preferred. If we cannot decide, we return None.
def _cmp_by_local_pref(path1, path2): """Selects a path with highest local-preference. Unlike the weight attribute, which is only relevant to the local router, local preference is an attribute that routers exchange in the same AS. Highest local-pref is preferred. If we cannot decide, we return None...
Select locally originating path as best path. Locally originating routes are network routes, redistributed routes, or aggregated routes. For now we are going to prefer routes received through a Flexinet-Peer as locally originating route compared to routes received from a BGP peer. Returns None if g...
def _cmp_by_local_origin(path1, path2): """Select locally originating path as best path. Locally originating routes are network routes, redistributed routes, or aggregated routes. For now we are going to prefer routes received through a Flexinet-Peer as locally originating route compared to routes ...
Calculated the best-paths by comparing as-path lengths. Shortest as-path length is preferred. If both path have same lengths, we return None.
def _cmp_by_aspath(path1, path2): """Calculated the best-paths by comparing as-path lengths. Shortest as-path length is preferred. If both path have same lengths, we return None. """ as_path1 = path1.get_pattr(BGP_ATTR_TYPE_AS_PATH) as_path2 = path2.get_pattr(BGP_ATTR_TYPE_AS_PATH) assert a...
Select the best path based on origin attribute. IGP is preferred over EGP; EGP is preferred over Incomplete. If both paths have same origin, we return None.
def _cmp_by_origin(path1, path2): """Select the best path based on origin attribute. IGP is preferred over EGP; EGP is preferred over Incomplete. If both paths have same origin, we return None. """ def get_origin_pref(origin): if origin.value == BGP_ATTR_ORIGIN_IGP: return 3 ...
Select the path based with lowest MED value. If both paths have same MED, return None. By default, a route that arrives with no MED value is treated as if it had a MED of 0, the most preferred value. RFC says lower MED is preferred over higher MED value.
def _cmp_by_med(path1, path2): """Select the path based with lowest MED value. If both paths have same MED, return None. By default, a route that arrives with no MED value is treated as if it had a MED of 0, the most preferred value. RFC says lower MED is preferred over higher MED value. """ ...
Select the path based on source (iBGP/eBGP) peer. eBGP path is preferred over iBGP. If both paths are from same kind of peers, return None.
def _cmp_by_asn(local_asn, path1, path2): """Select the path based on source (iBGP/eBGP) peer. eBGP path is preferred over iBGP. If both paths are from same kind of peers, return None. """ def get_path_source_asn(path): asn = None if path.source is None: asn = local_asn ...
Select the route received from the peer with the lowest BGP router ID. If both paths are eBGP paths, then we do not do any tie breaking, i.e we do not pick best-path based on this criteria. RFC: http://tools.ietf.org/html/rfc5004 We pick best path between two iBGP paths as usual.
def _cmp_by_router_id(local_asn, path1, path2): """Select the route received from the peer with the lowest BGP router ID. If both paths are eBGP paths, then we do not do any tie breaking, i.e we do not pick best-path based on this criteria. RFC: http://tools.ietf.org/html/rfc5004 We pick best path ...
Selects the route received from the peer with the shorter CLUSTER_LIST length. [RFC4456] The CLUSTER_LIST length is evaluated as zero if a route does not carry the CLUSTER_LIST attribute.
def _cmp_by_cluster_list(path1, path2): """Selects the route received from the peer with the shorter CLUSTER_LIST length. [RFC4456] The CLUSTER_LIST length is evaluated as zero if a route does not carry the CLUSTER_LIST attribute. """ def _get_cluster_list_len(path): c_list = path.get_p...
Enqueues given destination for processing. Given instance should be a valid destination.
def enqueue(self, destination): """Enqueues given destination for processing. Given instance should be a valid destination. """ if not destination: raise BgpProcessorError('Invalid destination %s.' % destination) dest_queue = self._dest_queue # RtDest are qu...
Utility to log given stats to *stats* logger. Stats to log are given by `stats_source` and in its absence we log `kwargs`. *stats* logger is configured independently from any logger. Only stats should be logged to this logger. Will add current timestamp to the logged stats if not given. Parameters...
def log(stats_resource=None, stats_source=None, log_level=DEFAULT_LOG_LEVEL, **kwargs): """Utility to log given stats to *stats* logger. Stats to log are given by `stats_source` and in its absence we log `kwargs`. *stats* logger is configured independently from any logger. Only stats should be ...
This method registers a new neighbor. The BGP speaker tries to establish a bgp session with the peer (accepts a connection from the peer and also tries to connect to it). ``address`` specifies the IP address of the peer. It must be the string representation of an IP address. Only IPv4 i...
def neighbor_add(self, address, remote_as, remote_port=DEFAULT_BGP_PORT, enable_ipv4=DEFAULT_CAP_MBGP_IPV4, enable_ipv6=DEFAULT_CAP_MBGP_IPV6, enable_vpnv4=DEFAULT_CAP_MBGP_VPNV4, enable_vpnv6=DEFAULT_CAP_MBGP_VPNV6...
This method changes the neighbor configuration. ``address`` specifies the IP address of the peer. ``conf_type`` specifies configuration type which you want to change. Currently ryu.services.protocols.bgp.bgpspeaker.MULTI_EXIT_DISC can be specified. ``conf_value`` specifies val...
def neighbor_update(self, address, conf_type, conf_value): """ This method changes the neighbor configuration. ``address`` specifies the IP address of the peer. ``conf_type`` specifies configuration type which you want to change. Currently ryu.services.protocols.bgp.bgpspeaker.MULTI_EX...
This method deletes a advertised prefix. ``prefix`` must be the string representation of an IP network. ``route_dist`` specifies a route distinguisher value.
def prefix_del(self, prefix, route_dist=None): """ This method deletes a advertised prefix. ``prefix`` must be the string representation of an IP network. ``route_dist`` specifies a route distinguisher value. """ func_name = 'network.del' networks = { PREFIX...
Request the application to be automatically loaded. If this is used for "api" style modules, which is imported by a client application, set api_style=True. If this is used for client application module, set api_style=False.
def require_app(app_name, api_style=False): """ Request the application to be automatically loaded. If this is used for "api" style modules, which is imported by a client application, set api_style=True. If this is used for client application module, set api_style=False. """ iterable = (in...
set_port_config <peer> <target> <port> <key> <value> eg. set_port_config sw1 running LogicalSwitch7-Port2 admin-state down eg. set_port_config sw1 running LogicalSwitch7-Port2 no-forward false
def do_set_port_config(self, line): """set_port_config <peer> <target> <port> <key> <value> eg. set_port_config sw1 running LogicalSwitch7-Port2 admin-state down eg. set_port_config sw1 running LogicalSwitch7-Port2 no-forward false """ def f(p, args): try: ...
This method adds a new vrf used for VPN. ``route_dist`` specifies a route distinguisher value. ``import_rts`` specifies a list of route targets to be imported. ``export_rts`` specifies a list of route targets to be exported. ``site_of_origins`` specifies site_of_origin values. ...
def vrf_add(self, route_dist, import_rts, export_rts, site_of_origins=None, route_family=RF_VPN_V4, multi_exit_disc=None): """ This method adds a new vrf used for VPN. ``route_dist`` specifies a route distinguisher value. ``import_rts`` specifies a list of route targets to be i...
This method sets attribute mapping to a neighbor. attribute mapping can be used when you want to apply attribute to BGPUpdate under specific conditions. ``address`` specifies the IP address of the neighbor ``attribute_maps`` specifies attribute_map list that are used before pat...
def attribute_map_set(self, address, attribute_maps, route_dist=None, route_family=RF_VPN_V4): """This method sets attribute mapping to a neighbor. attribute mapping can be used when you want to apply attribute to BGPUpdate under specific conditions. ``address`...
Adds EVPN route from VRF identified by *route_dist*.
def add_evpn_local(route_type, route_dist, next_hop, **kwargs): """Adds EVPN route from VRF identified by *route_dist*. """ if(route_type in [EVPN_ETH_AUTO_DISCOVERY, EVPN_ETH_SEGMENT] and kwargs['esi'] == 0): raise ConfigValueError(conf_name=EVPN_ESI, conf_val...
get_logical_switch_config <peer> <source> <logical switch>
def do_get_logical_switch_config(self, line): """get_logical_switch_config <peer> <source> <logical switch> """ def f(p, args): try: source, lsw = args except: print("argument error") return o = p.get_config(sou...
raw_get <peer>
def do_raw_get(self, line): """raw_get <peer> """ def f(p, args): result = p.raw_get() tree = ET.fromstring(result) validate(tree) print(et_tostring_pp(tree)) self._request(line, f)
get_config <peer> <source> eg. get_config sw1 startup
def do_get_config(self, line): """get_config <peer> <source> eg. get_config sw1 startup """ def f(p, args): try: source = args[0] except: print("argument error") return print(p.get_config(source)) ...
BFD packet receiver.
def recv(self, bfd_pkt): """ BFD packet receiver. """ LOG.debug("[BFD][%s][RECV] BFD Control received: %s", hex(self._local_discr), six.binary_type(bfd_pkt)) self._remote_discr = bfd_pkt.my_discr self._remote_state = bfd_pkt.state self._remote_de...
Parse ARP packet, return ARP class from packet library.
def arp_parse(data): """ Parse ARP packet, return ARP class from packet library. """ # Iteratize pkt pkt = packet.Packet(data) i = iter(pkt) eth_pkt = next(i) # Ensure it's an ethernet frame. assert isinstance(eth_pkt, ethernet.ethernet) a...
This method gets in-bound filters of the specified neighbor. ``address`` specifies the IP address of the neighbor. Returns a list object containing an instance of Filter sub-class
def in_filter_get(self, address): """This method gets in-bound filters of the specified neighbor. ``address`` specifies the IP address of the neighbor. Returns a list object containing an instance of Filter sub-class """ func_name = 'neighbor.in_filter.get' param = { ...
Wrapper for socket.create_connection() function. If *address* (a 2-tuple ``(host, port)``) contains a valid IPv4/v6 address, passes *address* to socket.create_connection(). If *host* is valid path to Unix Domain socket, tries to connect to the server listening on the given socket. :param address: ...
def create_connection(address): """ Wrapper for socket.create_connection() function. If *address* (a 2-tuple ``(host, port)``) contains a valid IPv4/v6 address, passes *address* to socket.create_connection(). If *host* is valid path to Unix Domain socket, tries to connect to the server listenin...
Send the specified event to the RyuApp instance specified by name.
def send_event(self, name, ev, state=None): """ Send the specified event to the RyuApp instance specified by name. """ if name in SERVICE_BRICKS: if isinstance(ev, EventRequestBase): ev.src = self.name LOG.debug("EVENT %s->%s %s", ...
list_port <peer>
def do_list_port(self, line): """list_port <peer> """ def f(p, args): o = p.get() for p in o.resources.port: print('%s %s %s' % (p.resource_id, p.name, p.number)) self._request(line, f)
commit <peer> eg. commit sw1
def do_commit(self, line): """commit <peer> eg. commit sw1 """ def f(p, args): print(p.commit()) self._request(line, f)
This method returns the state of peer(s) in a json format. ``address`` specifies the address of a peer. If not given, the state of all the peers return. ``format`` specifies the format of the response. This parameter must be one of the following. - 'json' (default) ...
def neighbor_state_get(self, address=None, format='json'): """ This method returns the state of peer(s) in a json format. ``address`` specifies the address of a peer. If not given, the state of all the peers return. ``format`` specifies the format of the response. This ...
delete_config <peer> <source> eg. delete_config sw1 startup
def do_delete_config(self, line): """delete_config <peer> <source> eg. delete_config sw1 startup """ def f(p, args): try: source = args[0] except: print("argument error") return print(p.delete_config(sou...
list_cap <peer>
def do_list_cap(self, line): """list_cap <peer> """ def f(p, args): for i in p.netconf.server_capabilities: print(i) self._request(line, f)
Sends ZEBRA_IPV4/v6_ROUTE_ADD message to Zebra daemon. :param prefix: IPv4/v6 Prefix to advertise. :param nexthops: List of nexthop addresses. :param safi: SAFI to advertise. :param flags: Message flags to advertise. See "ZEBRA_FLAG_*". :param distance: (Optional) Distance to ad...
def send_ip_route_add( self, prefix, nexthops=None, safi=packet_safi.UNICAST, flags=zebra.ZEBRA_FLAG_INTERNAL, distance=None, metric=None, mtu=None, tag=None): """ Sends ZEBRA_IPV4/v6_ROUTE_ADD message to Zebra daemon. :param prefix: IPv4/v6 Prefix to adverti...
This method registers a new BMP (BGP monitoring Protocol) server. The BGP speaker starts to send BMP messages to the server. Currently, only one BMP server can be registered. ``address`` specifies the IP address of a BMP server. ``port`` specifies the listen port number of a BMP server...
def bmp_server_add(self, address, port): """This method registers a new BMP (BGP monitoring Protocol) server. The BGP speaker starts to send BMP messages to the server. Currently, only one BMP server can be registered. ``address`` specifies the IP address of a BMP server. ``por...
This method unregister the registered BMP server. ``address`` specifies the IP address of a BMP server. ``port`` specifies the listen port number of a BMP server.
def bmp_server_del(self, address, port): """ This method unregister the registered BMP server. ``address`` specifies the IP address of a BMP server. ``port`` specifies the listen port number of a BMP server. """ func_name = 'bmp.stop' param = { 'host': addr...
Returns neighbor configuration for given neighbor ip address. Raises exception if no neighbor with `neigh_ip_address` exists.
def _get_neighbor_conf(neigh_ip_address): """Returns neighbor configuration for given neighbor ip address. Raises exception if no neighbor with `neigh_ip_address` exists. """ neigh_conf = \ CORE_MANAGER.neighbors_conf.get_neighbor_conf(neigh_ip_address) if not neigh_conf: raise Runt...
send a QUERY message periodically.
def _send_query(self): """ send a QUERY message periodically.""" timeout = 60 ofproto = self._datapath.ofproto parser = self._datapath.ofproto_parser if ofproto_v1_0.OFP_VERSION == ofproto.OFP_VERSION: send_port = ofproto.OFPP_NONE else: send_port ...
PacketIn event handler. when the received packet was IGMP, proceed it. otherwise, send a event.
def packet_in_handler(self, evt): """PacketIn event handler. when the received packet was IGMP, proceed it. otherwise, send a event.""" msg = evt.msg dpid = msg.datapath.id req_pkt = packet.Packet(msg.data) req_igmp = req_pkt.get_protocol(igmp.igmp) if req_igmp: ...