class InterfaceStatus(object): """ Class which handles provides information about status of the interface @ivar interface_name: The name of the interface @type interface_name: C{str} @ivar link: The link status of the interface. @type link: L{InterfaceState<interfaces.InterfaceStatus.InterfaceStatus.InterfaceState>} @ivar lineproto: The lineproto state of the interface. @type lineproto: L{InterfaceState<interfaces.InterfaceStatus.InterfaceStatus.InterfaceState>} """ InterfaceStateEventType = enum('ONEP_IF_STATE_EVENT_LINK', 'ONEP_IF_STATE_EVENT_LINEPROTO', 'ONEP_IF_STATE_EVENT_ANY') InterfaceState = enum(ONEP_IF_STATE_ADMIN_DOWN=1, ONEP_IF_STATE_OPER_DOWN=2, ONEP_IF_STATE_OPER_UP=3) InterfaceVLANEventType = enum('ONEP_IF_VLAN_EVENT_ADD', 'ONEP_IF_VLAN_EVENT_DELETE', 'ONEP_IF_VLAN_EVENT_ANY') InterfaceVRFEventType = enum('ONEP_IF_VRF_EVENT_LINEPROTO', 'ONEP_IF_VRF_EVENT_LINK') interface_name = None link = InterfaceState.ONEP_IF_STATE_ADMIN_DOWN lineproto = InterfaceState.ONEP_IF_STATE_ADMIN_DOWN def __init__(self, link, lineproto, interface_name): """ Constructor of InterfaceStatus class. """ self.link = link self.lineproto = lineproto self.interface_name = interface_name def __str__(self): """ Obtain string representation of the Interface Status object. """ sb = '' sb += '\nInterfaceStatus [ ' + self.interface_name + ' ]\n' sb += '\tLinkState : ' + str( self.InterfaceState.enumval(self.link)) + '\n' sb += '\tLineProtoState : ' + str( self.InterfaceState.enumval(self.lineproto)) + '\n' return sb
class RouteOperation(object): """ This abstract class is the parent class of L3UnicastRouteOperation and in the future for L3MulticastRouteOperation, L2UnicastRouteOperation, L2MulticastRouteOperation, etc. This class represents the operation to be performed on a route. """ _op_type = int() RouteOperationType = enum('ADD', 'REMOVE', 'REPLACE') def __init__(self, opType): """ Constructor @param opType: The operation type. @type opType: L{Enum<onep.core.util.Enum>} """ super(RouteOperation, self).__init__() self._op_type = opType def _get_op_type(self): return self._op_type _doc = 'The operation type.\n @type: L{Enum<onep.core.util.Enum>}\n ' op_type = property(_get_op_type, None, None, _doc)
class Route(object): """ This abstract class is the parent class of L3UnicastRoute and in the future for L3MulticastRoute, L2UnicastRoute, L2MulticastRoute, etc. All common fields among these derived class will be defined in this class. """ RouteErrorCode = enum('NONE', 'SUCCESS', 'PARTIAL_SUCCESS', 'EAGAIN', 'FAILURE', 'MAX')
class ServiceSetDescription(object): """ ServiceSetDescription defines a collection of service sets that are grouped as an integral unit to provide a collection of services on a network element. A service set collection is a logical grouping of ONE-P network services providing modular access to a set of network functionality. The ServiceSetDescription class provides information about the service set name and the version and the network element on which this service set is available. See L{discover_service_set_list<onep.element.NetworkElement.discover_service_set_list>} """ ServiceSetName = enum('ONEP_SERVICE_SET_ALL', 'ONEP_BASE_SERVICE_SET', 'ONEP_LISP_SERVICE_SET', 'ONEP_VTY_SERVICE_SET', 'ONEP_ONEFW_SERVICE_SET', 'ONEP_MEDIATRACE_SERVICE_SET', 'ONEP_DATAPATH_SERVICE_SET', 'ONEP_ADVRTG_SERVICE_SET') _network_element = None _service_set_list = dict() def __init__(self, networkElement = None, serviceSetList = None): """ Constructor @param networkElement: @type networkElement: L{NetworkElement<onep.element.NetworkElement>} @paramserviceSetlist: """ if networkElement == None and serviceSetList == None: self.__init___0() else: self._network_element = networkElement self._service_set_list = serviceSetList def __init___0(self): pass def _get_network_element(self): return self._network_element _doc = '\n Gets the network element.\n \n @type: L{NetworkElement<onep.element.NetworkElement>}\n ' network_element = property(_get_network_element, None, None, _doc) def _get_service_set_list(self): return self._service_set_list _doc = '\n Gets the HashMap containing the service name and the versions. The HashMap \n key is the service name as defined in ServiceSetName and the HashMap value \n is the array of available service set versions. Because a particular \n service set can have multiple versions, the value associated with each \n key is an array of strings.\n \n @return: The C{dict} containing the service name and the array of available \n versions.\n @rtype: C{dict} \n ' service_set_list = property(_get_service_set_list, None, None, _doc)
class RouteRange(object): """ This abstract class is the parent class of L3UnicastRouteRange and in the future for L3MulticastRouteRange, L2UnicastRouteRange, L2MulticastRouteRange, etc. All common fields among these derived class will be defined in this class. """ RangeType = enum('EQUAL_OR_LARGER', 'LARGER') _start_prefix = None _range_type = int() _count = long()
class Server(object): """ Server class describes the AAA Server that is used for user authentication. Each server is characterized by its IP Address and the AAA protocol. """ OnepAAAProtocol = enum('ONEP_AAA_PROTOCOL_RADIUS', 'ONEP_AAA_PROTOCOL_TACACSPLUS', 'ONEP_AAA_PROTOCOL_LOCAL') def __init__(self, address, protocol): """AAA server constructor, used internally""" self.address = address self.protocol = protocol
class AsyncMsg(object): """ This abstract class is meant to be implemented by a any class acting as a event object. """ def __init__(self, element, msgType): """ Constructor for AsyncMsg class. Keyword argument: eventHandle Event ID is a unique ID to identify which event listener should receive the event . type Event type, for example OnepConstants.EVENT_TYPE_SYSLOG represent a syslog event type. """ self.src_ne = element self.msg_type = msgType def do_event(self, source): """ This method must be implemented by substantial class to specify what action to do when a event is processed in the event queue. Typically an action would be invoking client's event listener. Keyword argument: source The source of the event. For example, the source of a syslog event would be a NetworkElement object. """ pass OnepAsyncMsgType = enum('ONEP_ASYNC_MESSAGE_TYPE_APICALL', 'ONEP_ASYNC_MESSAGE_TYPE_EVENT')
class OnepConstants(object): OK = 0 FAIL = 1 ONEP_PORT = 15001 ONEP_TLS_PORT = 15002 DEFAULT_QUEUE_SIZE = 100 DEFAULT_N_THREADS = 1 SESSION_RECONNECT_LIMIT = 300 MAX_USERNAME_LEN = 64 MAX_PASSWORD_LEN = 25 UNKNOWN_STATE = 0 DISCONNECTED_STATE = 1 CONNECTING_STATE = 2 CONNECTED_STATE = 3 EVENT_TYPE_CONNECTION = 0 EVENT_TYPE_APPLICATION = 1 EVENT_TYPE_CLI = 2 EVENT_TYPE_CDP = 3 EVENT_TYPE_SYSLOG = 4 EVENT_TYPE_CONFIG_NOTIFICATION = 5 EVENT_TYPE_DEBUG_FLAG = 6 EVENT_TYPE_SHOW_DATA = 7 EVENT_TYPE_DISCOVERY = 8 EVENT_TYPE_INTERFACE_STATE = 9 EVENT_TYPE_INTERFACE_STATISTICS = 10 EVENT_TYPE_OIR = 11 EVENT_TYPE_IF_ADDRCHANGE = 12 EVENT_TYPE_LOCATION_CHANGE = 13 EVENT_TYPE_VTY = 14 EVENT_TYPE_TOPOLOGY = 15 EVENT_TYPE_RIB_STATE = 16 EVENT_TYPE_ART_STATE = 17 EVENT_TYPE_VRF = 18 EVENT_TYPE_VLAN = 19 EVENT_TYPE_INTERFACE_STATISTICS_POLL = 20 EVENT_TYPE_UPDATE_ROUTE = 21 EVENT_TYPE_ROUTING_SERVICE_SATUS = 22 EVENT_TYPE_REPLAY_ROUTE = 23 INTERFACE_DESCRIPTION_SIZE = 200 MAC_ADDRESS_SIZE = 6 ERR_BAD_ARGUMENT = OnepStatus.ONEP_ERR_BAD_ARGUMENT ERR_CONNECT_FAIL = OnepStatus.ONEP_ERR_CONNECT_FAIL ERR_EVENT_CHANNEL = OnepStatus.ONEP_ERR_EVENT_CHANNEL ERR_NO_DATA = OnepStatus.ONEP_ERR_NO_DATA ERR_DUPLICATE = OnepStatus.ONEP_ERR_DUPLICATE ERR_EVENTQ_FULL = OnepStatus.ONEP_EOK_EVENTQ_FULL SERIAL_VERSION_UID = 1L EVENT_MAX_OCCURS = 32 EVENT_MIN_PRIORITY = 0 EVENT_MAX_PRIORITY = 8 OnepOperatorType = enum('ONEP_OP_NONE', 'ONEP_OP_GT', 'ONEP_OP_GE', 'ONEP_OP_EQ', 'ONEP_OP_NE', 'ONEP_OP_LT', 'ONEP_OP_LE') OnepCombinationType = enum('ONEP_COMBINATION_NONE', 'ONEP_COMBINATION_OR', 'ONEP_COMBINATION_AND') OnepAddressFamilyType = enum('ONEP_AF_ANY', 'ONEP_AF_INET', 'ONEP_AF_INET6', 'ONEP_AF_MAX') OnepAddressScopeType = enum( 'ONEP_ADDRESS_IPv4_PRIMARY', 'ONEP_ADDRESS_IPv4_SECONDARY', 'ONEP_ADDRESS_IPv4_ALL', 'ONEP_ADDRESS_IPv6_LINK_LOCAL', 'ONEP_ADDRESS_IPv6_EUI64', 'ONEP_ADDRESS_IPv6_GLOBAL_ANYCAST', 'ONEP_ADDRESS_IPv6_GLOBAL', 'ONEP_ADDRESS_IPv6_ALL') OnepBandwidthUnits = enum('ONEP_BW_UNITS_KBPS', 'ONEP_BW_UNITS_PERCENT') OnepQueueSizeUnits = enum('ONEP_QUEUE_UNITS_PKTS', 'ONEP_QUEUE_UNITS_BYTES', 'ONEP_QUEUE_UNITS_MSEC') OnepDscp = enum(ONEP_DSCP_DEFAULT=0, ONEP_DSCP_AF11=10, ONEP_DSCP_AF12=12, ONEP_DSCP_AF13=14, ONEP_DSCP_AF21=18, ONEP_DSCP_AF22=20, ONEP_DSCP_AF23=22, ONEP_DSCP_AF31=26, ONEP_DSCP_AF32=28, ONEP_DSCP_AF33=30, ONEP_DSCP_AF41=34, ONEP_DSCP_AF42=36, ONEP_DSCP_AF43=38, ONEP_DSCP_CS1=8, ONEP_DSCP_CS2=16, ONEP_DSCP_CS3=24, ONEP_DSCP_CS4=32, ONEP_DSCP_CS5=40, ONEP_DSCP_CS6=48, ONEP_DSCP_CS7=56, ONEP_DSCP_EF=46) OnepSyslogLevel = enum(EMERGENCY=0, ALERT=1, CRITICAL=2, ERROR=3, WARNING=4, NOTICE=5, INFO=6, DEBUG=7) OnepSyslogFacility = enum('LOCAL0', 'LOCAL1', 'LOCAL2', 'LOCAL3', 'LOCAL4', 'LOCAL5', 'LOCAL6', 'LOCAL7') OnepProtocol = enum(UDP=1, TCP=2, ICMP=3) OnepSnmpSecurityModel = enum(V1=1, V2C=2, USM=3) OnepSnmpSecurityLevel = enum(NOAUTH_NOPRIV=1, AUTH_NOPRIV=2, AUTH_PRIV=3, UNKNOWN=4) OnepUserKeyEncrtption = enum('UNKNOWN', 'UNENCRYPTED', 'SHA256', 'MD5') OnepSnmpTrap = enum(SNMP=1, SYSLOG=18, ENTITY=21, IPSEC=55) OnepEulaState = enum(ONEP_EULA_ACCEPTED=0, ONEP_EULA_NOT_ACCEPTED=1, ONEP_EULA_NOT_APPLICABLE=2) PasswordEncrypt = enum(UNENCRYPTED=0, SHA256=4, MD5=5, HIDDEN=7) VlanState = enum('NONE', 'ACTIVE', 'SUSPEND', 'NOT_CONFIG') AclProtocol = enum(ICMP=1, IGMP=2, TCP=6, EGP=8, IGRP=9, UDP=17, RSVP=46, GRE=47, ESP=50, AH=51, ALL=256)
raise OnepVtyNotClosed('Vty Service must be closed to set idle timeout') try: self.api_client.ExecutionCmd_setIdleTimeoutIDL(self.element.session_handle._id, int(timeout)) except ExceptionIDL as e: raise OnepRemoteProcedureException(e) except TException as e: raise OnepConnectionException(e.message, e) def destroy(self): """ Done with VtyService instance so destroy it Throws OnepVtyNotClosed if VTY service is still open """ if self.is_open(): raise OnepVtyNotClosed('Vty Service must be closed before destroy') self.api_client.ExecutionCmd_destroyIDL(self.element.session_handle._id, self.exec_handle) VtyService.OnepVtyState = enum('ONEP_VTY_STATE_DISCONNECTED', 'ONEP_VTY_STATE_CONNECTING', 'ONEP_VTY_STATE_CONNECTED', 'ONEP_VTY_STATE_IDLE_TIMEOUT', 'ONEP_VTY_STATE_INVALID') VtyService.OnepVtyCmdInterp = enum('ONEP_VTY_CMD_IOS_SH', 'ONEP_VTY_CMD_TCL') VtyService.OnepVtyOutputFormat = enum('ONEP_VTY_OUTPUT_FORMAT_TLV', 'ONEP_VTY_OUTPUT_FORMAT_TEXT', 'ONEP_VTY_OUTPUT_FORMAT_XML') VtyService.log = None # decompiled 1 files: 1 okay, 0 failed, 0 verify failed # 2015.02.05 17:20:29 IST
class Node(object): """ Node class represents topology node discovered via a protocol by connecting to a NetworkElement. A Node object can contain the identity of a network node like hostname, IP address etc, depending how the node was discovered. For example, if the node is discovered via CDP, then the Node object contains hostname, IP address; if the node is discovered through OSPF or any other L3 routing protocol, then the Node object contains only the IP address. """ NodeType = enum('CDP_NODE', 'MEDIA_TRACE_NODE', 'INVALID_NODE_TYPE') _name = None _type = None _address_list = None def __init__(self, name, type, address_list): """ @raise OnepIllegalArgumentException: The exception is thrown when address received in the address list is None or invalid. """ validate(name, str) if isValidEnum(self.NodeType, type) is False: raise OnepIllegalArgumentException('type is invalid.') validate(address_list, list) for addr in address_list: validate(addr, str) self._name = name self._type = type self._address_list = address_list self.mt_node = None def _get_name(self): return self._name _doc = '\n Get the hostname of the Node object\n\n The administratively-assigned name of a node when the node was\n discovered. The host name of the nodes are available only if\n the nodes are discovered by CDP. If they are logical nodes\n discovered through routing protocols then the method returns null.\n\n @type: C{str}\n ' name = property(_get_name, None, _doc) def _get_type(self): return self._type _doc = '\n Get the node type that Node object is created with.\n ' type = property(_get_type, None, _doc) def _get_address_list(self): return self._address_list _doc = '\n Get IP addresses associated with the Node object. A topology node can\n contain multiple IP address when nodes are correlated\n but for CDP this would be only one which denotes the management IP address.\n ' address_list = property(_get_address_list, None, _doc) @staticmethod def _from_idl(node_idl, node_type): if node_idl is None or node_type is None: return node_name = node_idl.hostname addr_list = list() na_list = node_idl.addrlist if na_list != None: for na in na_list: inet_addr = NetworkInterface._convert_to_inetaddress(na) if inet_addr != None: addr_list.append(inet_addr) return Node(node_name, node_type, addr_list) @staticmethod def _from_out_idl(node_out_idl, node_type): """ Convert TopologyNodeOutIDL to Node object This method for internal use only @param node_out_idl: TopologyNodeOutIDL object @param node_type: NodeType node type @return: Node object """ if node_out_idl == None or node_type == None: return node_name = node_out_idl.hostname addr_list = list() na_list = node_out_idl.addrlist if na_list != None: for na in na_list: inet_addr = NetworkInterface._convert_to_inetaddress(na) if inet_addr != None: addr_list.append(inet_addr) return Node(node_name, node_type, addr_list) def equals(self, obj): """ Compare two nodes for equality. This method returns true if the two topology nodes are equal and the same. For CDP nodes the hostname and the management IP address of the node are compared. @param obj: The other Node object to compare with. @return: Returns true if the two topology nodes are equal and the same. """ if obj == None: return False if not isinstance(obj, Node): return False if self._type != obj.type: return False if self._name != obj.name: return False if Counter(self._address_list) != Counter(obj.address_list): return False return True def __str__(self): mgmt = '' if self._address_list != None and len( self._address_list) != 0 and self._address_list[0] != None: mgmt = self._address_list[0] return 'Node[' + self._name + ',' + mgmt + ',' + Node.NodeType.enumval( self._type) + ']'
def do_event(self, source): """ This method specifies what action to do when a event is processed in the event queue. For Vty Event, the action is invoking client's event listener. Keyword argument: source -- The source of the event. For Vty Event, the source in an instance of NetworkElement. """ if source == None: return logging.debug('VtyData.do_event: exec_handle = ' + str(self.exec_handle) + ' data = ' + self.data) ne = source targetListener = ne.event_manager.get_vty_event_listener( self.exec_handle) if targetListener != None: targetListener.handleEvent( self, ne.event_manager.get_vty_event_listener_client_data( self.exec_handle)) VtyData.OnepVtyMsgType = enum('ONEP_VTY_MSG_DATA', 'ONEP_VTY_MSG_STATE', 'ONE_VTY_MSG_ERROR') # decompiled 1 files: 1 okay, 0 failed, 0 verify failed # 2015.02.05 17:20:30 IST
class Routing(object): """ Routing class represents the entry point of Routing Service.To access the Routing Service API, the application instantiates a Routing object that's associated with a NetworkElement. Warning: This Sample Code Has Not Been Verified Example: def example() : # Get the network element and connect to it. ne = element.NetworkElement.NetworkElement("10.1.1.4","dolph") handle = ne.connect("cisco", "cisco") # Get a Routing instance that's associated with the network element. routing = Routing.get_instance(ne) # Get RIB information and print the list of layer 3 unicast routes. rib = routing.rib scope = L3UnicastScope("", AFIType.IPV4, SAFIType.UNICAST, "") prefix = None filter = L3UnicastRIBFilter() range = L3UnicastRouteRange( prefix, RouteRange.RangeType.EQUAL_OR_LARGER, 10) routeList = rib.get_route_list(scope, filter, range) for route in routeList : if (isinstance (route,L3UnicastRoute) : print route # Add a listener to receive route state change events. # When events arrive, listener.handleEvent() will be invoked. listener = MyRouteListener() eventHandle = rib.add_route_state_listener( listener, scope, filter, RIB.TRIGER_INITIAL_WALK, None) # Get the instance of AppRouteTable in Routing object. art = routing.get_app_route_table() # Create a new route and change its administrative distance # to make it more trusted. scope = L3UnicastScope("", AFIType.IPV4, SAFIType.UNICAST, "") destNetwork = NetworkPrefix("192.168.200.0", 24) # Wrong address for the interface, see what happen. nextHop = L3UnicastNextHop( ne.get_interface_by_name("Ethernet1/0"), "192.168.99.77", scope) nextHopList = set() nextHopList.add(nextHop) aRoute = L3UnicastRoute(destNetwork, nextHopList) aRoute.admin_distance = 1 # Now update the app route table with this route. op = L3UnicastRouteOperation(RouteOperationType.REPLACE, aRoute); opList = list() opList.append(op); resultList = art.update_routes(scope, opList); # Implement a RIBRouteStateListener. class MyRouteListener (RIBRouteStateListener) : def handleEvent(event, clientData) : print "Scope: " + event.scope print "Route: " + event.route Warning: This Sample Code Has Not Been Verified """ RoutingServiceType = enum('RIB', 'ART', 'ALL') _network_element = None _app_route_table = None static_route_table = None _routing_instance_map = dict() _routing_client = None _rib = None def __init__(self, networkElement): """ Constructor. For internal use only. @param networkElement: The target network element which routing service is associate with.. @type networkElement: L{NetworkElement<onep.element.NetworkElement>} @raise OnepConnectionException: The exception is thrown when the network element is not connectted. """ super(Routing, self).__init__() if not networkElement.is_connected(): self._routing_client = None raise OnepConnectionException() self._network_element = networkElement self._rib = RIB(self) self._app_route_table = AppRouteTable(self) self.static_route_table = StaticRouteTable(self) if self._routing_client == None: self._routing_client = RoutingIDL.Client( networkElement.api_protocol) if self._routing_client == None: raise OnepConnectionException( 'Unable to create Routing client instance') self.log = logging.getLogger('onep.' + __name__) @staticmethod def get_instance(networkElement): """ Create a Routing instance based on the provided NetworkElement. This static method follows factory pattern to guarantee only one instance of Routing will be created for each NetworkElement. @param networkElement: The network element which the Routing instance is associate with.. @type networkElement: L{NetworkElement<onep.element.NetworkElement>} @raise OnepConnectionException: The exception is thrown when the network element is not connected. """ if networkElement == None or not networkElement.is_connected(): raise OnepConnectionException() if not networkElement.routing: networkElement.routing = Routing(networkElement) return networkElement.routing def _get_network_element(self): return self._network_element _doc = '\n Gets the NetworkElement object where this Routing instance belongs to\n @type : L{NetworkElement<onep.element.NetworkElement}\n ' network_element = property(_get_network_element, None, None, _doc) def _get_rib(self): return self._rib _doc = '\n Gets the RIB object in this Routing service\n @type: L{RIB<onep.routing.RIB>}\n ' rib = property(_get_rib, None, None, _doc) def _get_app_route_table(self): return self._app_route_table _doc = '\n Gets the AppRouteTable object in this Routing service.\n @type: L{AppRouteTable<onep.routing.AppRouteTable>}\n ' app_route_table = property(_get_app_route_table, None, None, _doc) def add_service_status_listener(self, listener, client_data): """ Adds a routing service status listener. @param listener: The RoutingServiceStatusListener object that handles the events. @type listener: L{RoutingServiceStatusListener<onep.routing.RoutingServiceStatusListener>} @param client_data: The client data associated with the listener. This client data will be part of input parameters when the handleEvent method in the listener is invoked. @return event_handle: a numeric ID associated with this event registration. The eventHandle is used to unregister the listener using the remove listener method. If registration fails, -1 is returned. @rtype: C{int} @raise OnepIllegalArgumentException: The exception is thrown when scope, filter or range is invalid @raise OnepConnectionException: The exception is thrown when connection to the network element has failed. @raise OnepRemoteProcedureException: The exception is thrown when an error has occurred in the remote procedure call made to a network element @raise OnepException: This occurs when an internal exception occurs """ if listener == None: raise OnepIllegalArgumentException('listener', 'null') try: event_prop = self._routing_client.RoutingServiceStatusEvent_registerIDL( self._network_element.session_handle._id) if event_prop != None: self._network_element.event_manager.add_listener( event_prop.eventHandle, listener, client_data) self.log.debug( 'Registered Service status listener with event handle : ' + str(event_prop.eventHandle)) return event_prop.eventHandle raise OnepException( 'Internal error while registering the Listener') except ExceptionIDL as e: raise OnepRemoteProcedureException(e) except TException as e: raise OnepConnectionException(e) def remove_service_status_listener(self, event_handle): """ Removes the RoutingServiceStatusListener listener object. This method will remove the listener associated with the specified eventHandle and also remove the corresponding registered event on the route table. @param eventHandle: Registered event identifier. @type eventHandle: C{int} @raise OnepIllegalArgumentException: The exception is thrown when eventHandle is not valid or is unregistered already. @raise OnepRemoteProcedureException: The exception is thrown when an error has occurred in the remote procedure call made to a network element @raise OnepConnectionException: The exception is thrown when connection to a network element has failed. """ self._parent_rss.network_element.event_manager.remove_listener( event_handle)
sb += '\tSerial No : ' + str(self.idl.serialNo) + '\n' try: sb += '\tsysName : ' + self.sys_name + '\n' sb += '\tsysUpTime : ' + str(self._get_sys_uptime()) + '\n' except Exception as e: sb += '\tsysName :\n' sb += '\tsysUpTime :\n' sb += '\tsysDescr : ' + str(self.idl.sysDescr) + '\n' return sb content_string = property(_get_content_string) def __str__(self): sb = '' addr = '' if self.element != None: addr = self.element.host_address if addr == None: addr = '' sb += 'ElementProperty [ ' + addr + ' ]\n' sb += self.content_string return sb ElementProperty.OnepElementHwType = enum('ONEP_ELEMENT_HW_BASE_ETHER', 'ONEP_ELEMENT_HW_FAST_ETHER', 'ONEP_ELEMENT_HW_GIGA_ETHER') # decompiled 1 files: 1 okay, 0 failed, 0 verify failed # 2015.02.05 17:21:11 IST
class AppRouteTable(object): """ This class represents an application route table. It provides application the ability to add, remove and replace route from the application route table. The following services are provided: Add, replace and remove route from the application route table.Get notification when the added application route is promoted or demoted in the RIB. Depending on platform, the application route table could do extra check before adding the route to the RIB. For example, route may be added to the RIB when the next hop is resolvable. Once the application accept and return success for the operation, the application is responsible to keep the state of the routes consistent across HA switchover. The route added will not be visible in the configuration. But the added route would be visible in routing related show commands. The show output will be able to tell which application added the route. The added route are redistributable. If a listener is registered, the application route table will provide notification when an application route gets promoted or demoted in the RIB. Currently, only add/delete/update route operations are supported. @undocumented: __init__ """ RouteState = enum('PROMOTE', 'DEMOTE') TRIGER_INITIAL_WALK = 1 _parent_rss = None _async_queue_size = 100 def __init__(self, parentRSS): """ Constructor. For internal use only """ self._parent_rss = parentRSS self.log = logging.getLogger(__name__) def update_routes(self, scope, opList): """ Update a route. It is a synchronous API. It is used to add, delete and replace single route in the Application Route Table. The type of operation is indicated by RouteOperationType parameter. For route addition: If the route do not exist, create route with the provided next hops. If the route already exist in the table, any new next hop specified is added to the route. Duplicated next hop is ignored. For route replace: If the route do not exist, it act like route addition operation. If the route already exist in the table, the all the old next hops are removed and new next hops specified are added to the route. For route deletion: Next hop specified will be removed. If no next hop is specified, then all next hops are removed. The route will be removed when no more next hops exist. Return error if the scope and route is not consistent. This method will make remote procedure call and response time may be long. @param scope: Indicate which table in the Application Route Table to send the route operation too. @type scope: L{L3UnicastScope<onep.routing.L3UnicastScope>} @param opList: The list of route operation. If API succeeds, per route per next hop status are returned and could be accessed using Route.error_code and NextHop.eror_code @type opList: C{list} of L{L3UnicastRouteOperation<onep.routing.L3UnicastRouteOperation>} @return: A list of the route operation. This list is a copy of the routes in the input parameter, with error code for each route added. @rtype: C{list} of L{L3UnicastRouteOperation<onep.routing.L3UnicastRouteOperation>} @raise OnepIllegalArgumentException: This exception is thrown if the scope and route are not consistent @raise OnepConnectionException: The exception is thrown when connection to the network element has failed. @raise OnepRemoteProcedureException: The exception is thrown when an error has occurred in the remote procedure call made to a network element """ if opList == None or len(opList) == 0: return scopeIdl = None if isinstance(scope, L3UnicastScope): scopeIdl = scope._to_idl() if scopeIdl == None: raise OnepIllegalArgumentException('scope', 'invalid') opListIdl = list() for rop in opList: if rop != None and isinstance(rop, (L3UnicastRouteOperation, )): opListIdl.append(rop._to_idl()) try: opIdlList = self._parent_rss._routing_client.Routing_L3UcastARTUpdateRoutesIDL( self._parent_rss.network_element.session_handle._id, scopeIdl, opListIdl) self.log.info('Returning from Routing_L3UcastARTUpdateRoutesIDL') opListOut = list() for opIdl in opIdlList: if opIdl != None: opListOut.append( L3UnicastRouteOperation( opIdl.opType, L3UnicastRoute._from_idl( opIdl.route, self._parent_rss.network_element), True)) return opListOut except ExceptionIDL as e: raise OnepRemoteProcedureException(e) except TException as e: raise OnepConnectionException(e) def async_update_routes(self, scope, op_list, listener, client_data): """ Asynchronously update a route. It is an asynchronous API that will return immediately and the application provided listener will be invoked when the all the route update requests are processed by the network element. It is used to add, delete and replace single route in the Application Route Table. The type of operation is indicated by RouteOperationType parameter. For route addition: If the route do not exist, create route with the provided next hops. If the route already exist in the table, any new next hop specified is added to the route Duplicated next hop is ignored. For route replace: If the route do not exist, it act like route addition operation. If the route already exist in the table, the all the old next hops are removed and new next hops specified are added to the route. If no next hop is specified, then all next hops are removed. The route will be removed when no more next hops exist. Return error if the scope and route is not consistent. This method will make remote procedure call and response time may be long. @param scope: Indicate which table in the Application Route Table to send the route operation too. @type scope: L{Scope<onep.routing.Scope>} @param op_list: The list of route operation. If API succeeds, per route per next hop status are returned and could be accessed using Route.error_code and NextHop.error_code @type op_list: C{list} of L{L3UnicastRouteOperation<onep.routing.L3UnicastRouteOperation>} @param listener: The UpdateRouteResponseListener object that handles the events. @type listener: L{UpdateRouteResponseListener<onep.routing.UpdateRouteResponse>} @param client_data: The client data associated with the listener. This client data will be part of input parameters when the handleEvent method in the listener is invoked. @return: An identifier for this asynchronous update request. Could be used to monitor the status or cancel the request. @rtype: C{int} @raise OnepIllegalArgumentException: This exception is thrown if the scope and route are not consistent @raise OnepConnectionException: The exception is thrown when connection to the network element has failed. @raise OnepRemoteProcedureException: The exception is thrown when an error has occurred in the remote procedure call made to a network element """ if op_list == None or len(op_list) == 0: raise OnepIllegalArgumentException('opList', 'empty') scope_idl = None if isinstance(scope, L3UnicastScope): scope_idl = scope._to_idl() if scope_idl == None: raise OnepIllegalArgumentException('scope', 'Invalid') op_list_idl = list() for rop in op_list: if rop != None and isinstance(rop, L3UnicastRouteOperation): op_list_idl.append(rop._to_idl()) try: event_prop = self._parent_rss._routing_client.Routing_L3UcastARTUpdateRoutesAsyncIDL( self._parent_rss.network_element.session_handle._id, scope_idl, op_list_idl) self.log.debug( 'Done calling Routing_L3UcastARTUpdateRoutesAsyncIDL') if event_prop != None: self._parent_rss.network_element.event_manager.add_listener( event_prop.eventHandle, listener, client_data) self.log.debug( 'Registered UpdateResponseListener with handle' + str(event_prop.eventHandle)) self._parent_rss.network_element.event_manager.register_dedicated_queue( event_prop.eventHandle, self._async_queue_size) return event_prop.eventHandle raise OnepException( 'Internal error while registering the Listener') except ExceptionIDL as e: raise OnepRemoteProcedureException(e) except TException as e: raise OnepConnectionException(e) def add_route_state_listener(self, routeStateListener, scope, flags, clientData): """ Adds a route state listener to the ART object. @param routeStateListener: The RouteStateListener object that handles the events. @type routeStateListener: L{ARTRouteStateListener<onep.routing.ARTRouteStateListener>} @param scope: Indicate which table in the Application Route Table get notification from. @type scope: L{L3UnicastScope<onep.routing.L3UnicastScope>} @param flags: Additional flags to be passed to listener. This argument is reserved for future use and ignored at present. @type flags: C{int} @param clientData: The client data associated with the listener. This client data will be part of input parameters when the handleEvent method in the listener is invoked. @return: EventHandle, a numeric ID associated with this event registration. The eventHandle is used to unregister the listener using the remove_route_state_listener method If registration fails, -1 is returned. @rtype: C{int} @raise OnepIllegalArgumentException: The exception is thrown when the listener or other parameters is not valid. @raise OnepConnectionException: The exception is thrown when connection to a network element has failed. @raise OnepRemoteProcedureException: The exception is thrown when an error has occurred in the remote procedure call made to a network element """ if routeStateListener == None: raise OnepIllegalArgumentException('routeStateListener', 'null') scopeIdl = None if isinstance(scope, (L3UnicastScope, )): scopeIdl = scope._to_idl() if scopeIdl == None: raise OnepIllegalArgumentException('scope', 'invalid') try: eventProp = self._parent_rss._routing_client.L3UcastARTEvent_registerIDL( self._parent_rss.network_element.session_handle._id, scopeIdl) self.log.info('Returning from L3UcastARTEvent_registerIDL ') if eventProp != None: self._parent_rss.network_element.event_manager.add_listener( eventProp.eventHandle, routeStateListener, clientData) self.log.debug( 'Registered ARTRouteStateListener listener, eventHandle=' + str(eventProp.eventHandle)) return eventProp.eventHandle raise OnepException( 'Internal error while registering the Listener') except ExceptionIDL as e: raise OnepRemoteProcedureException(e) except TException as e: raise OnepConnectionException(e) def remove_route_state_listener(self, eventHandle): """ Removes the RouteStateListener listener object. This method will remove the listener associated with the specified eventHandle and also remove the corresponding registered event on the route table. @param eventHandle: Registered event identifier. @type eventHandle: C{int} @raise OnepIllegalArgumentException: The exception is thrown when eventHandle is not valid or is unregistered already. @raise OnepRemoteProcedureException: The exception is thrown when an error has occurred in the remote procedure call made to a network element @raise OnepConnectionException: The exception is thrown when connection to a network element has failed. """ self._parent_rss.network_element.event_manager.remove_listener( eventHandle) def add_replay_route_event_listener(self, listener, scope, client_data): """ Adds a replay route event listener to the RIB object. @param listener: The ReplayRouteEventListener object that handles the events. @type listener: L{ReplayRouteEventListener<onep.routing.ReplayRouteEventListener>} @param scope: Indicate which table in the Application Route Table get notification from. @type scope: L{L3UnicastScope<onep.routing.L3UnicastScope>} @param client_data: The client data associated with the listener. This client data will be part of input parameters when the handleEvent method in the listener is invoked. @return: EventHandle, a numeric ID associated with this event registration. The eventHandle is used to unregister the listener using the remove_route_state_listener method If registration fails, -1 is returned. @rtype: C{int} @raise OnepIllegalArgumentException: The exception is thrown when the listener or other parameters is not valid. @raise OnepConnectionException: The exception is thrown when connection to a network element has failed. @raise OnepRemoteProcedureException: The exception is thrown when an error has occurred in the remote procedure call made to a network element """ if listener == None: raise OnepIllegalArgumentException('ReplayRouteEventListener', 'null') scopeIdl = None if isinstance(scope, (L3UnicastScope, )): scopeIdl = scope._to_idl() if scopeIdl == None: raise OnepIllegalArgumentException('scope', 'invalid') try: eventProp = self._parent_rss._routing_client.RoutingReplayRouteEvent_registerIDL( self._parent_rss.network_element.session_handle._id, scopeIdl) self.log.info( 'Returning from RoutingReplayRouteEvent_registerIDL ') if eventProp != None: self._parent_rss.network_element.event_manager.add_listener( eventProp.eventHandle, listener, client_data) self.log.debug( 'Registered ReplayRouteEventListener listener, eventHandle=' + str(eventProp.eventHandle)) return eventProp.eventHandle raise OnepException( 'Internal error while registering the Listener') except ExceptionIDL as e: raise OnepRemoteProcedureException(e) except TException as e: raise OnepConnectionException(e) def remove_replay_route_event_listener(self, eventHandle): """ Removes the ReplayRouteEventListener listener object. This method will remove the listener associated with the specified eventHandle and also remove the corresponding registered event on the route table. @param eventHandle: Registered event identifier. @type eventHandle: C{int} @raise OnepIllegalArgumentException: The exception is thrown when eventHandle is not valid or is unregistered already. @raise OnepRemoteProcedureException: The exception is thrown when an error has occurred in the remote procedure call made to a network element @raise OnepConnectionException: The exception is thrown when connection to a network element has failed. """ self._parent_rss.network_element.event_manager.remove_listener( eventHandle)
# # * ------------------------------------------------------------------ # * __init__.py # * # * Sept. 2013, Michael Ott # * # * Copyright (c) 2010-2014 by cisco Systems, Inc. # * All rights reserved. # * ------------------------------------------------------------------ # from onep.policy import Acl from onep.policy.L3Acl import L3Acl from onep.policy.L3Ace import L3Ace from onep.policy.L2Acl import L2Acl from onep.policy.L2Ace import L2Ace from onep.core.exception.OnepIllegalArgumentException import OnepIllegalArgumentException from onep.core.exception.OnepRemoteProcedureException import OnepRemoteProcedureException from onep.core.exception.OnepConnectionException import OnepConnectionException from onep.core.util.Enum import enum AclType = enum('ONEP_ACL_L2', 'ONEP_ACL_L3') AclFilter = enum('ONEP_ACL_FILTER_ANY', 'ONEP_ACL_FILTER_L2', 'ONEP_ACL_FILTER_L3')
class L3UnicastScope(Scope): AFIType = enum('UNKNOWN', 'IPV4', 'IPV6') SAFIType = enum('UNKNOWN', 'UNICAST', 'MULTICAST') _afi = None _safi = None _topology = None def __init__0(self): super(L3UnicastScope, self).__init__() self._vrf = '' self._afi = self.AFIType.IPV4 self._safi = self.SAFIType.UNICAST self._topology = '' def __init__(self, vrf=None, afi=None, safi=None, topology=None): """ Constructor @param vrf: Name of the VRF. An empty string means default VRF. If the input is None, it will be interpreted as empty string. @type vrf: C{str} @param afi: The address family. See AFIType for allowed value. If this parameter is None, default is IPV4. @type afi : C{int} @param safi: The subsequence address family. See SAFIType for allowed value. If this parameter is None, default is UNICAST. @type safi : C{int} @param topology : Name of the topology. An empty string means the default topology. If the input is None, it will be interpreted as empty string. @type topology: C{str} @raise OnepIllegalArgumentException : The exception is thrown if vrf is invalid. """ if vrf == None and afi == None and safi == None and topology == None: self.__init__0() else: self.__init__1(vrf, afi, safi, topology) self.log = logging.getLogger('onep.' + __name__) def __init__1(self, vrf, afi, safi, topology): super(L3UnicastScope, self).__init__() if vrf is not None and not isinstance(vrf, str): raise OnepIllegalArgumentException('vrf', 'invalid') if vrf is None: self._vrf = '' else: self._vrf = vrf if afi == None: self._afi = self.AFIType.IPV4 elif not isinstance(afi, int): raise OnepIllegalArgumentException('afi', 'invalid') if afi < self.AFIType.UNKNOWN or afi > self.AFIType.IPV6: raise OnepIllegalArgumentException('afi', 'invalid') self._afi = afi if safi == None: self._safi = self.SAFIType.UNICAST elif not isinstance(safi, int): raise OnepIllegalArgumentException('safi', 'invalid') if safi < self.SAFIType.UNKNOWN or safi > self.SAFIType.MULTICAST: raise OnepIllegalArgumentException('safi', 'invalid') self._safi = safi if topology is None: self._topology = '' else: self._topology = topology def _get_afi(self): return self._afi def _set_afi(self, afi): if afi == None: self._afi = self.AFIType.IPV4 elif not isinstance(afi, int): raise OnepIllegalArgumentException if afi < self.AFIType.UNKNOWN or afi > self.AFIType.IPV6: raise OnepIllegalArgumentException self._afi = afi _doc = '\n The address family to set.\n If this parameter is null, default is IPV4\n @type: C{int}\n @raise OnepIllegalArgumentException: If afi is invalid\n ' afi = property(_get_afi, _set_afi, None, _doc) def _get_safi(self): return self._safi def _set_safi(self, safi): if safi == None: self._safi = self.SAFIType.UNICAST elif not isinstance(safi, int): raise OnepIllegalArgumentException if safi < self.SAFIType.UNKNOWN or safi > self.SAFIType.MULTICAST: raise OnepIllegalArgumentException self._safi = safi _doc = '\n Sets the subsequence address family.\n If this parameter is null, default is UNICAST.\n \n @type: C{int}\n @raise OnepIllegalArgumentException: If SAFI is invalid\n ' safi = property(_get_safi, _set_safi, None, _doc) def _get_topology_name(self): return self._topology def _set_topology_name(self, topology): self._topology = '' if topology == None else topology _doc = '\n Sets name of the topology. None means the default topology.\n An empty string means the default topology.\n \n @type: C{str}\n ' topology = property(_get_topology_name, _set_topology_name, None, _doc) def __str__(self): """ Returns a string representation of the L3UnicastScope object. @return: a string representation of the object """ return 'Scope[vrf:' + self.vrf + ',' + 'afi:' + str( self.AFIType.enumval(self.afi)) + ',' + 'safi:' + str( self.SAFIType.enumval( self.safi)) + ',' + 'topology:' + self.topology + ']' def _to_idl(self): self.log.info('Calling L3UcastScopeIDL') return ttypes.L3UcastScopeIDL(self._afi, self._safi, self._topology, self._vrf) @staticmethod def _from_idl(scopeIdl): try: return L3UnicastScope(scopeIdl.vrfName, scopeIdl.afi, scopeIdl.safi, scopeIdl.topoName) except OnepIllegalArgumentException: return None
class Edge(object): """ Edge class represents a path as seen by a protocol from one interface (head) on a node to an interface (tail) on another node. """ EdgeType = enum('DIRECTED', 'UNDIRECTED') _head_node = None _tail_node = None _head_node_connector = None _tail_node_connector = None def __init__(self, head_node, head_node_connector, tail_node, tail_node_connector): """ @raise OnepIllegalArgumentException: The exception is thrown when one or more of the input arguments is invalid. """ validate_none(head_node, 'head_node') validate_none(head_node_connector, 'head_node_connector') validate_none(tail_node, 'tail_node') validate_none(tail_node_connector, 'tail_node_connector') validate(head_node, Node) validate(head_node_connector, NodeConnector) validate(tail_node, Node) validate(tail_node_connector, NodeConnector) self._head_node = head_node self._tail_node = tail_node self._head_node_connector = head_node_connector self._tail_node_connector = tail_node_connector def _get_head_node(self): return self._head_node _doc = ' Get the head node of this instance of head\n @return: Head node object\n @rtype: L{Node<src.topology.Node>}\n ' head_node = property(_get_head_node, None, _doc) def _get_head_node_connector(self): return self._head_node_connector _doc = 'Get the head node connector\n @return: The head NodeConnector object.\n ' head_node_connector = property(_get_head_node_connector, None, _doc) def _get_tail_node(self): return self._tail_node _doc = ' Get the tail Node of this instance of Edge.\n\n @return: The tail Node object.\n ' tail_node = property(_get_tail_node, None, _doc) def _get_tail_node_connector(self): return self._tail_node_connector _doc = ' Get the tail NodeCnnector of this instance of Edge.\n\n @return: The tail NodeConnector object.\n ' tail_node_connector = property(_get_tail_node_connector, None, _doc) @staticmethod def _from_idl(edge_idl, node_type, conn_type): """ Convert TopologyEdgeIDL to Edge object. This method is for internal use only. @param edge_idl: EdgeIdl object @param node_type: NodeType object @param conn_type: NodeConnector type @return: Edge object """ head_node = Node._from_idl(edge_idl.headnode, node_type) tail_node = Node._from_idl(edge_idl.tailnode, node_type) head_conn = NodeConnector._from_idl(edge_idl.headconn, conn_type, head_node) tail_conn = NodeConnector._from_idl(edge_idl.tailconn, conn_type, tail_node) return Edge(head_node, head_conn, tail_node, tail_conn) @staticmethod def _from_out_idl(edge_idl, node_type, conn_type): """ Convert TopologyEdgeOutIDL to Edge object. This method is for internal use only. @param edge_idl: EdgeIdl object @param node_type: NodeType object @param conn_type: NodeConnector type @return: Edge object """ head_node = Node._from_out_idl(edge_idl.headnode, node_type) tail_node = Node._from_out_idl(edge_idl.tailnode, node_type) head_conn = NodeConnector._from_out_idl(edge_idl.headconn, conn_type, head_node) tail_conn = NodeConnector._from_out_idl(edge_idl.tailconn, conn_type, tail_node) return Edge(head_node, head_conn, tail_node, tail_conn) def equals(self, obj): """ Compare two Edge object for equality. This method returns true if the two Edge are equal and the same. @param obj: The other Edge object to compare with. @type obj: C{Object} @return: True if the edge are equal or the same @rtype: C{boolean} """ if obj == None: return False if not isinstance(obj, Edge): return False if self._head_node.equals(obj.head_node) is False: return False if self._tail_node.equals(obj.tail_node) is False: return False if self._head_node_connector.equals(obj.head_node_connector) is False: return False if self._tail_node_connector.equals(obj.tail_node_connector) is False: return False return True def __str__(self): return 'Edge[' + str(self._head_node) + ',' + str( self._head_node_connector) + ',' + str( self._tail_node) + ',' + str(self._tail_node_connector) + ']'
class RIB(object): """RIB class represents service provided by RIB (Routing Information Base). """ RouteState = enum('UP', 'DOWN', 'UNKNOWN') TRIGER_INITIAL_WALK = 1 _parent_rss = None def __init__(self, parent_rss): """ Constructor for RIB """ self._parent_rss = parent_rss self.log = logging.getLogger('onep.' + __name__) def get_route_list(self, scope, filter, range): """ Gets the RIB routes from the network element for the specified scope, filter and range. This method will make remote procedure call and response time may be long. Only routes which satisfy the filter and range are retrieved. This method may not return all the number of routes as specified in the range count per invocation. The platform controls the maximum number of routes returned per invocation. To retrieve all the routes matching the criteria, the application may have to call the method multiple times, adjusting the start prefix and the type in the range argument accordingly, until a list of size 0 is returned. Also, to prevent connection timeout when getting a long list of routes, application should increase the timeout by calling the following method before connecting to a network element #NetworkApplicaiton.set_default_socket_timeout(300) @param scope: Indicates which table in the RIB to retrieve route from. @type scope: L{L3unicastScope<onep.routing.L3unicastScope>} @param filter: Specifies characteristic of a route must match for it to be retrieved. Use default filter (instantiated with default constructor) if no filtering is needed.the same as if a filter with all default values passed in. @type filter: L{L3UnicastRIBFilter<onep.routing.L3UnicastRIBFilter>} @param range: Specifies range of route to be retrieved. Use default range (instantiated with default constructor) if no range matching is needed. @type range: L{L3UnicastRouteRange<onep.routing.L3UnicastRouteRange>} """ scope_idl = None if isinstance(scope, L3UnicastScope): scope_idl = scope._to_idl() if scope_idl == None: raise OnepIllegalArgumentException('scope', 'invalid') filter_idl = None if isinstance(filter, L3UnicastRIBFilter): filter_idl = filter._to_idl() if filter_idl == None: raise OnepIllegalArgumentException('filter', 'invalid') range_idl = None if isinstance(range, L3UnicastRouteRange): range_idl = range._to_idl() if range_idl == None: raise OnepIllegalArgumentException('range', 'invalid') try: route_idl_list = self._parent_rss._routing_client.Routing_L3UcastGetRibRouteListIDL( self._parent_rss.network_element.session_handle._id, scope_idl, filter_idl, range_idl) if route_idl_list == None or len(route_idl_list) == 0: print 'route list is null' return list() else: route_list = list() for route_idl in route_idl_list: if route_idl != None: route_list.append( L3UnicastRoute._from_idl( route_idl, self._parent_rss.network_element)) return route_list except ExceptionIDL as e: if e.code == OnepConstants.ERR_NO_DATA: return list() raise OnepRemoteProcedureException(e) except TException as e: raise OnepConnectionException(e) def add_route_state_listener(self, route_state_listener, scope, filter, flag, client_data): """ Adds a route state listener to the RIB object. @param route_state_listener: The RouteStateListener object that handles the events. @type route_state_listener: L{RIBRouteStateListener<onep.routing.RIBRouteStateListener>} @param scope: Indicates which table in the RIB to retrieve route from. @type scope: L{L3UnicastScope<onep.routing.L3UnicastScope>} @param filter: Specifies characteristic of a route must match for it to be retrieved @type filter: L{L3UnicastRIBFilter<onep.routing.L3UnicastRIBFilter>} @param client_data: The client data associated with the listener. This client data will be part of input parameters when the handleEvent method in the listener is invoked. @type client_data: C{str} @param flag: Additional request when the listener is installed. If TRIGER_INITIAL_WALK is set, triggers an initial walk of the RIB and reports an UP event to the application for each route that matches rib_filter. The TRIGER_INITIAL_WALK flag is supported only on network elements that run IOS Classic or IOS-XE. On IOS-XR and NXOS, TRIGER_INITIAL_WALK is ignored; an initial walk is always performed. @type flag : C{int} @return: EventHandle, a numeric ID associated with this event registration. The eventHandle is used to unregister the listener using the removeRouteStateListener method. If registration fails, -1 is returned. @rtype: C{int} @raise OnepIllegalArgumentException: The exception is thrown when scope, filter or range is invalid @raise OnepConnectionException: The exception is thrown when connection to the network element has failed. @raise OnepRemoteProcedureException: The exception is thrown when an error has occurred in the remote procedure call made to a network element @raise OnepException: The exception is thrown when an internal error occurs """ if route_state_listener == None: raise OnepIllegalArgumentException('routeStateListener', 'null') if not isinstance(route_state_listener, RIBRouteStateListener): OnepIllegalArgumentException('routeStateListener', 'invalid') scope_idl = None if isinstance(scope, (L3UnicastScope, )): scope_idl = scope._to_idl() if scope_idl == None: raise OnepIllegalArgumentException('scope', 'invalid') filter_idl = None if isinstance(filter, (L3UnicastRIBFilter, )): if scope.afi == L3UnicastScope.AFIType.IPV6 and filter.subnet.address == '0.0.0.0' and filter.subnet.prefix_length == 0: filter.subnet = NetworkPrefix('0::0', 0) filter_idl = filter._to_idl() if filter_idl == None: raise OnepIllegalArgumentException('filter', 'invalid') try: event_prop = self._parent_rss._routing_client.L3UcastRibRouteEvent_registerIDL( self._parent_rss.network_element.session_handle._id, scope_idl, filter_idl, flag) if event_prop != None: self._parent_rss.network_element.event_manager.add_listener( event_prop.eventHandle, route_state_listener, client_data) self.log.debug( 'Registered RIBRoute listener with event handle : ' + str(event_prop.eventHandle)) return event_prop.eventHandle raise OnepException( 'Internal error while registering the Listener') except ExceptionIDL as e: raise OnepRemoteProcedureException(e) except TException as e: raise OnepConnectionException(e) def remove_route_state_listener(self, eventHandle): """Removes the RouteStateListener listener object. This method will remove the listener associated with the specified eventHandle and also remove the corresponding registered event on the RIB. @param eventHandle: Registered event identifier @type eventHandle: C{int} @raise OnepIllegalArgumentException: The exception is thrown when eventHandle is not valid or is unregistered already. @raise OnepRemoteProcedureException: The exception is thrown when an error has occurred in the remote procedure call made to a network element @raise OnepConnectionException: The exception is thrown when connection to a network element has failed. """ self._parent_rss.network_element.event_manager.remove_listener( eventHandle)
class NodeConnector: """ NodeConnector class represents the logical/physical interfaces forming an edge in a topology graph. NodeConnectorc contains identity of a network interface including interface name, IP address, etc. depending on how the interface was discovered. If the interface is discovered through CDP(physical) then it is represented by a CDP instantiated node connector object. If the interface is discovered through OSPF or any other L3 routing protocol, then it is a OSPF instantiated node connector object and contains only IP address. @undocumented: __init__ """ NodeConnectorType = enum('ONEP_CDP_CONNECTOR', 'ONEP_INVALID_CONNECTOR_TYPE') _node = None _name = None _type = None _address_list = None def __init__(self, name, type, node, address_list): """ Constructor For internal use only @raise OnepIllegalArgumentException: The exception is thrown if any of the input argument is invalid. """ validate(name, str) if isValidEnum(self.NodeConnectorType, type) is False: raise OnepIllegalArgumentException('type is invalid.') if not isinstance(node, Node): raise OnepIllegalArgumentException('node is invalid.') validate(address_list, list) for addr in address_list: validate(addr, str) self._node = node self._name = name self._type = type self._address_list = address_list def _get_name(self): return self._name _doc = '\n Get the name of the NodeConnector. This is applicable only if\n the connector is discovered through protocols such as CDP.\n\n @type: C{str}\n ' name = property(_get_name, None, _doc) def _get_node(self): return self._node _doc = 'Get the node that the NodeConnector object is associated with.\n\n @type: L{Node<src.topology.Node>}\n ' node = property(_get_node, None, _doc) def _get_address_list(self): return self._address_list _doc = 'Get IP addresses associated with the NodeConnector object.\n\n @type: C{list} of C{str}\n ' address_list = property(_get_address_list, None, _doc) def _get_type(self): return self._type _doc = '\n Get the node type that NodeConnector object is created with.\n ' type = property(_get_type, None, _doc) @staticmethod def _from_idl(connector_idl, connector_type, node): """ Convert a TopologyConnectorIDL object to NodeConnector. This method is for internal use only. @param connector_idl: TopologyConnectorIDL object. @param connector_type: ConnectorType object @param node: associated node @return: A NodeConnector object """ if connector_idl == None or connector_type == None: return node_name = connector_idl.connname addr_list = [] na_list = connector_idl.addrlist if na_list != None: for na in na_list: inet_addr = NetworkInterface._convert_to_inetaddress(na) if inet_addr != None: addr_list.append(inet_addr) return NodeConnector(node_name, connector_type, node, addr_list) @staticmethod def _from_out_idl(connector_idl, connector_type, node): """ Convert a TopologyConnectorOutIDL object to NodeConnector. This method is for internal use only. @param connector_idl: TopologyConnectorOutIDL object. @param connector_type: NodeConnector type @param node: The associated node. @return: A NodeConnector object """ if connector_idl == None or connector_type == None: return node_name = connector_idl.connname addr_list = [] na_list = connector_idl.addrlist if na_list != None: for na in na_list: inet_addr = None inet_addr = na.addr if inet_addr != None: addr_list.append(inet_addr) return NodeConnector(node_name, connector_type, node, addr_list) def equals(self, obj): """ Compare two NodeConnector for equality. This method returns true if the two NodeConnector are equal and the same. The connectors are equal only when the nodes they are housed in are also equal. @param obj:The other NodeConnector object to compare with. @type obj: C{Object} @return: returns true if the two NodeConnector are the same """ if obj == None: return False if not isinstance(obj, NodeConnector): return False if self._name != obj.name: return False if self._type != obj.type: return False if self._node.equals(obj.node) is False: return False if Counter(self._address_list) != Counter(obj.address_list): return False return True def __str__(self): """ Returns a string representation of the NodeConnector object. @return: string representation of the object @rtype: C{str} """ mgmt = '' if self._address_list != None and len( self._address_list) > 0 and self._address_list[0] != None: mgmt = self._address_list[0] return 'NodeConnector[' + self._name + ',' + mgmt + ',' + NodeConnector.NodeConnectorType.enumval( self._type) + ']'
class ApplicationCliData(AsyncMsg): """ The application managed data information returned by the network element when a configuration is applied to application data on the network element, or a show application data is invoked through the CLI. @ivar data_name: The name of the data variable @type data_name: C{str} @ivar data_value: The value of the data variable @type data_value: C{str} """ OnepAppCLIDataType = enum('ONEP_APP_CLI_TYPE_CONFIG', 'ONEP_APP_CLI_TYPE_EXEC') def __init__(self, element, data_name, data_val, type): """ Constructor for ApplicationCliData class. """ super(ApplicationCliData, self).__init__( element, _onep_async_msg_type.ONEP_ASYNC_MESSAGE_TYPE_APICALL) self.log = logging.getLogger(__name__) self.data_name = data_name self.data_value = data_val self.cli_type = type self._api_client = ApplmgmtDataIDL.Client(element.api_protocol) def _set_show_data(self, element, data_name, data_value): if data_name == None: raise OnepIllegalArgumentException('dataName', 'None') try: self._api_client.ApplManagedData_setShowDataIDL( element.session_handle._id, data_name, data_value) except ExceptionIDL as e: raise OnepRemoteProcedureException(e) except TException as e: raise OnepConnectionException(e.message, e) def do_event(self, network_element): if network_element == None: return if self.cli_type == self.OnepAppCLIDataType.ONEP_APP_CLI_TYPE_CONFIG: self.log.debug('Message for CLI type: ONEP_APP_CLI_TYPE_CONFIG') target_listener = network_element.get_application_config_cli_listener( ) client_data = network_element.get_application_config_cli_client_data( ) if target_listener != None: target_listener.handle_event(self, client_data) else: self.log.debug('Message for CLI type: ONEP_APP_CLI_TYPE_EXEC') target_listener = network_element.get_application_exec_cli_listener( ) client_data = network_element.get_application_exec_cli_client_data( ) if target_listener != None: show_data_value = target_listener.handle_event( self, client_data) if not isinstance(show_data_value, str): raise TypeError( 'Expected str from %s.handle_event. %s received.' % (type(target_listener), type(show_data_value))) try: self._set_show_data(network_element, self.data_name, show_data_value) except OnepRemoteProcedureException as e: self.log.error( 'Show CLI data dispatch failed with message: ' + e.message) except OnepIllegalArgumentException as e: self.log.error( 'Show CLI data dispatch failed with message: ' + e.message) except OnepConnectionException as e: self.log.error( 'Show CLI data dispatch failed with message: ' + e.message)
import logging from onep.core.util.Enum import enum StorageType = enum(TRANSIENT=0, PERSISTENT=1) StatisticCategory = enum(NONE=0, ENTRY=1, MATCH=3, ACTION=5, ALL=7) from onep.policyservice.bulk import BulkService from onep.policyservice import match as Match from onep.policyservice.target import Target from onep.policyservice.caps import PolicyCapabilities from onep.policyservice import action as Action class PolicyQuery(object): ''' ***DEPRICATED*** PolicyQuery class is deprecated. Please use caps.PolicyCapabilitiesType enum directly **************** ''' PolicyCapabilitiesType = caps.PolicyCapabilitiesType def __init__(self): self.log = logging.getLogger(__name__) self.log.warning('This class is deprecated. ' \ 'Please use caps.PolicyCapabilitiesType')
class Version(object): """ Version class represents the version of a onePK component. The component could be the client-side package version or the server-side version. For onePK applications to work, the server-side and the client-side versioning have to be compatible. onePK has foundation package and optional packages (e.g. LISP, VTY etc) Each of these packages have a server side which resides on the Network Element and a client side which resides in the application in any of the hosting models. The client side corresponds to the SDK package used by application. The onePK server side as well as client-side versions are identified with a version number in the form of: "<b><i>major.minor.maintenance</i></b>" Any "major" release upgrade is not backward compatible, whereas any "minor" or "maintenance" release upgrade is backward compatible. - Major version number reflects the main version of the package and changes only when API signatures changes in non-compatible way. - Minor version numbers changes when new functionalities are added, such as addition of new API, or addition of a new parameter to an API in backward-compatible way. - Maintenance version numbers changes with bug fixes, document changes or support library changes. The usage of versioning by applications is described below. Consider the case where the application client side is running a higher minor version than the server side. Case 1: Application does no version checking. In this case calling a method not supported on the connected Network Element will result in application runtime fault (application will receive exception specifying the method is not supported, causing it to abort). Case 2: Application checks versions and exits gracefully. In this case there is no runtime fault and application can exit gracefully. Case 3: Application checks versions, and continues. When Application knows that it only uses Network Element-supported methods there is no problem. When Application uses methods not supported on the connected Network Element, it would need to set a condition that causes the application to synthesize the missing functionality using only the Network Element supported methods instead. """ def __init__(self, major, minor, maintenance): """ Constructor for internal use only. """ self.major = major self.minor = minor self.maintenance = maintenance VersionCompare = enum('ONEP_VERSION_NCP', 'ONEP_VERSION_MATCH', 'ONEP_VERSION_GT', 'ONEP_VERSION_LT') @classmethod def get_package_version(cls, ssName): """ This method gets the package (Service Set) version which this client program is currently using. @param ssName: Specifies the Service Set whose version is requested. @return: Version object for the Service Set. If the input service set name is null or unsupported, null will be returned. """ if ssName == ServiceSetDescription.ServiceSetName.ONEP_BASE_SERVICE_SET: return Version(ONEP_VERSION_MAJOR, ONEP_VERSION_MINOR, ONEP_VERSION_MAINTENANCE) else: if ssName == ServiceSetDescription.ServiceSetName.ONEP_LISP_SERVICE_SET: return Version(ONEP_VERSION_LISP_MAJOR, ONEP_VERSION_LISP_MINOR, ONEP_VERSION_LISP_MAINTENANCE) return None @classmethod def get_element_version(cls, element, ssName): """ This method gets the Service Set version of the given Network Element. @param element: The Network Element to get the version from. @param ssName: Specifies the Service Set whose version is requested. @return: Version object for the Service Set. If any of the input parameters is null or unsupported, null will be returned. @raise OnepConnectionException: The exception is thrown when the Network Element is not connected. @raise OnepRemoteProcedureException: The exception is thrown when an error has occurred in the remote procedure call made to the Network Element. """ if element == None or ssName == None: return if not element.is_connected(): raise OnepConnectionException('network element is not connected') try: ver_idl = element.api_client.NetworkElement_getVersionIDL( element.session_handle._id, ssName) if ver_idl != None: return Version(ver_idl.major, ver_idl.minor, ver_idl.maint) raise OnepRemoteProcedureException() except ExceptionIDL as e: raise OnepRemoteProcedureException(e) except TException as e: raise OnepConnectionException(e.message, e) @classmethod def version_check(cls, element, ssName): """ This method checks version compatibility between the a given Network Element and this client program. The result of the compatibility check is provided in the form of VersionCompare enum values. The specified Network Element should be in the connected state for the API to validate the compatibility check. The results of the comparison should be interpreted as follows: - ONEP_VERSION_NCP: The client side and Network Element versions are not compatible for the given package - ONEP_VERSION_GT: The client side version is greater than NE version for the given package - ONEP_VERSION_LT: The client side version is less than Network Element version for the given package - ONEP_VERSION_MATCH: The client side and Network Element versions are exact match @param element: The Network Element with which the applications version compatibility check needs to be done for the specified package. @param ssName: Specifies the Service Set to be checked. @return: The result of version check is returned as value of VersionCompare enum. If any of the input parameters is null or unsupported, null will be returned. @raise OnepConnectionException: The exception is thrown when the Network Element is not connected. @raise OnepRemoteProcedureException: The exception is thrown when an error has occurred in the remote procedure call made to the Network Element. """ if element == None or ssName == None: return client_version = cls.get_package_version(ssName) if client_version == None: return ne_version = cls.get_element_version(element, ssName) if ne_version == None: return if client_version.major != ne_version.major: return Version.VersionCompare.ONEP_VERSION_NCP if client_version.minor > ne_version.minor: return Version.VersionCompare.ONEP_VERSION_GT if client_version.minor < ne_version.minor: return Version.VersionCompare.ONEP_VERSION_LT if client_version.maintenance > ne_version.maintenance: return Version.VersionCompare.ONEP_VERSION_GT if client_version.maintenance < ne_version.maintenance: return Version.VersionCompare.ONEP_VERSION_LT return Version.VersionCompare.ONEP_VERSION_MATCH def check_major(self, major): """ This method checks if the Version instance matches a given specific major number. @param major: Integer representing the major number. @return: True if the major version have exact match; false otherwise. """ return self.major == major def check_minor(self, minor): """ This method checks if the Version instance matches a given specific minor number. @param minor: Integer representing the major number. @return: True if the minor version have exact match; false otherwise. """ return self.minor == minor def check_maintenance(self, maintenance): """ This method checks if the Version instance matches a given specific maintenance number. @param maintenance: Integer representing the maintenance number. @return: True if the maintenance versions have exact match; false otherwise. """ return self.maintenance == maintenance def check_exact(self, major, minor, maintenance): """ This method checks if this Version instance matches a given specific major, minor and maintenance number. @param major: Integer representing the major number. @param minor: Integer representing the minor number. @param maintenance: Integer representing the maintenance number. @return: True if the major, minor and maintenance version have exact match; false otherwise. """ return self.major == major and self.minor == minor and self.maintenance == maintenance def __str__(self): return str(self.major) + '.' + str(self.minor) + '.' + str( self.maintenance)
class User(object): """ AAA User class. A AAA User is associated with the following entities: - Network Element which is used to access AAA services for the AAA User - AAA Server that was used for the last AAA service. The server is characterized by its address and the AAA Protocol type (onep_aaa_protocol_e). One or more AAA servers are configured on the Network Element. Based on the availability,one of the configured server is used for accessing the AAA service - AAA Attribute List that contains the Authorization Profile associated with the AAA User that was downloaded from the AAA Server. An attribute list can also be included while sending a service request to the AAA Server. @undocumented: AttrListToIDL """ OnepAAAAcctAction = enum('ONEP_AAA_ACCT_ACTION_START', 'ONEP_AAA_ACCT_ACTION_STOP', 'ONEP_AAA_ACCT_ACTION_UPDATE') def __init__(self, ne, username, password): """ Create a User instance. @param ne: Network Element which is used to access AAA server. @param username: User name. @param password: User password. @raise OnepIllegalArgumentException: if username, password or network element is null @raise OnepException: if application is not connected to network element """ self.server = None self.userID = 0 self.is_auto_acct_enabled = False self.attr_original = [] self.auth_profile = [] User.log = logging.getLogger(__name__) if ne == None: raise OnepIllegalArgumentException('ne') if username == None: raise OnepIllegalArgumentException('username') if password == None: raise OnepIllegalArgumentException('password') if not ne.is_connected(): raise OnepException('Application is not connected to ' + ne.host_address) self.network_element = ne self.username = username self.password = password self.user_client = AaaIDL.Client(ne.api_protocol) def set_network_element(self, network_element): """ Set the network element to be used for the AAA Service. This method updates the Network Element to be used to access the AAA Service for an existing AAA User instance. It overwrites the Network Element that was set in the call to User(NetworkElement,String,String). If auto-accounting is enabled for the user and if an accounting session is active between the existing Network Element and the AAA Server, then this API will result into sending an Accounting-Stop over the accounting session. Auto-accounting session will not be initiated from the new Network Element until the AAA User is authenticated on the new Network Element and the Authorization Profile has auto-accounting enabled. @param network_element: the Network Element to set @raise OnepIllegalArgumentException: if the network element is null """ if network_element == None: raise OnepIllegalArgumentException('network_element') if not network_element.is_connected(): raise OnepException('Application is not connected to ' + network_element.host_address) self.network_element = network_element self.user_client = AaaIDL.Client(network_element.api_protocol) if self.is_auto_acct_enabled: self.send_accounting_record( self.OnepAAAAcctAction.ONEP_AAA_ACCT_ACTION_STOP, []) self.is_auto_acct_enabled = False def authenticate(self, list_): """ Authenticate a user using the AAA Service on the Network Element. This method authenticates a user (i.e. an instance of AAA User) using the AAA Service on the Network Element associated with the user set while creating the AAA User instance or updated using set_network_element(NetworkElement). On successful authentication the following will happen: - The user's authorization profile configured on the AAA server is returned as a AAA Attribute List instance. - Accounting is turned on for the user, if the AAA Server administrator has enabled auto-accounting for this user by configuring Cisco VSA "auto-acct=enable" in the user's authorization profile. The AAA User Authorization Profile is realized using a list of L{onep.aaa.Attribute} structure, which is cached locally in the AAA User instance. Change of Authorization functionality is not available, so if the AAA admin changes the user's profile on the AAA server after the user was successfully authenticated, the new profile will not be reflected in this object unless the Application calls authenticate() again to refresh the Authorization Profile. Note: Accounting, if enabled, is turned off when the AAA User instance is removed using remove_user() or if the AAA User's Network Element attachment is changed using set_network_element(NetworkElement) API Note: The AAA Server that was used to service this request can be retrieved from self.server Note: The "allowed-action" attribute is not returned in the authorization profile. Use is_action_authorized(String) to read the value of this attribute set in the authorization profile configured on the AAA server. Example: >>> attrs = user.authenticate(None) >>> for attr in attrs: print str(attr) @return: List of Attributes containing the authorization profile for the user. If no authorization profile is configured on AAA server, the list is a size of 0. @raise OnepConnectionException: The exception is thrown when connection to a network element has failed @raise OnepRemoteProcedureException: The exception is thrown when error has occurred in the remote- procedure call made to a network element """ attrType = None attr = None attrName = None format = AttrFormat_e() idlList = self.AttrListToIDL(list_) try: self._validate_element_connection() except OnepException: raise try: result = self.user_client.authenticate_IDL( self.network_element.session_handle._id, self.username, self.password, idlList) self.userID = result.aaa_user_id self.is_auto_acct_enabled = True if result.auto_acct_enabled != 0 else False try: address = NetworkInterface._convert_to_inetaddress( result.server.address) self.server = Server( address, Server.OnepAAAProtocol.enumval(result.server.aaa_protocol)) except OnepIllegalArgumentException as e2: self.log.error( 'User authenticate: error retrieving server information') for attrIDL in result.author_profile: skipResultList = False attr = None attrName = None format = attrIDL.format try: attrType = attrIDL.type except OnepIllegalArgumentException as e1: self.log.error('Error adding attribute type ' + str(attrIDL.type) + ' to list, possible enum mismatch') continue if attrIDL.type == OnepAAAAttributeType.ONEP_AAA_AT_ALLOWED_APP or attrIDL.type == OnepAAAAttributeType.ONEP_AAA_AT_ALLOWED_ACTION or attrIDL.type == OnepAAAAttributeType.ONEP_AAA_AT_AUTO_ACCT: skipResultList = True if attrIDL.type == OnepAAAAttributeType.ONEP_AAA_AT_APP_ATTR: appAttrValue = attrIDL.str_value if appAttrValue.startswith('"') and appAttrValue.endswith( '"'): appAttrValue = appAttrValue.substring[1:-1] appValue = appAttrValue.split(':') if len(appValue) < 3: self.log.error('Invalid app attribute format') continue attrName = appValue[0] try: if appValue[1].lower() == 'string': attr = StringAttribute(attrType, attrName, appValue[2]) else: attr = IntAttribute(attrType, attrName, int(appValue[2])) except OnepIllegalArgumentException as e: self.log.error( 'Error adding a Application attribute type ' + str(appValue)) continue elif format == AttrFormat_e.AAA_TYPE_FORMAT_ULONG: try: attr = IntAttribute(attrType, None, attrIDL.ulong_value) except OnepIllegalArgumentException as e: self.log.error('Error adding attribute type ' + str(attrType)) continue elif format == AttrFormat_e.AAA_TYPE_FORMAT_STRING: try: attr = StringAttribute(attrType, None, attrIDL.str_value) except OnepIllegalArgumentException as e: self.log.error('Error adding attribute type ' + str(attrType)) continue elif format == AttrFormat_e.AAA_TYPE_FORMAT_BINARY: try: attr = BinaryAttribute(attrType, None, attrIDL.binary_value) except OnepIllegalArgumentException as e: self.log.error('Error adding attribute type ' + str(attrType)) continue else: try: attr = AddressAttribute(attrType, None, attrIDL.str_value) except OnepIllegalArgumentException as e: self.log.error('Error adding attribute type ' + str(attrType)) continue self.attr_original.append(attr) if not skipResultList: self.auth_profile.append(attr) except ExceptionIDL as e: raise OnepRemoteProcedureException(e) except TException as e: raise OnepConnectionException(arg_cause=e) return self.auth_profile def is_action_authorized(self, action): """ Verify if action is authorized for user. This method verifies whether a particular action is authorized for a user. The action-name string must exactly match one of the action-names in the user's profile on the AAA Server. The search space is limited to actions listed for the application that invoked L{authenticate}. Action-names are case-sensitive. @param action: Action name @return: True if action is authorized, False otherwise. @raise OnepException: if action is not present in the attribute list returned by {@link #authenticate} API """ if self.attr_original == None: raise OnepException('User authorization profile does not exist ') if action == None: raise OnepIllegalArgumentException('action') for attr in self.attr_original: if attr.type_ != OnepAAAAttributeType.ONEP_AAA_AT_ALLOWED_ACTION: continue actionStr = attr.str_value.split(':') if len(actionStr) < 2: self.log.error('Invalid Allowed Action attribute format') continue if actionStr[1].lower() == action.lower(): return True return False def send_accounting_record(self, action, accntRecord): """ Send an accounting record for a user using AAA Service on the Network Element. This method is used for sending an accounting record to the AAA (Accounting) Server. Note: This method must not be used to send Accounting messages if auto-accounting is enabled for the AAA User. Note: If auto-accounting is enabled for a user then this API will not be allowed to be executed. Note: The AAA Server that was used to service this request can be retrieved by calling L{authenticate} @param action: Accounting action type L{OnepAAAAcctAction}, START, STOP,or UPDATE. @param accntRecord: Attribute list containing Application-specific attributes (including byte/packet counters as per RFC2866) to be included in the accounting records. This argument can be specified as None if there are no Application-specific attributes to be sent. @raise OnepConnectionException: The exception is thrown when connection to a network element has failed. @raise OnepRemoteProcedureException: The exception is thrown when error has occurred in the remote- procedure call made to a network element. @raise OnepConnectionException: The exception is thrown when connection to a network element has failed @raise OnepIllegalArgumentException: if accntRecord is null. """ try: self._validate_element_connection() except OnepException: raise if self.is_auto_acct_enabled: raise OnepException('Auto accounting is already enabled') idlList = self.AttrListToIDL(accntRecord) try: acctResult = self.user_client.account_IDL(self.userID, action, idlList) self.userID = acctResult.aaa_user_id except ExceptionIDL as e: raise OnepRemoteProcedureException(e) except TException as e: raise OnepConnectionException(arg_cause=e) def AttrListToIDL(self, attrList): attrIDLList = [] if attrList == None: return attrIDLList for attr in attrList: attrIDLList.append(attr.toIDL(self.network_element)) return attrIDLList def remove_user(self): """ Remove the user record maintained by ONEP Infrastructure. This API removes all the information that is maintained by ONEP session infrastructure for the given user. If accounting has started for the given user, an accounting STOP request is sent to the AAA server. Note: The API below does not remove user records from the AAA server, nor does it invalidate the existing user instance. The application can reuse the existing User instance to re-authenticate with the AAA Server. @raise OnepConnectionException: The exception is thrown when connection to a network element has failed. @raise OnepRemoteProcedureException: The exception is thrown when an error has occurred in the remote procedure call made to a network element. @raise OnepException: The exception is thrown when the removal of user session fails. """ if self.userID == 0: self.log.debug('User session does not exist') return try: self._validate_element_connection() except OnepException: raise try: if self.user_client.deallocate_aaa_user_IDL( self.userID, 1 if self.is_auto_acct_enabled else 0) == 0: raise OnepException('Error removing user ' + self.username) self.is_auto_acct_enabled = False self.attr_original = None self.userID = 0 except ExceptionIDL as e: raise OnepRemoteProcedureException(e) except TException as e: raise OnepConnectionException(arg_cause=e) def _validate_element_connection(self): if not self.network_element.is_connected(): raise OnepException( 'Application is not connected to network element ' + self.network_element.host_address) if self.network_element.session_handle is None: raise OnepException( 'Application is not connected to network element ' + self.network_element.host_address) if self.user_client._iprot is not self.network_element.api_protocol: self.user_client = AaaIDL.Client(self.network_element.api_protocol)
class L3UnicastNextHop(NextHop): """NextHop class represents a next hop of route, and support both IPv4 and IPv6. """ _network_interface = None _address = None _scope = None _error_code = None _metric = None _route_tag = None log = logging.getLogger('onep.' + __name__) NextHopType = enum('DEFAULT', 'REPAIR') def __init__0(self, network_interface, address, metric): super(L3UnicastNextHop, self).__init__() if network_interface == None and address == None: raise OnepIllegalArgumentException( 'networkInterface and address invalid') if network_interface and not isinstance(network_interface, NetworkInterface): raise OnepIllegalArgumentException('networkInterface invalid') if address and not HostIpCheck(address).is_ipaddress(): raise OnepIllegalArgumentException('address invalid') if metric is not None and not isinstance(metric, int): raise OnepIllegalArgumentException('metric invalid') self._network_interface = network_interface self._address = address self._scope = L3UnicastScope() self._metric = metric def __init__(self, network_interface, address, scope=None, error_code=None, metric=None): """Constructor. This constructor can be used for convenience when the Scope is not required, for example, when the route operation is REMOVE. @param network_interface: The network interface in the next hop to set. @type network_interface: L{NetworkInterface<onep.interfaces.NetworkInterface>} @param address: The address in the next hop to set. @type address: C{str} @param scope: The the next hop scope to set. @type scope: L{L3UnicastScope<onep.routing.L3UnicastScope>} @raise OnepIllegalArgumentException: The exception is thrown when both networkInterface and address are not valid. """ if scope is None and error_code is None: self.__init__0(network_interface, address, metric) elif error_code is None: super(L3UnicastNextHop, self).__init__() if network_interface == None and address == None: raise OnepIllegalArgumentException( 'networkInterface and address invalid') if network_interface and not isinstance(network_interface, NetworkInterface): raise OnepIllegalArgumentException('networkInterface invalid') if address and not HostIpCheck(address).is_ipaddress(): raise OnepIllegalArgumentException('address invalid') if metric is not None and not isinstance(metric, int): raise OnepIllegalArgumentException('invalid metric') self._network_interface = network_interface self._address = address self._scope = scope self._metric = metric else: self.__init__1(network_interface, address, scope, error_code, metric) def __init__1(self, network_interface, address, scope, errorCode, metric): super(L3UnicastNextHop, self).__init__() self._network_interface = network_interface self._address = address self._scope = scope self._error_code = errorCode self._metric = metric def _get_network_interface(self): return self._network_interface def _set_network_interface(self, network_interface): if network_interface is None or not isinstance(network_interface, NetworkInterface): raise OnepIllegalArgumentException('Not a valid Interface') self._network_interface = network_interface _doc = '\n The network interface in the next hop\n \n @type: L{NetworkInterface<onep.interfaces.NetworkInterface>}\n @raise OnepIllegalArgumentException: if interface not valid\n ' network_interface = property(_get_network_interface, _set_network_interface, None, _doc) def _get_address(self): return self._address def _set_address(self, address): if address is None or not HostIpCheck(address).is_ipaddress(): raise OnepIllegalArgumentException('address invalid') self._address = address _doc = '\n The address in the next hop\n \n @type: C{str}\n @raise OnepIllegalArgumentException: if address not valid\n ' address = property(_get_address, _set_address, None, _doc) def _get_metric(self): return self._metric def _set_metric(self, metric): if metric is not None and not isinstance(metric, int): raise OnepIllegalArgumentException('metric invalid') self._metric = metric _doc = '\n The metric in the next hop. If a route has multiple next hops,\n the metric can help a router to pick the best next hop to use.\n Larger values indicate higher preference.\n \n @type: C{int}\n @raise OnepIllegalArgumentException: if metric not valid\n ' metric = property(_get_metric, _set_metric, None, _doc) def _get_route_tag(self): return self._route_tag def _set_route_tag(self, route_tag): if route_tag is None: self._route_tag = route_tag elif isinstance( route_tag, (int, long)) and -1 < route_tag and route_tag < 4294967296L: self._route_tag = c_int(route_tag).value else: raise OnepIllegalArgumentException( 'route_tag is invalid. It should be in unsigned 32-bit integer range.' ) _doc = '\n The route tag in the next hop. The route tag can be used by\n routing protocols on the router in conjunction with routing\n policies to decide which routes to advertise to other routers.\n \n @type: C{int}\n @raise OnepIllegalArgumentException: if route tag not valid\n ' route_tag = property(_get_route_tag, _set_route_tag, None, _doc) def __str__(self): """ Gets the string representation of the object @return: The string representation of the object. """ nh_str = 'L3UnicastNextHop[' nh_str += 'Address:' + self.address + ',' nh_str += 'Interface:' if self.network_interface is None: nh_str += 'None,' else: nh_str += self.network_interface.name + ',' nh_str += 'ErrorCode:' + str(self.error_code) + ',' nh_str += 'RouteTag:' + str(self.route_tag) + ',' nh_str += 'Metric:' + str(self.metric) + ']' return nh_str def _to_idl(self): addr_idl = None if self._address != None: addr_idl = NetworkInterface._convert_to_networkaddressidl( self._address) if self._network_interface == None: network_interface_name = None network_interface_handle = 0 network_interface_type = 0 else: network_interface_name = self._network_interface.name network_interface_handle = self._network_interface.xos_handle network_interface_type = self._network_interface.interface_type if self._metric is not None: nh_metric = self._metric else: nh_metric = 0 nh_idl = RouteNextHopIDL(network_interface_name, addr_idl, network_interface_handle, network_interface_type, 0, nh_metric, self._route_tag) self.log.info('Creating RouteNextHopIDL') scope_idl = None if self._scope != None and isinstance(self._scope, (L3UnicastScope, )): scope_idl = self._scope._to_idl() l3nh_idl = L3UcastRouteNextHopIDL(nh_idl, 0, scope_idl) self.log.info('Creating L3UcastRouteNextHopIDL') return l3nh_idl @staticmethod def _from_idl(nh_idl, ne): if nh_idl == None: return addr = None if nh_idl.nextHop and nh_idl.nextHop.address != None: if isinstance(nh_idl, L3UcastRouteNextHopIDL): addr = NetworkInterface._convert_to_inetaddress( nh_idl.nextHop.address) elif isinstance(nh_idl, L3UcastRouteNextHopOutIDL): addr = nh_idl.nextHop.address.addr scp = L3UnicastScope._from_idl(nh_idl.scope) ni = None try: ni = NetworkInterface(ne, nh_idl.nextHop.name, nh_idl.nextHop.interfaceType, nh_idl.nextHop.xosHandle) except OnepIllegalArgumentException as e: L3UnicastNextHop.log.debug('failed to convert NetworkInterface ' + e) L3UnicastNextHop.log.debug('Creating L3UcastRouteNextHop from IDL') l3nh = L3UnicastNextHop(ni, addr, scp, nh_idl.nextHop.ec, nh_idl.nextHop.metric) if nh_idl.nextHop.route_tag is not None: l3nh._route_tag = nh_idl.nextHop.route_tag return l3nh
class CDPEvent(EventObject): """ An event which indicates that a CDP event occurred in a Network Element. A CDP event occurs when the neighbor is connected or disconnected, or its capabilities are updated on the neighbor. """ CDPEventNotifyType = enum(ONEP_CDP_ADD=1, ONEP_CDP_UPDATE=2, ONEP_CDP_DELETE=3, ONEP_CDP_ALL=4) def __init__(self, sourceNE, eventHandle, ni, notifyType, deviceId, holdTime, mgmtDomain, platform, version, capabilities, inetAddr, neighborIntfName): """ Constructor - used internally @param event_handle : Registered event identifier. @type event_handle : C{int} @param intf : Interface on which the CDP event was received @type intf : L{NetworkInterface<onep.interfaces.NetworkInterface>} @param notify_type : CDP notification type add/update/delete @type notify_type : C{int} @param device_id : Device ID from which the CDP event was received @type device_id : C{int} @param hold_time : CDP event hold time associated with this event @type hold_time : C{int} @param mgmt_domain : VTP management domain of the neighbor interface that caused this CDP @type mgmt_domain : C{str} @param platform : Platform type of the neighbor that caused this CDP event @type platform : C{str} @param version : OS version running on the neighbor that caused this CDP event @type version : C{str} @param capabilities : Capabilities @type capabilities : L{PolicyCapabilities<onep.policyservice.PolicyCapabilities.PolicyCapabilities>} @param inet_addr : Network address @type inet_addr : C{str} @param neighbor_intf_name : Neighbor interface name @type neighbor_intf_name : C{str} """ super(CDPEvent, self).__init__(sourceNE, eventHandle, OnepConstants.EVENT_TYPE_CDP) CDPEvent.log = logging.getLogger(__name__) self.log.debug('CDPEvent is constructed') self.event_handle = eventHandle self.intf = ni self.notify_type = notifyType self.device_id = deviceId self.hold_time = holdTime self.mgmt_domain = mgmtDomain self.platform = platform self.version = version self.capabilities = capabilities self.inet_addr = inetAddr self.neighbor_intf_name = neighborIntfName def do_event(self, ne): """ This method specifies what action to do when an event is processed. For CDPEvent, the action is invoking the client's event listener. @param ne: The source of the event. For CDPEvent, the source in an instance of NetworkElement. """ self.log.debug('cdp EventIDL: event_handle = ' + str(self.event_handle) + ' NetworkInterface = ' + str(self.intf) + ' notify_type = ' + str(self.notify_type) + ' neighbor = ' + str(self.device_id) + ' hold time = ' + str(self.hold_time) + ' vtp domain = ' + self.mgmt_domain + ' platform = ' + self.platform + ' version = ' + self.version + ' capabilitites = ' + self.capabilities) targetListener = ne.event_manager.get_event_listener(self.event_handle) clienData = ne.event_manager.get_event_listener_client_data( self.event_handle) if targetListener != None: targetListener.handle_event(self, clienData)
class TopologyEvent(EventObject): """ An event which indicates that a Topology event occurred in a network element. Sample code:: class MyTopologyListener(TopologyListener): def handle_event(self, event, clientData): print "Received Topology Event" if event.type == TopologyEvent.EventType.EDGES_ADD: print "Some edges are added" if event.type = TopologyEvent.EventType.EDGES_DELETE: print "Some edges are removed" print "Number of edges in new topology" print len(event.edge_list) # Create a Topology based on Topology type # The Toplogy object will contain Graph object and will keep the graph updated based # on the events received The latest graph can be obtained # using get_graph method topology = TopologyClass(ne, Topology.TopologyType.CDP) graph = topology.get_graph() listener = MyTopologyListener() event_type = list() event_type.append(TopologyEvent.TopologyEventType.EDGES_ADD) event_type.append(TopologyEvent.TopologyEventType.EDGES_DELETE) filter = TopologyFilter(event_type) event_handle = topology.add_listener(listener, filter, None) @undocumented: do_event @undocumented: __init__ """ TopologyEventType = enum(EDGES_ADD=1, EDGES_DELETE=2, NODES_ADD=4, NODES_DELETE=8) _log = logging.getLogger(__name__) _lock = threading.Lock() _topology = None _tp_event_types = None _edge_list = None def __init__(self, element, event_handle, topology_handle, types, edge_list): """ Constructor for TopologyEvent class @param element: The Network Element in which the topology event occured. @type element: L{NetworkElement<onep.element.NetworkElement>} @param event_handle: Event handle is a unique ID to identify which event listener should receive the event . @type event_handle: C{int} @param topology_handle: A handle/key of topology the sends the events @type topology_handle: C{int} @param types: A set of TopologyTypeEvent enum representing types of changes @type types: C{list} of L{Enum<onep.core.util.Enum>} @param edge_list: List of edges representing the changes @type edge_list: C{list} of L{onep.topology.Edge>} """ super(TopologyEvent, self).__init__(element, event_handle, OnepConstants.EVENT_TYPE_TOPOLOGY) self._topology = TopologyClass._get_topology(topology_handle) self._tp_event_types = types self._edge_list = edge_list def _get_topology(self): return self._topology _doc = ' \n return the Topology object\n @type: L{onep.topology.TopologyClass>}\n ' topology = property(_get_topology, None, _doc) def _get_types(self): return self._tp_event_types _doc = '\n Gets the list of TopologyEventType enum representing the types of changes.\n \n @type: C{list} of L{Enum<onep.util.Enum>}\n ' types = property(_get_types, None, _doc) def _get_edge_list(self): return self._edge_list _doc = '\n Gets the list of edges representing the changes\n \n @type : C{list} of L{Edge<onep.topology.Edge>}\n ' edge_list = property(_get_edge_list, None, _doc) def get_node_list(self): """ Get the node list associated with the event. @return: A list of nodes @rtype: C{list} of L{Node<onep.topology.Node>} """ node_list = [] if self._edge_list: for edge in self._edge_list: node_list.append(edge._head_node) node_list.append(edge._tail_node) return node_list def do_event(self, source): """ This method specifies what action to do when a event is processed in the event queue. For Topology Event, the action is invoking client's event listener @param source: The source of the event. For Topology Event, the source in an instance of NetworkElement @type source: L{NetworkElement<onep.element.NetworkElement>} """ dbg = 'TopologyEvent.doEvent: eventHandle = ' + str(self.event_handle) self._log.debug(dbg) ne = source targetListener = ne.event_manager.get_event_listener(self.event_handle) filter = TopologyClass._get_filter_by_event_handle(self.event_handle) final_event_types = self._get_matched_event_type_list( self._tp_event_types, filter, self) if final_event_types: self._tp_event_types = final_event_types else: self._log.debug('Skip topology event, no listener is interested.') return if targetListener: clientData = ne.event_manager.get_event_listener_client_data( self.event_handle) targetListener.handle_event(self, clientData) self._log.debug('Topology doEvent complete') def _get_matched_event_type_list(self, tp_event_types, filter, event): """ This method processes the events returned by the network element and compares them with the local/cached graph. It identifies if Edges delete or edges add have resulted into Nodes delete or Nodes add events too and updates the local/cached graph accordingly. For internal use only. @param tp_event_types: the events @type tp_event_types: C{list} of L{Enum<onep.util.Enum>} @param filter: The TopologyFilter to specify criteria of interested topology events @type filter: L{TopologyFilter<src.topology.TopologyFilter>} @param event: An event object which indicates that an event occurred in a network element @type event: L{TopologyEvent<src.topology.TopologyEvent>} @return: A list of matched event types @rtype: C{list} of L{Enum<onep.util.Enum>} """ filter_criteria = filter._event_type events_list = [] if filter_criteria: for et in filter_criteria: if et == TopologyEvent.TopologyEventType.EDGES_ADD: if TopologyEvent.TopologyEventType.EDGES_ADD in tp_event_types: events_list.append(et) elif et == TopologyEvent.TopologyEventType.EDGES_DELETE: if TopologyEvent.TopologyEventType.EDGES_DELETE in tp_event_types: events_list.append(et) elif et == TopologyEvent.TopologyEventType.NODES_ADD: if TopologyEvent.TopologyEventType.NODES_ADD in tp_event_types: events_list.append(et) elif TopologyEvent.TopologyEventType.EDGES_ADD in tp_event_types: if self._contains_new_node(event._edge_list, event._topology): self._log.debug('NODES_ADD: found new node') events_list.append(et) elif et == TopologyEvent.TopologyEventType.NODES_DELETE: if TopologyEvent.TopologyEventType.NODES_DELETE in tp_event_types: self._log.debug('NODES_DELETE: found node delete') events_list.append(et) elif TopologyEvent.TopologyEventType.EDGES_DELETE in tp_event_types: if self._contains_dangling_node( event._edge_list, event._topology): self._log.debug( 'NODES_DELETE: found dangling node') events_list.append(et) for etype in tp_event_types: if etype in (TopologyEvent.TopologyEventType.EDGES_ADD, TopologyEvent.TopologyEventType.EDGES_DELETE): event._topology._cached_graph.update(etype, event._get_edge_list()) if etype in (TopologyEvent.TopologyEventType.NODES_ADD, TopologyEvent.TopologyEventType.NODES_DELETE): event._topology._cached_graph.update(etype, event._get_node_list()) return events_list def _contains_new_node(self, edge_list, topology): """ This method returns true if a new node is found. For internal use only. @param edge_list: List of Edges @type edge_list: C{list} of L{onep.topology.Edge>} @param topology: TopologyClass @type topology: L{TopologyClassr<src.topology.TopologyClass>} @return: True if a new node is found else False """ if edge_list: for edge in edge_list: if self._is_node_exists(edge._head_node, topology): if self._is_node_exists(edge._tail_node, topology): return False else: raise OnepIllegalArgumentException('EdgeList is invalid.') return True def _is_node_exists(self, node, topology): """ This method iterates through the cached graph to find if the node already exists or not For internal use only. @param node: Node to be found @type node: L{Node<onep.topology.Node>} @param topology: TopologyClass @type topology: L{TopologyClassr<src.topology.TopologyClass>} @return: True if the node exists else False """ if topology and topology._cached_graph: with self._lock: for cnode in topology._cached_graph._get_node_list(): if node._name == cnode._name: return True else: raise OnepIllegalArgumentException('Invalid Topology params.') return False def _contains_dangling_node(self, edge_list, topology): """ This method returns true if it finds a Node that has no connection to another node. For internal use only. @param edge_list: List of Edges @type edge_list: C{list} of L{onep.topology.Edge>} @param topology: TopologyClass @type topology: L{TopologyClassr<src.topology.TopologyClass>} @return: True if a dangling node is found else False """ if edge_list: for edge in edge_list: if self._get_edge_count_by_node(edge._head_node, topology) <= 1: return True if self._get_edge_count_by_node(edge._tail_node, topology) <= 1: return True else: raise OnepIllegalArgumentException('EdgeList is invalid.') return False def _get_edge_count_by_node(self, node, topology): """ This method iterates through the cached graph to find the number of connections a node has. For internal use only. @param node: Node to be found @type node: L{Node<onep.topology.Node>} @param topology: TopologyClass @type topology: L{TopologyClassr<src.topology.TopologyClass>} @return count: number of connections a node has """ if not node or not topology or not topology._cached_graph: raise OnepIllegalArgumentException('Invalid Topology params.') with self._lock: edge_list = topology._cached_graph.get_edge_list( Edge.EdgeType.DIRECTED) if edge_list: count = 0 for edge in edge_list: if edge: if node._name == edge._head_node._name: count = count + 1 if node._name == edge._tail_node._name: count = count + 1 return count raise OnepIllegalArgumentException('EdgeList is invalid.') @staticmethod def _convert_type_list_to_bitmip(type_list): bitmask = 0 for st in type_list: bitmask |= st return bitmask @staticmethod def convert_type_bitmip_to_list(type_mask): type_list = [] if type_mask & TopologyEvent.TopologyEventType.EDGES_ADD > 0: type_list.append(TopologyEvent.TopologyEventType.EDGES_ADD) if type_mask & TopologyEvent.TopologyEventType.EDGES_DELETE > 0: type_list.append(TopologyEvent.TopologyEventType.EDGES_DELETE) if type_mask & TopologyEvent.TopologyEventType.NODES_ADD > 0: type_list.append(TopologyEvent.TopologyEventType.NODES_ADD) if type_mask & TopologyEvent.TopologyEventType.NODES_DELETE > 0: type_list.append(TopologyEvent.TopologyEventType.NODES_DELETE) return type_list
# 2015.02.05 17:19:57 IST from onep.policyservice import action from onep.policyservice import match from onep.PolicyBulkIDL.PolicyBulkIDL import Client from onep.core.util.OnepArgumentTypeValidate import * from onep.core.util.Enum import enum from onep.core.exception import OnepIllegalArgumentException from onep.core.exception import OnepRemoteProcedureException from onep.core.exception import OnepNotSupportedException from Shared.ttypes import ExceptionIDL import logging PolicyCapabilitiesType = enum( 'NONE', 'ACL_INGRESS', 'ACL_EGRESS', 'QOS_INGRESS', 'QOS_EGRESS', 'L2_ANY', 'L2_DEST', 'L2_IPV4_L4_ANY', 'L2_IPV6_L4_ANY', 'L2_ACL', 'L2_L3', 'L3_IPV4', 'L3_IPV6', 'L3_DS', 'IPV4_L4_ANY', 'IPV6_L4_ANY', 'IPV4_DEST', 'IPV6_DEST', 'PBR', 'TRAFFIC_INGRESS', 'TRAFFIC_EGRESS', 'ZBFW', 'DATAPATH', 'MAC', 'ANY', 'MPLS', 'ARP', 'SELECTOR', 'LAST') _service_set_excluded = { PolicyCapabilitiesType.DATAPATH: { 'actions': [action.ActionType.COPY, action.ActionType.DIVERT], 'matches': [] } } def _in_excluded(table, item, index): if table.type in _service_set_excluded: return item in _service_set_excluded[table.type][index] def _translate_action_enums(table):
def __init__(self): """ Constructs an OIRFilter object without specifying criteria """ super(OIRFilter, self).__init__() self._oir_type = OIRFilter.OIRType.ONEP_OIR_ALL def _get_oir_type(self): return self._oir_type def _set_oir_type(self, oir_type): if oir_type: self._oir_type = oir_type else: self._oir_type = OIRFilter.OIRType.ONEP_OIR_ALL _doc_oir_type = '\n The parameter used by the filter to identify type of OIR event to be \n listened to. It is of the type OIRFilter.OIRTYPE. If the oir_type is\n set to none, the default type "ONEP_OIR_ALL" will be used,\n which will receive notifications for all OIR events.\n ' oir_type = property(_get_oir_type, _set_oir_type, _doc_oir_type) OIRFilter.OIRType = enum('ONEP_OIR_ALL', 'ONEP_OIR_INSERT', 'ONEP_OIR_REMOVE', 'ONEP_OIR_UNKNOWN') # decompiled 1 files: 1 okay, 0 failed, 0 verify failed # 2015.02.05 17:18:18 IST
if f: f.close() if fcopy: fcopy.close() os.remove(file_path + '.tmp') _LOCK.release() if not error and fd == -1 and not line or _CLOSING_SENTINEL != line.rstrip( ): error = True if error: _LOGGER.error( "One or more errors occurred while processing file '%s'. The file is possibly corrupted.", file_path) DecisionType = enum('REJECT', 'ACCEPT_AND_PIN', 'ACCEPT_ONCE') class TLSUnverifiedElementHandler(object): """ This class represents a handler for TLS connections in which the network element has not been verified. The class that wants to process unverified TLS connections and decide whether to accept or reject them should subclass this class. """ __metaclass__ = ABCMeta @abstractmethod
class InterfaceConfig(object): """ This class represents the configuration (software property) of the network interface. The configuration might be changed during the life of the session. Hence, it is refreshed if the last accessed time has aged out. @ivar islayer2: Indicates if this a Layer-2 Interface @type islayer2: C{bool} @ivar display_name: The name of the interface. @type display_name: C{str} @ivar description: The description of the interface. @type description: C{str} @ivar tx_bandwidth: The interface transmit bandwidth @type tx_bandwidth: C{int} @ivar rx_bandwidth: The interface receive bandwidth @type rx_bandwidth: C{int} @ivar mtu: The MTU value of the interface @type mtu: C{int} @ivar mac_address: The MAC address of the interface @type mac_address: C{str} @ivar undir_mode: Gets the unidirectional mode, @type undir_mode: L{UnidirMode<interfaces.InterfaceConfig.InterfaceConfig.UnidirMode>} @ivar encap: The interface encapsulation type. @type encap: L{Encap<interfaces.InterfaceConfig.InterfaceConfig.Encap>} @ivar snmp_index: The interface Simple Network Management Protocol (SNMP) index @type snmp_index: C{int} @undocumented: __init__ @undocumented: DuplexMode @undocumented: speed @undocumented: duplex @undocumented: duplex_conf @undocumented: fwd_class_id @undocumented: flow_control @undocumented: auto_neg """ Encap = enum('ONEP_IF_ENCAP_NULL', 'ONEP_IF_ENCAP_ANY', 'ONEP_IF_ENCAP_UNKNOWN', 'ONEP_IF_ENCAP_ARPA', 'ONEP_IF_ENCAP_LOOP', 'ONEP_IF_ENCAP_DOT1Q', 'ONEP_IF_ENCAP_ATM', 'ONEP_IF_ENCAP_SNAP', 'ONEP_IF_ENCAP_HDLC', 'ONEP_IF_ENCAP_PPP', 'ONEP_IF_ENCAP_ETHER', 'ONEP_IF_ENCAP_GRE', 'ONEP_IF_ENCAP_MPLS') UnidirMode = enum('ONEP_IF_UNIDIR_MODE_OFF', 'ONEP_IF_UNIDIR_MODE_SEND_ONLY', 'ONEP_IF_UNIDIR_MODE_RECV_ONLY', 'ONEP_IF_UNIDIR_MODE_NOT_SUPPORTED') DuplexMode = enum('ONEP_IF_HALF_DUPLEX', 'ONEP_IF_FULL_DUPLEX', 'ONEP_IF_AUTO_DUPLEX', 'ONEP_IF_DUPLEX_NOT_SUPPORTED') SwitchportMode = enum('ONEP_IF_SWITCHPORT', 'ONEP_IF_SWITCHPORT_MODE_ACCESS', 'ONEP_IF_SWITCHPORT_MODE_DOT1Q_TUNNEL', 'ONEP_IF_SWITCHPORT_MODE_TRUNK', 'ONEP_IF_SWITCHPORT_MODE_NOT_SUPPORTED') def __init__(self, encap, unidir_mode, mtu, rx_bandwidth, tx_bandwidth, snmp_index, islayer2, display_name, mac_address, description, ip_redirect, ip_unreachable, ip_proxy_arp, ip_unicast_reverse_path, vrf, speed=None, duplex=None, duplex_conf=None, fwdClassID=None, flow_control=None, auto_neg=None): """ Constructor of InterfaceConfig class. """ self.encap = encap self.unidir_mode = unidir_mode self.mtu = mtu self.rx_bandwidth = rx_bandwidth self.tx_bandwidth = tx_bandwidth self.snmp_index = snmp_index self.islayer2 = islayer2 self.display_name = display_name self.mac_address = mac_address self.description = description self.iphelper = [] self.ip_redirect = bool(ip_redirect) self.ip_unreachable = bool(ip_unreachable) self.ip_proxy_arp = bool(ip_proxy_arp) self.ip_unicast_reverse_path = bool(ip_unicast_reverse_path) self.vrf = vrf self.speed = speed self.duplex = duplex self.duplex_conf = duplex_conf self.fwd_class_id = fwdClassID self.flow_control = flow_control self.auto_neg = auto_neg def __str__(self): """ Returns the configuration in string format. """ tmp = 'Interface Configuration' tmp += '\n Interface Name: ' + str(self.display_name) tmp += '\n MAC Address: ' + str(self.mac_address) tmp += '\n Rx Bandwidth: ' + str(self.rx_bandwidth) tmp += '\n Tx Bandwidth: ' + str(self.tx_bandwidth) tmp += '\n MTU: ' + str(self.mtu) tmp += '\n SNMP Index: ' + str(self.snmp_index) tmp += '\n Layer2: ' + str(self.islayer2) tmp += '\n Encapsulation: ' + str(self.Encap.enumval(self.encap)) tmp += '\n Mode: ' + str(self.UnidirMode.enumval(self.unidir_mode)) tmp += '\n Description: ' + str(self.description) tmp += '\n IP helper-addresses: ' + str(self.iphelper) tmp += '\n IP redirect: ' + str(self.ip_redirect) tmp += '\n IP unreachable: ' + str(self.ip_unreachable) tmp += '\n IP proxy ARP: ' + str(self.ip_proxy_arp) tmp += '\n IP unicast reverse path: ' + str( self.ip_unicast_reverse_path) tmp += '\n Virtual Route Forwarding: %s' % str(self.vrf) return tmp