Esempio n. 1
0
    trafficItemObj = trafficStatus[0]
    endpointObj = trafficStatus[1][0]
    configElementObj = trafficStatus[2][0]

    trafficObj.startTraffic(regenerateTraffic=True, applyTraffic=True)

    # Check the traffic state before getting stats.
    #    Use one of the below APIs based on what you expect the traffic state should be before calling stats.
    #    If you expect traffic to be stopped such as for fixedFrameCount and fixedDuration
    #    or do you expect traffic to be started such as in continuous mode.
    trafficObj.checkTrafficState(expectedState=['stopped'], timeout=45)
    #trafficObj.checkTrafficState(expectedState=['started'], timeout=45)

    statObj = Statistics(mainObj)
    stats = statObj.getStats(viewName='Flow Statistics')

    print(
        '\n{txPort:10} {txFrames:15} {rxPort:10} {rxFrames:15} {frameLoss:10}'.
        format(txPort='txPort',
               txFrames='txFrames',
               rxPort='rxPort',
               rxFrames='rxFrames',
               frameLoss='frameLoss'))
    print('-' * 90)

    for flowGroup, values in stats.items():
        txPort = values['Tx Port']
        rxPort = values['Rx Port']
        txFrames = values['Tx Frames']
        rxFrames = values['Rx Frames']
Esempio n. 2
0
            'frameSize': 128
        }])

    trafficItemObj = trafficStatus[0]
    endpointObj = trafficStatus[1][0]
    configElementObj = trafficStatus[2][0]

    trafficObj.startTraffic(regenerateTraffic=True, applyTraffic=True)

    # Check the traffic state to assure traffic has stopped before checking for stats.
    if trafficObj.getTransmissionType(configElementObj) == "fixedFrameCount":
        trafficObj.checkTrafficState(
            expectedState=['stopped', 'stoppedWaitingForStats'], timeout=45)

    statObj = Statistics(mainObj)
    stats = statObj.getStats(viewName='Flow Statistics', silentMode=False)

    print(
        '\n{txPort:10} {txFrames:15} {rxPort:10} {rxFrames:15} {frameLoss:10}'.
        format(txPort='txPort',
               txFrames='txFrames',
               rxPort='rxPort',
               rxFrames='rxFrames',
               frameLoss='frameLoss'))
    print('-' * 90)

    for flowGroup, values in stats.items():
        txPort = values['Tx Port']
        rxPort = values['Rx Port']
        txFrames = values['Tx Frames']
        rxFrames = values['Rx Frames']
                                               egressTrackingPort, offsetBit,
                                               bitWidth, egressStatViewName,
                                               ingressTrackingFilterName)

    trafficObj.startTraffic()

    response = mainObj.get(mainObj.httpHeader + statview)
    print(response.json())

    # Check the traffic state to assure traffic has indeed stopped before checking for stats.
    if trafficObj.getTransmissionType(configElementObj) == "fixedFrameCount":
        trafficObj.checkTrafficState(
            expectedState=['stopped', 'stoppedWaitingForStats'], timeout=45)

    statObj = Statistics(mainObj)
    stats = statObj.getStats(viewName=egressStatViewName)

    #if removeAllTclStatViews:
    #    mainObj.removeAllTclViews()

    print('{0:10} {1:15} {2:15}'.format('rxPort', 'txFrames', 'rxFrames'))
    print('-' * 90)

    for flowGroup, values in stats.items():
        rxPort = values['Rx Port']
        txFrames = values['Tx Frames']
        rxFrames = values['Rx Frames']
        frameLoss = values['Frames Delta']

        print('{rxPort:10} {txFrames:15} {rxFrames:15}'.format(
            rxPort=rxPort, txFrames=txFrames, rxFrames=rxFrames))
Esempio n. 4
0
    quickTestObj.verifyQuickTestInitialization(quickTestHandle)
    quickTestObj.monitorQuickTestRunningProgress(quickTestHandle, getProgressInterval=3)

    # where: localWindows|remoteWindows|remoteLinux
    # Copy result files from Windows API server to local Windows.
    #quickTestObj.getQuickTestPdf(quickTestHandle, copyToLocalPath='C:\\Results', where='localWindows',
    #                             renameDestinationFile='rfc2544.pdf', includeTimestamp=True)
    #quickTestObj.getQuickTestCsvFiles(quickTestHandle, copyToPath='c:\\Results', csvFile='all')

    # Copy result files from Windows API server to remote Linux.
    quickTestObj.getQuickTestPdf(quickTestHandle, copyToLocalPath='/home/hgee', where='remoteLinux',
                                 renameDestinationFile='rfc2544.pdf', includeTimestamp=True)
    quickTestObj.getQuickTestCsvFiles(quickTestHandle, copyToPath='/home/hgee', csvFile='all')

    statObj = Statistics(mainObj)
    stats = statObj.getStats(viewName='Flow View')

    print('\n{txPort:15} {rxPort:15} {rxThruPut:10} {txFrames:15} {rxFrames:10} {frameLoss:10}'.format(
        txPort='txPort', rxPort='rxPort', rxThruPut='rxThruPut', txFrames='txFrames', rxFrames='rxFrames', frameLoss='frameLoss'))
    print('-'*90)

    for flowGroup,values in stats.items():
        txPort = values['Tx Port']
        rxPort = values['Rx Port']
        rxThroughput = values['Rx Throughput (% Line Rate)']
        txFrameCount = values['Tx Count (frames)']
        rxFrameCount = values['Rx Count (frames)']
        frameLoss = values['Frame Loss (frames)']

        print('{txPort:15} {rxPort:15} {rxThruPut:10} {txFrames:15} {rxFrames:10} {frameLoss:10}'.format(
            txPort=txPort, rxPort=rxPort, rxThruPut=rxThroughput, txFrames=txFrameCount, rxFrames=rxFrameCount, frameLoss=frameLoss))
Esempio n. 5
0
class ClassicProtocol(object):
    def __init__(self, ixnObj=None):
        """
        Parameters
           ixnObj: <str>: The main connection object.
        """
        self.ixnObj = ixnObj

        from IxNetRestApiPortMgmt import PortMgmt
        self.portMgmtObj = PortMgmt(self.ixnObj)

        from IxNetRestApiStatistics import Statistics
        self.statObj = Statistics(self.ixnObj)

    def getPortsByProtocol(self, protocolName):
        """
        Description
            Based on the specified protocol, return all ports associated with the protocol.

        Parameters
           protocolName options:
              bfd, bgp, cfm, eigrp, elmi, igmp, isis, lacp, ldp, linkOam, lisp, mld,
              mplsOam, mplsTp, openFlow, ospf, ospfV3, pimsm, ping, rip, ripng, rsvp,
              static, stp

        Returns: [chassisIp, cardNumber, portNumber]
                  Example: [['192.168.70.11', '1', '1'], ['192.168.70.11', '1', '2']]

        Returns [] if no port is configured with the specified protocolName
        """
        portList = []
        response = self.ixnObj.get(self.ixnObj.sessionUrl + '/vport')
        # ['http://{apiServerIp:port}/api/v1/sessions/1/ixnetwork/vport/1']
        vportList = [
            '%s/%s/%s' % (self.ixnObj.sessionUrl, 'vport', str(i["id"]))
            for i in response.json()
        ]

        # Go through each port that has the protocol enabled.
        for vport in vportList:
            # http://{apiServerIp:port}/api/v1/sessions/1/ixnetwork/vport/1/protocols/ospf
            currentProtocol = vport + '/protocols/' + protocolName
            response = self.ixnObj.get(currentProtocol)
            if response.json()['enabled'] == True:
                # 192.168.70.11:1:5
                response = self.ixnObj.get(vport)
                assignedTo = response.json()['assignedTo']
                currentChassisIp = str(assignedTo.split(':')[0])
                currentCardNumber = str(assignedTo.split(':')[1])
                currentPortNumber = str(assignedTo.split(':')[2])
                currentPort = [
                    currentChassisIp, currentCardNumber, currentPortNumber
                ]
                portList.append(currentPort)

        return portList

    def getProtocolListByPort(self, port):
        """
        Description
            Get all enabled protocols by the specified port.

        Parameters
            port: [chassisIp, cardNumber, portNumber] -> ['192.168.70.11', '2', '8']
        """
        self.ixnObj.logInfo('\ngetProtocolListByPort...')
        chassis = str(port[0])
        card = str(port[1])
        port = str(port[2])
        specifiedPort = [chassis, card, port]
        enabledProtocolList = []
        response = self.ixnObj.get(self.ixnObj.sessionUrl + '/vport')
        vportList = [
            '%s/%s/%s' % (self.ixnObj.sessionUrl, 'vport', str(i["id"]))
            for i in response.json()
        ]
        for vport in vportList:
            response = self.ixnObj.get(vport, 'assignedTo')
            # 192.168.70.11:1:5
            assignedTo = response.json()['assignedTo']
            currentChassisIp = str(assignedTo.split(':')[0])
            currentCardNumber = str(assignedTo.split(':')[1])
            currentPortNumber = str(assignedTo.split(':')[2])
            currentPort = [
                currentChassisIp, currentCardNumber, currentPortNumber
            ]
            if currentPort != specifiedPort:
                continue
            else:
                response = self.ixnObj.get(vport + '/protocols?links=true')
                if response.status_code == 200:
                    #print 'json', response.json()['links']
                    for protocol in response.json()['links']:
                        currentProtocol = protocol['href']
                        url = self.ixnObj.httpHeader + currentProtocol
                        response = self.ixnObj.get(url)
                        if 'enabled' in response.json() and response.json(
                        )['enabled'] == True:
                            # Exclude ARP object
                            if 'arp' not in currentProtocol:
                                enabledProtocolList.append(
                                    str(currentProtocol))

        return enabledProtocolList

    def sendArpOnPort(self, portName):
        """
        Description
            Send Arp request on a specified port

        Parameters
            portName: <str>: Name of the port. eg: '1/1/11'

        Syntax
            POST: http://10.154.162.94:11009/api/v1/sessions/1/ixnetwork/vport/operations/sendarp
            DATA: {"arg1": "/api/v1/sessions/1/ixnetwork/vport/1"}

        Examples
            sendArpOnPort(portName='1/1/11')
        """
        vport = self.portMgmtObj.getVportObjectByName(portName)
        if vport == None:
            raise IxNetRestApiException(
                'PortName {0} not connected to chassis'.format(portName))

        url = self.ixnObj.sessionUrl + '/vport/operations/sendarp'
        response = self.ixnObj.post(url, data={'arg1': vport})
        self.ixnObj.waitForComplete(response,
                                    url + '/' + response.json()['id'])

    def getDiscoverdNeighborOnPort(self, portName):
        """
        Description
            Get Arp discovered neighbor on a specified port

        Parameters
            portName: <str>: Name of the port. eg: '1/1/11'

        Syntax
            GET: http://10.154.162.94:11009/api/v1/sessions/1/ixnetwork/vport/1/discoveredNeighbor/1

        Examples
            getDiscoverdNeighborOnPort(portName='1/1/11')

        Return
            Discovered mac address
        """
        vport = self.portMgmtObj.getVportObjectByName(portName)
        if vport == None:
            raise IxNetRestApiException(
                'PortName {0} not connected to chassis'.format(portName))

        url = vport + '/discoveredNeighbor'
        response = self.ixnObj.get(url)

        url = self.ixnObj.httpHeader + response.json()[0]['links'][0]['href']
        response = self.ixnObj.get(url)

        self.ixnObj.logInfo('Discovered Neighbor: %s' %
                            response.json()['neighborMac'])
        return response.json()['neighborMac']

    def startStopProtocolOnPort(self, protocol, portName, action='start'):
        """
        Description
            Start and stop a protocol on a specified port

        Parameters
            protocol: <str>: Protocol to start
            portName: <str>: Name of the port, eg: '1/1/11'
            action: <str>: start or stop a protocol, default is start

        Syntax
            POST: /api/v1/sessions/{id}/ixnetwork/vport/protocols/<protocol>
            DATA: {'args': 'api/v1/sessions/1/ixnetwork/vport/1'}

        Examples
            startStopProtocolOnPort(protocol='ospf', portName='1/1/11')
            startStopProtocolOnPort(protocol='ospf', portName='1/1/11', action='stop')

        """
        vport = self.portMgmtObj.getVportObjectByName(portName)
        if vport == None:
            raise IxNetRestApiException(
                'PortName {0} not connected to chassis'.format(portName))

        url = self.ixnObj.sessionUrl + '/vport/protocols/' + protocol + '/operations/' + action
        vport = vport + '/protocols/' + protocol
        response = self.ixnObj.post(url, data={'arg1': vport})
        self.ixnObj.waitForComplete(response,
                                    url + '/' + response.json()['id'])

    def getConfiguredProtocols(self):
        """
        Description
            Get the list of protocols configured on vports.

        Return
            A list or one or more congfigured protocols eg: "['ospf','bgp']"
            return [] if no protocol is configured
        """
        time.sleep(5)
        configuredProtocolList = []
        protocolList = [
            'bfd', 'bgp', 'eigrp', 'isis', 'ldp', 'lisp', 'mplsOam', 'mplsTp',
            'ospf', 'ospfV3', 'pimsm', 'rip', 'ripng'
        ]
        response = self.ixnObj.get(self.ixnObj.sessionUrl + '/vport')
        if response == False:
            raise IxNetRestApiException('No ports connected to chassis')

        vportList = [
            '%s' % vport['links'][0]['href'] for vport in response.json()
        ]
        for eachVport in vportList:
            for eachProtocol in protocolList:
                node = '/router'
                if re.search('bgp', eachProtocol, re.I):
                    node = '/neighborRange'
                protocolResponse = self.ixnObj.get(self.ixnObj.httpHeader +
                                                   eachVport + '/protocols/' +
                                                   eachProtocol)
                response = self.ixnObj.get(self.ixnObj.httpHeader + eachVport +
                                           '/protocols/' + eachProtocol + node)
                if response.json() != []:
                    if response.json(
                    )[0]['enabled'] == True and protocolResponse.json(
                    )['runningState'] == 'started':
                        configuredProtocolList.append(eachProtocol)
        configuredProtocolList = list(set(configuredProtocolList))
        return configuredProtocolList

    def enableProtocolOnPort(self, protocol, portName, enable=True):
        """
        Description
           Enable protocol on a speficied port

        Parameters
            protocol: <str>: Protocol to start
            portName: <str>: Name of the port eg: '1/1/11'
            enable: <bool> enable or disable specified protocol. default is True

        Syntax
            PATCH: /api/v1/sessions/{id}/ixnetwork/vport/{id}/protocols/<protocol>/router/{id}
            PATCH: /api/v1/sessions/{id}/ixnetwork/vport/{id}/protocols/<protocol>/neighborRange/{id}
            PATCH: /api/v1/sessions/{id}/ixnetwork/vport/{id}/protocols/<protocol>/host/{id}
            PATCH: /api/v1/sessions/{id}/ixnetwork/vport/{id}/protocols/<protocol>/bridge/{id}
            PATCH: /api/v1/sessions/{id}/ixnetwork/vport/{id}/protocols/<protocol>/actor/{id}
            PATCH: /api/v1/sessions/{id}/ixnetwork/vport/{id}/protocols/<protocol>/neighborPair/{id}

        Examples
            enableProtocolOnPort(protocol='ospf', portName='1/1/11')
            enableProtocolOnPort(protocol='ospf', portName='1/1/11', enable=False)
        """
        vport = self.portMgmtObj.getVportObjectByName(portName)
        if vport == None:
            raise IxNetRestApiException(
                'PortName {0} not connected to chassis'.format(portName))

        RouterInstanceList = self.getRouterInstanceByPortAndProtocol(
            protocol=protocol, vport=vport)
        if RouterInstanceList == []:
            raise IxNetRestApiException(
                'No Router instance exists in protocol {0}'.format(protocol))

        for eachRouterInstance in RouterInstanceList:
            url = self.ixnObj.httpHeader + eachRouterInstance
            self.ixnObj.patch(url, data={"enabled": enable})

    def getProtocolSessionsStats(self, portName, protocol):
        """
        Description
            Get a protocol session status for a specified protocol on a port

        Parameters
            portName: <str>: Name of the Port to get the protocol session stats eg: "1/1/11"
            protocol: <str>: Name of the protocol. eg: <ospf/ospfV3/bgp/isis/ripng/bfd/rip/ldp/mplsoam/pim>

        Examples
            getProtocolSessionsStats(portName='1/1/11', protocol='ospf')

        Return
            Protocol stats in dictionary format eg: {'ospf': {'Configured': 2, 'Up': 1}}
        """
        protocolStats = {}
        vport = self.portMgmtObj.getVportObjectByName(portName)
        if vport == None:
            raise IxNetRestApiException(
                'PortName {0} not connected to chassis'.format(portName))

        node = '/router'
        if re.search('bgp', protocol, re.I):
            node = '/neighborRange'
        protocolResponse = self.ixnObj.get(vport + '/protocols/' + protocol)
        response = self.ixnObj.get(vport + '/protocols/' + protocol + node)

        if response.json() != []:
            if response.json()[0]['enabled'] == True and protocolResponse.json(
            )['runningState'] == 'started':
                if re.search('ospf', protocol, re.I):
                    protocolViewName = 'OSPF Aggregated Statistics'
                elif re.search('ospfV3', protocol, re.I):
                    protocolViewName = 'OSPFv3 Aggregated Statistics'
                elif re.search('bgp', protocol, re.I):
                    protocolViewName = 'BGP Aggregated Statistics'
                elif re.search('isis', protocol, re.I):
                    protocolViewName = 'ISIS Aggregated Statistics'
                elif re.search('ripng', protocol, re.I):
                    protocolViewName = 'RIPng Aggregated Statistics'
                elif re.search('bfd', protocol, re.I):
                    protocolViewName = 'BFD Aggregated Statistics'
                elif re.search('rip', protocol, re.I):
                    protocolViewName = 'RIP Aggregated Statistics'
                elif re.search('ldp', protocol, re.I):
                    protocolViewName = 'LDP Aggregated Statistics'
                elif re.search('mplsoam', protocol, re.I):
                    protocolViewName = 'MPLSOAM Aggregated Statistics'
                elif re.search('pim', protocol, re.I):
                    protocolViewName = 'PIMSM Aggregated Statistics'
                else:
                    raise IxNetRestApiException('No viewName defined')
            else:
                raise IxNetRestApiException(
                    'No {0} protocol running or enabled on port {1}'.format(
                        protocol, portName))
        else:
            raise IxNetRestApiException(
                'No {0} protocol configured on port {1}'.format(
                    protocol, portName))

        stats = self.statObj.getStats(viewName=protocolViewName,
                                      displayStats=False)

        #totalPorts = len(stats.keys());  # Length stats.keys() represents total ports.
        self.ixnObj.logInfo('ProtocolViewName: {0}'.format(protocolViewName))
        for session in stats.keys():
            if re.search('OSPF', protocolViewName, re.I):
                sessionsUp = int(stats[session]['Full Nbrs.'])
                totalSessions = int(stats[session]['Sess. Configured'])
            elif re.search('BGP', protocolViewName, re.I):
                sessionsUp = int(stats[session]['Sess. Up'])
                totalSessions = int(stats[session]['Sess. Configured'])
            elif re.search('ISIS', protocolViewName, re.I):
                sessionsUp = int(stats[session]['L2 Sess. Up'])
                totalSessions = int(stats[session]['L2 Sess. Configured'])
            elif re.search('RIPng', protocolViewName, re.I) or re.search(
                    'BFD', protocolViewName, re.I):
                sessionsUp = int(stats[session]['Routers Running'])
                totalSessions = int(stats[session]['Routers Configured'])
            elif re.search('RIP', protocolViewName, re.I):
                sessionsUp = int(stats[session]['Request Packet Tx'])
                totalSessions = int(stats[session]['Routers Configured'])
            elif re.search('LACP', protocolViewName, re.I):
                sessionsUp = int(stats[session]['LAG Member Ports UP'])
                totalSessions = int(stats[session]['Total LAG Member Ports'])
            elif re.search('LDP', protocolViewName, re.I):
                sessionsUp = int(stats[session]['Targeted Sess. Up'])
                totalSessions = int(
                    stats[session]['Targeted Sess. Configured'])
            elif re.search('MPLS', protocolViewName, re.I):
                sessionsUp = int(stats[session]['BFD Up-Sessions'])
                totalSessions = int(stats[session]['BFD Session Count'])
            elif re.search('PIM', protocolViewName, re.I):
                sessionsUp = int(stats[session]['Rtrs. Running'])
                totalSessions = int(stats[session]['Rtrs. Configured'])
                # totalSessionsNotStarted = int(stats[session]['Sessions Not Started'])
            else:
                raise IxNetRestApiException('No protocol viewName found')

            if stats[session]['Port Name'] == portName:
                self.ixnObj.logInfo(
                    '\n\tPortName: {0}\n\t   TotalSessionsUp: {1}\n\t   TotalSessionsConfigured: {2}'
                    .format(stats[session]['Port Name'], sessionsUp,
                            totalSessions),
                    timestamp=False)
                protocolStats[protocol] = {
                    'Configured': totalSessions,
                    'Up': sessionsUp
                }
        return protocolStats

    def enableRouteRangeOnProtocol(self,
                                   portName,
                                   protocol,
                                   routeRange,
                                   enable=True):
        """
        Description
            Enable a route range for a protocol on a speficied port

        Parameters
            portName: <str>: Name of the port eg: "1/1/11"
            protocol: <str>: protocol to enable route range. eg: <OSPF|OSPFV3|BGP|ISIS|EIGRP|RIP|RIPng>
            routeRange: <str>: route range <IPv4|IPv6> address
            enable: <bool>: enable or disable route range, default is True (enable)

        Syntax
            PATCH: /api/v1/sessions/{id}/ixnetwork/vport/{id}/protocols/<protocol>/router/{id}/routeRange/{id}
            PATCH: /api/v1/sessions/{id}/ixnetwork/vport/{id}/protocols/<protocol>/neighborRange/{id}/routeRange/{id}

        Examples:
            enableRouteRangeOnProtocol(protName='1/1/11', protocol='ospf', routeRange='10.10.10.1')
            enableRouteRangeOnProtocol(protName='1/1/11', protocol='ospfv3', routeRange='10::1', enable=True)
        """
        vport = self.portMgmtObj.getVportObjectByName(portName)
        if vport == None:
            raise IxNetRestApiException(
                'PortName {0} not connected to chassis'.format(portName))

        RouterInstanceList = self.getRouterInstanceByPortAndProtocol(
            protocol=protocol, vport=vport)
        if RouterInstanceList == []:
            raise IxNetRestApiException(
                'No Router instance exists in protocol {0}'.format(protocol))

        args = 'firstRoute'
        if protocol == 'ospf':
            args = 'networkNumber'
        if protocol == 'bgp':
            args = 'networkAddress'

        for eachRouterInstance in RouterInstanceList:
            url = self.ixnObj.httpHeader + eachRouterInstance + '/routeRange'
            response = self.ixnObj.get(url)
            RouteRangeInstanceList = [
                "%s" % (str(i["links"][0]["href"])) for i in response.json()
            ]
            self.ixnObj.logInfo('Route Range list %s' % RouteRangeInstanceList)

            for eachRouteRange in RouteRangeInstanceList:
                url = self.ixnObj.httpHeader + eachRouteRange
                response = self.ixnObj.get(url)
                RouteRangeNetwork = response.json()[args]
                if RouteRangeNetwork == routeRange:
                    self.ixnObj.patch(url, data={"enabled": enable})
                    return
            raise IxNetRestApiException(
                'Route range: {0} does not exist in protocol: {1} port: {2}'.
                format(routeRange, protocol, portName))

    def removeRouteRangeOnProtocol(self, portName, protocol, routeRange):
        """
        Description
            Remove a route range for a protocol on a speficied port

        Parameters
            portName: <str>: Name of the port eg: "1/1/11"
            protocol: <str>: protocol to remove route range. eg: <OSPF|OSPFV3|BGP|ISIS|EIGRP|RIP|RIPng>
            routeRange: <str>: route range <IPv4|IPv6> address

        Syntax
            DELETE: /api/v1/sessions/{id}/ixnetwork/vport/{id}/protocols/<protocol>/router/{id}/routeRange/{id}
            DELETE: /api/v1/sessions/{id}/ixnetwork/vport/{id}/protocols/<protocol>/neighborRange/{id}/routeRange/{id}

        Examples:
            removeRouteRangeOnProtocol(protName='1/1/11', protocol='ospf', routeRange='10.10.10.1')
            removeRouteRangeOnProtocol(protName='1/1/11', protocol='ospfv3', routeRange='10::1')
        """
        vport = self.portMgmtObj.getVportObjectByName(portName)
        if vport == None:
            raise IxNetRestApiException(
                'PortName {0} not connected to chassis'.format(portName))

        RouterInstanceList = self.getRouterInstanceByPortAndProtocol(
            protocol=protocol, vport=vport)
        if RouterInstanceList == []:
            raise IxNetRestApiException(
                'No Router instance exists in protocol {0}'.format(protocol))

        self.ixnObj.logInfo('Router list %s' % RouterInstanceList)
        args = 'firstRoute'
        if protocol == 'ospf':
            args = 'networkNumber'
        if protocol == 'bgp':
            args = 'networkAddress'

        for eachRouterInstance in RouterInstanceList:
            url = self.ixnObj.httpHeader + eachRouterInstance + '/routeRange'
            response = self.ixnObj.get(url)
            RouteRangeInstanceList = [
                "%s" % (str(i["links"][0]["href"])) for i in response.json()
            ]
            self.ixnObj.logInfo('Route Range list %s' % RouteRangeInstanceList)
            for eachRouteRange in RouteRangeInstanceList:
                url = self.ixnObj.httpHeader + eachRouteRange
                response = self.ixnObj.get(url)
                RouteRangeNetwork = response.json()[args]
                if RouteRangeNetwork == routeRange:
                    self.ixnObj.delete(url)
                    return

            raise IxNetRestApiException(
                'Route range: {0} does not exist in protocol: {1} port: {2}'.
                format(routeRange, protocol, portName))

    def createRouteRangeOnProtocol(self, portName, protocol, routeRange):
        """
        Description
            Create a route range for a protocol on a speficied port

        Parameters
            portName: <str>: Name of the port eg: "1/1/11"
            protocol: <str>: protocol to create route range. eg: <OSPF|OSPFV3|BGP|ISIS|EIGRP|RIP|RIPng>
            routeRange: <dict>: route range to configure <IPv4|IPv6> address
            eg: {'enabled': 'True', 'mask': 24, 'numberOfRoutes': 5, 'networkNumber': '8.7.7.1', 'metric': 10, 'origin': 'externalType1'}
                {'enabled': 'True', 'maskWidth': 64, 'numberOfRoute': 10, 'firstRoute': '7::1', 'metric': 10, 'nextHop': '7::2'}

        Syntax
            POST: /api/v1/sessions/{id}/ixnetwork/vport/{id}/protocols/ospf/router/{id}/routeRange/{id}
            DATA: {'enabled': 'True', 'mask': 24, 'numberOfRoutes': 5, 'networkNumber': '7.7.7.1', 'metric': 10, 'origin': 'externalType1'}

            POST: /api/v1/sessions/{id}/ixnetwork/vport/{id}/protocols/ospfV3/router/{id}/routeRange/{id}
            DATA: {'enabled': 'True', 'mask': 64, 'numberOfRoutes': 5, 'firstRoute': '7::1', 'metric': 10, 'type': 'anotherArea', 'addressFamily': 'unicast'}

            POST: /api/v1/sessions/{id}/ixnetwork/vport/{id}/protocols/eigrp/router/{id}/routeRange/{id}
            DATA: {'enabled': 'True', 'mask': 24, 'numberOfRoutes': 10, 'firstRoute': '7.7.7.1', 'metric': 10, 'nextHop': '7.7.7.2'}

            POST: /api/v1/sessions/{id}/ixnetwork/vport/{id}/protocols/rip/router/{id}/routeRange/{id}
            DATA: {'enabled': 'True', 'maskWidth': 24, 'noOfRoutes': 10, 'firstRoute': '7.7.7.1', 'metric': 10, 'nextHop': '7.7.7.2'}

            POST: /api/v1/sessions/{id}/ixnetwork/vport/{id}/protocols/ripng/router/{id}/routeRange/{id}
            DATA: {'enabled': 'True', 'maskWidth': 64, 'numberOfRoute': 10, 'firstRoute': '7::1', 'metric': 10, 'nextHop': '7::2'}

            POST: /api/v1/sessions/{id}/ixnetwork/vport/{id}/protocols/bgp/neighborRange/{id}/routeRange/{id}
            DATA: {'enabled': 'True', 'fromPrefix': 24, 'thruPrefix': 24, 'numRoutes': 10, 'networkAddress': '7.7.7.7'}

            POST: /api/v1/sessions/{id}/ixnetwork/vport/{id}/protocols/bgp/neighborRange/{id}/routeRange/{id}
            DATA: {'enabled': 'True', 'fromPrefix': 64, 'thruPrefix': 64, 'numRoutes': 10, 'networkAddress': '7::1'}

        Examples
            createRouteRangeOnProtocol(portName='1/1/11', protocol='ospf', routeRange={'enabled': 'True', 'mask': 24,
                                                                         'numberOfRoutes': 5, 'networkNumber': '8.7.7.1',
                                                                         'metric': 10, 'origin': 'externalType1'}
            createRouteRangeOnProtocol(portName='1/1/11', protocol='ospf', routeRange={'networkNumber': '8.7.7.1'}

        """
        vport = self.portMgmtObj.getVportObjectByName(portName)
        if vport == None:
            raise IxNetRestApiException(
                'PortName {0} not connected to chassis'.format(portName))

        RouterInstanceList = self.getRouterInstanceByPortAndProtocol(
            protocol=protocol, vport=vport)
        if RouterInstanceList == []:
            raise IxNetRestApiException(
                'No Router instance exists in protocol {0}'.format(protocol))

        self.ixnObj.logInfo('Router list %s' % RouterInstanceList)
        #routeRange = ast.literal_eval(routeRange)
        for eachRouterInstance in RouterInstanceList:
            url = self.ixnObj.httpHeader + eachRouterInstance + '/routeRange'
            self.ixnObj.post(url, data=routeRange)

    def getRouterInstanceByPortAndProtocol(self, protocol, vport):
        """
        Description
            Get router instance for the specified protocol on a speficied vport

        Parameters
            protocol: <str>: protocol to get a router instance
            vport: <str>: vport instance eg: "/api/v1/sessions/1/ixnetwork/vport/1"

        Syntax
            GET: /api/v1/sessions/{id}/ixnetwork/vport/{id}/protocols/<protocol>/router
            GET: /api/v1/sessions/{id}/ixnetwork/vport/{id}/protocols/<protocol>/neighborRange
            GET: /api/v1/sessions/{id}/ixnetwork/vport/{id}/protocols/<protocol>/host
            GET: /api/v1/sessions/{id}/ixnetwork/vport/{id}/protocols/<protocol>/bridge
            GET: /api/v1/sessions/{id}/ixnetwork/vport/{id}/protocols/<protocol>/actor
            GET: /api/v1/sessions/{id}/ixnetwork/vport/{id}/protocols/<protocol>/neighborPair

        Examples
            getRouterInstanceByPortAndProtocol(protocol='ospf', vport='/api/v1/sessions/1/ixnetwork/vport/1')

        Return
            RouterInstanceList
            Returns [] if no router instance exists
        """
        if protocol == 'bgp':
            nextNode = '/neighborRange'
        elif protocol == 'igmp' or protocol == 'mld':
            nextNode = '/host'
        elif protocol == 'stp':
            nextNode = '/bridge'
        elif protocol == 'rsvp':
            nextNode = '/neighborPair'
        elif protocol == 'lacp':
            nextNode = '/link'
        else:
            nextNode = '/router'
        url = vport + '/protocols/' + protocol + nextNode
        response = self.ixnObj.get(url)
        RouterInstanceList = [
            "%s" % (str(i["links"][0]["href"])) for i in response.json()
        ]
        self.ixnObj.logInfo('Router Instance list %s' % RouterInstanceList)
        return RouterInstanceList

    def verifyProtocolSessionsUp(self,
                                 protocolViewName='BGP Peer Per Port',
                                 timeout=60):
        """
        Description
            Verify the specified protocol sessions are UP or not.

        Parameters
            protocolViewName: <str>: The protocol view name. Get this name from API browser or in IxNetwork GUI statistic tabs.
            timeout: <int>: Duration to wait for the protocol sessions to up. Default = 60 seconds.

        protocolViewName options:
            'BFD Aggregated Statistics'
            'BGP Aggregated Statistics'
            'ISIS Aggregated Statistics'
            'OSPF Aggregated Statistics'
            'RIPng Aggregated Statistics'
            'RIP Aggregated Statistics'
            'LDP Aggregated Statistics'
            'PIMSM Aggregated Statistics'
            'MPLSOAM Aggregated Statistics'

        Examples
            verifyProtocolSessionsUp(protcolViewName='ospf Aggregated Statistics')
            verifyProtocolSessionsUp(protcolViewName='ospf Aggregated Statistics',timeout=90)
        """
        totalSessionsDetectedUp = 0
        totalSessionsDetectedDown = 0
        totalPortsUpFlag = 0
        self.ixnObj.logInfo('Protocol view name %s' % protocolViewName)
        time.sleep(10)
        for counter in range(1, timeout + 1):
            stats = self.statObj.getStats(viewName=protocolViewName,
                                          displayStats=False)
            totalPorts = len(
                stats.keys())  # Length stats.keys() represents total ports.
            self.ixnObj.logInfo('ProtocolName: {0}'.format(protocolViewName))
            for session in stats.keys():
                if re.search('OSPF', protocolViewName, re.I):
                    sessionsUp = int(stats[session]['Full Nbrs.'])
                    totalSessions = int(stats[session]['Sess. Configured'])
                elif re.search('BGP', protocolViewName, re.I):
                    sessionsUp = int(stats[session]['Sess. Up'])
                    totalSessions = int(stats[session]['Sess. Configured'])
                elif re.search('ISIS', protocolViewName, re.I):
                    sessionsUp = int(stats[session]['L2 Sess. Up'])
                    totalSessions = int(stats[session]['L2 Sess. Configured'])
                elif re.search('RIPng', protocolViewName, re.I) or re.search(
                        'BFD', protocolViewName, re.I):
                    sessionsUp = int(stats[session]['Routers Running'])
                    totalSessions = int(stats[session]['Routers Configured'])
                elif re.search('RIP', protocolViewName, re.I):
                    sessionsUp = int(stats[session]['Request Packet Tx'])
                    totalSessions = int(stats[session]['Routers Configured'])
                elif re.search('LACP', protocolViewName, re.I):
                    sessionsUp = int(stats[session]['LAG Member Ports UP'])
                    totalSessions = int(
                        stats[session]['Total LAG Member Ports'])
                elif re.search('LDP', protocolViewName, re.I):
                    sessionsUp = int(stats[session]['Targeted Sess. Up'])
                    totalSessions = int(
                        stats[session]['Targeted Sess. Configured'])
                elif re.search('MPLS', protocolViewName, re.I):
                    sessionsUp = int(stats[session]['BFD Up-Sessions'])
                    totalSessions = int(stats[session]['BFD Session Count'])
                elif re.search('PIM', protocolViewName, re.I):
                    sessionsUp = int(stats[session]['Rtrs. Running'])
                    totalSessions = int(stats[session]['Rtrs. Configured'])
                # totalSessionsNotStarted = int(stats[session]['Sessions Not Started'])
                totalExpectedSessionsUp = totalSessions

                if totalExpectedSessionsUp != 0:
                    self.ixnObj.logInfo(
                        '\n\tPortName: {0}\n\t   TotalSessionsUp: {1}\n\t   ExpectedTotalSessionsup: {2}'
                        .format(stats[session]['Port Name'], sessionsUp,
                                totalExpectedSessionsUp),
                        timestamp=False)
                    if counter < timeout and sessionsUp != totalExpectedSessionsUp:
                        self.ixnObj.logInfo(
                            '\t   Protocol Session is still down',
                            timestamp=False)

                    if counter < timeout and sessionsUp == totalExpectedSessionsUp:
                        totalPortsUpFlag += 1
                        if totalPortsUpFlag == totalPorts:
                            self.ixnObj.logInfo(
                                'All protocol sessions are up!')
                            return

            if counter == timeout and sessionsUp != totalExpectedSessionsUp:
                raise IxNetRestApiException(
                    'Protocol Sessions failed to come up')

            self.ixnObj.logInfo('\n\tWait {0}/{1} seconds\n'.format(
                counter, timeout),
                                timestamp=False)
            time.sleep(1)

    def verifyAllConfiguredProtocolSessions(self, duration):
        """
        Description
            verify all configured protocol sessions are UP or not

        Parameters
            duration: <int>: duration to wait for the protocol sessions to UP

        Examples
            verifyAllConfiguredProtocolSessions(duration=120)
            verifyAllConfiguredProtocolSessions(120)
        """
        response = self.getConfiguredProtocols()
        if response == []:
            raise IxNetRestApiException(
                'No protocols Running or Configured or Enabled')

        for eachProtocol in response:
            if re.search('ospf', eachProtocol, re.I):
                viewName = 'OSPF Aggregated Statistics'
            elif re.search('ospfV3', eachProtocol, re.I):
                viewName = 'OSPFv3 Aggregated Statistics'
            elif re.search('bgp', eachProtocol, re.I):
                viewName = 'BGP Aggregated Statistics'
            elif re.search('isis', eachProtocol, re.I):
                viewName = 'ISIS Aggregated Statistics'
            elif re.search('ripng', eachProtocol, re.I):
                viewName = 'RIPng Aggregated Statistics'
            elif re.search('bfd', eachProtocol, re.I):
                viewName = 'BFD Aggregated Statistics'
            elif re.search('rip', eachProtocol, re.I):
                viewName = 'RIP Aggregated Statistics'
            elif re.search('ldp', eachProtocol, re.I):
                viewName = 'LDP Aggregated Statistics'
            elif re.search('mplsoam', eachProtocol, re.I):
                viewName = 'MPLSOAM Aggregated Statistics'
            elif re.search('pim', eachProtocol, re.I):
                viewName = 'PIMSM Aggregated Statistics'
            else:
                raise IxNetRestApiException('No viewName defined')

            self.verifyProtocolSessionsUp(protocolViewName=viewName,
                                          timeout=duration)
Esempio n. 6
0
def main():
    logging.basicConfig(filename='../ansible.log', level=logging.DEBUG)

    # Define the available arguments/parameters that a user can pass to this module.
    params = {
        'osPlatform': {
            'type': 'str',
            'required': False,
            'default': 'windows',
            'choices': ['windows', 'windowsConnectionMgr', 'linux']
        },
        'forceTakePortOwnership': {
            'type': 'bool',
            'required': False,
            'default': True
        },
        'releasePortsWhenDone': {
            'type': 'bool',
            'required': False,
            'default': False
        },
        'enableDebugTracing': {
            'type': 'bool',
            'required': False,
            'default': True
        },
        'deleteSessionAfterTest': {
            'type': 'bool',
            'required': False,
            'default': True
        },
        'ixChassisIp': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'portList': {
            'type': 'list',
            'required': True,
            'default': None
        },
        'apiServerIp': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'apiServerIpPort': {
            'type': 'int',
            'required': False,
            'default': 11009
        },
        'configLicense': {
            'type': 'str',
            'required': False,
            'default': 'True',
            'no_log': False
        },
        'linuxUsername': {
            'type': 'str',
            'required': False,
            'default': 'admin',
            'no_log': False
        },
        'linuxPassword': {
            'type': 'str',
            'required': False,
            'default': 'password',
            'no_log': False
        },
        'licenseServerIp': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'licenseMode': {
            'type': 'str',
            'required': False,
            'default': 'subscription'
        },
        'licenseTier': {
            'type': 'str',
            'required': False,
            'default': 'tier3'
        },
        'topologyGroup1Name': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'topologyGroup1Ports': {
            'type': 'list',
            'required': True,
            'default': None
        },
        'topologyGroup2Name': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'topologyGroup2Ports': {
            'type': 'list',
            'required': True,
            'default': None
        },
        'deviceGroup1Name': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'deviceGroup1Multiplier': {
            'type': 'int',
            'required': False,
            'default': 1
        },
        'deviceGroup2Name': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'deviceGroup2Multiplier': {
            'type': 'int',
            'required': False,
            'default': 1
        },
        'ethernet1Name': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'ethernet1MacAddress': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'ethernet1MacDirection': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'ethernet1MacStep': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'ethernet1MacPortStep': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'ethernet1VlanId': {
            'type': 'int',
            'required': True,
            'default': None
        },
        'ethernet1VlanIdDirection': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'ethernet1VlanIdStep': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'ethernet2Name': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'ethernet2MacAddress': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'ethernet2MacDirection': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'ethernet2MacStep': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'ethernet2MacPortStep': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'ethernet2VlanId': {
            'type': 'int',
            'required': True,
            'default': None
        },
        'ethernet2VlanIdDirection': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'ethernet2VlanIdStep': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'ipv41Address': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'ipv41AddressDirection': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'ipv41AddressStep': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'ipv41AddressPortStep': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'ipv41Gateway': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'ipv41GatewayDirection': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'ipv41GatewayStep': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'ipv41GatewayPortStep': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'ipv41AddressPrefix': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'ipv41ResolveGateway': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'ipv42Address': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'ipv42AddressDirection': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'ipv42AddressStep': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'ipv42AddressPortStep': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'ipv42Gateway': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'ipv42GatewayDirection': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'ipv42GatewayStep': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'ipv42GatewayPortStep': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'ipv42AddressPrefix': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'ipv42ResolveGateway': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'bgp1Name': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'bgp1Enable': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'bgp1HoldTimer': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'bgp1DutIp': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'bgp1DutIpDirection': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'bgp1DutIpStep': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'bgp1LocalAsBytes': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'bgp1EnableGracefulRestart': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'bgp1RestartTime': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'bgp1Type': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'bgp2Name': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'bgp2Enable': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'bgp2HoldTimer': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'bgp2DutIp': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'bgp2DutIpDirection': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'bgp2DutIpStep': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'bgp2LocalAsBytes': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'bgp2EnableGracefulRestart': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'bgp2RestartTime': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'bgp2Type': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'networkGroup1Name': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'networkGroup1Multiplier': {
            'type': 'int',
            'required': True,
            'default': None
        },
        'networkGroup1Address': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'networkGroup1AddressStep': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'networkGroup1AddressDirection': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'networkGroup1PrefixLength': {
            'type': 'int',
            'required': True,
            'default': None
        },
        'networkGroup2Name': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'networkGroup2Multiplier': {
            'type': 'int',
            'required': True,
            'default': None
        },
        'networkGroup2Address': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'networkGroup2AddressStep': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'networkGroup2AddressDirection': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'networkGroup2PrefixLength': {
            'type': 'int',
            'required': True,
            'default': None
        },
        'trafficItemName': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'trafficItemType': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'trafficItemBiDirection': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'trafficItemSrcDestMesh': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'trafficItemRouteMesh': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'trafficItemAllowSelfDestined': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'trafficItemTrackBy': {
            'type': 'list',
            'required': True,
            'default': None
        },
        'endpointName': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'transmissionType': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'frameCount': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'frameRate': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'frameRateType': {
            'type': 'str',
            'required': True,
            'default': None
        },
        'frameSize': {
            'type': 'str',
            'required': True,
            'default': None
        },
    }

    # seed the result dict in the object
    # we primarily care about changed and state
    # change is if this module effectively modified the target
    # state will include any data that you want your module to pass back
    # for consumption, for example, in a subsequent task
    result = dict(changed=False, original_message='', message='')

    # the AnsibleModule object will be our abstraction working with Ansible
    # this includes instantiation, a couple of common attr would be the
    # args/params passed to the execution, as well as if the module
    # supports check mode
    module = AnsibleModule(argument_spec=params, supports_check_mode=False)

    # if the user is working with this module in only check mode we do not
    # want to make any changes to the environment, just return the current
    # state with no modifications
    #if module.check_mode:
    #    return result

    module.params['name'] = 'Custom Ansible  module for BGP configuration'
    result['Result'] = 'Passed'

    # Default the API server to either windows or linux.
    osPlatform = module.params['osPlatform']

    if module.params['osPlatform'] not in [
            'windows', 'windowsConnectionMgr', 'linux'
    ]:
        raise IxNetRestApiException(
            "\nError: %s is not a known option. Choices are 'windows' or 'linux'."
            % module.params['osPlatform'])

    try:
        #---------- Preference Settings --------------

        forceTakePortOwnership = module.params['forceTakePortOwnership']
        releasePortsWhenDone = module.params['releasePortsWhenDone']
        enableDebugTracing = module.params['enableDebugTracing']
        deleteSessionAfterTest = module.params['deleteSessionAfterTest']
        # For Windows Connection Mgr and Linux API server only

        ixChassisIp = module.params['ixChassisIp']
        # [chassisIp, cardNumber, slotNumber]
        portList = module.params['portList']

        if module.params['osPlatform'] == 'linux':
            mainObj = Connect(
                apiServerIp=module.params['apiServerIp'],
                serverIpPort=module.params['apiSeverIpPort'],
                username=module.params['linuxUsername'],
                password=module.params['linuxPassword'],
                deleteSessionAfterTest=module.params['deleteSessionAfterTest'],
                verifySslCert=False,
                serverOs=module.params['osPlatform'])

        if module.params['osPlatform'] in ['windows', 'windowsConnectionMgr']:
            mainObj = Connect(
                apiServerIp=module.params['apiServerIp'],
                serverIpPort=module.params['apiServerIpPort'],
                serverOs=module.params['osPlatform'],
                deleteSessionAfterTest=module.params['deleteSessionAfterTest'])

        #---------- Preference Settings End --------------

        portObj = PortMgmt(mainObj)
        portObj.connectIxChassis(module.params['ixChassisIp'])

        if portObj.arePortsAvailable(module.params['portList'],
                                     raiseException=False) != 0:
            if module.params['forceTakePortOwnership'] == True:
                portObj.releasePorts(module.params['portList'])
                portObj.clearPortOwnership(module.params['portList'])
            else:
                raise IxNetRestApiException(
                    'Ports are owned by another user and forceTakePortOwnership is set to False'
                )

        mainObj.newBlankConfig()

        if module.params['configLicense'] == True:
            portObj.releaseAllPorts()
            mainObj.configLicenseServerDetails(
                [module.params['licenseServerIp']],
                module.params['licenseMode'], module.params['licenseTier'])

        # Set createVports = True if building config from scratch.
        portObj.assignPorts(module.params['portList'])

        protocolObj = Protocol(mainObj)
        topologyObj1 = protocolObj.createTopologyNgpf(
            portList=[module.params['topologyGroup1Ports']],
            topologyName=module.params['topologyGroup1Name'])

        deviceGroupObj1 = protocolObj.createDeviceGroupNgpf(
            topologyObj1,
            multiplier=module.params['deviceGroup1Multiplier'],
            deviceGroupName=module.params['deviceGroup1Name'])

        topologyObj2 = protocolObj.createTopologyNgpf(
            portList=[module.params['topologyGroup2Ports']],
            topologyName=module.params['topologyGroup2Name'])

        deviceGroupObj2 = protocolObj.createDeviceGroupNgpf(
            topologyObj2,
            multiplier=module.params['deviceGroup2Multiplier'],
            deviceGroupName=module.params['deviceGroup2Name'])

        ethernetObj1 = protocolObj.configEthernetNgpf(
            deviceGroupObj1,
            ethernetName=module.params['ethernet1Name'],
            macAddress={
                'start': module.params['ethernet1MacAddress'],
                'direction': module.params['ethernet1MacDirection'],
                'step': module.params['ethernet1MacStep']
            },
            macAddressPortStep=module.params['ethernet1MacPortStep'],
            vlanId={
                'start': module.params['ethernet1VlanId'],
                'direction': module.params['ethernet1VlanIdDirection'],
                'step': module.params['ethernet1VlanIdStep']
            })

        ethernetObj2 = protocolObj.configEthernetNgpf(
            deviceGroupObj2,
            ethernetName=module.params['ethernet2Name'],
            macAddress={
                'start': module.params['ethernet2MacAddress'],
                'direction': module.params['ethernet2MacDirection'],
                'step': module.params['ethernet2MacStep']
            },
            macAddressPortStep=module.params['ethernet2MacPortStep'],
            vlanId={
                'start': module.params['ethernet2VlanId'],
                'direction': module.params['ethernet2VlanIdDirection'],
                'step': module.params['ethernet2VlanIdStep']
            })

        ipv4Obj1 = protocolObj.configIpv4Ngpf(
            ethernetObj1,
            ipv4Address={
                'start': module.params['ipv41Address'],
                'direction': module.params['ipv41AddressDirection'],
                'step': module.params['ipv41AddressStep']
            },
            ipv4AddressPortStep=module.params['ipv41AddressPortStep'],
            gateway={
                'start': module.params['ipv41Gateway'],
                'direction': module.params['ipv41GatewayDirection'],
                'step': module.params['ipv41GatewayStep']
            },
            gatewayPortStep=module.params['ipv41GatewayPortStep'],
            prefix=module.params['ipv41AddressPrefix'],
            resolveGateway=module.params['ipv41ResolveGateway'])

        ipv4Obj2 = protocolObj.configIpv4Ngpf(
            ethernetObj2,
            ipv4Address={
                'start': module.params['ipv42Address'],
                'direction': module.params['ipv42AddressDirection'],
                'step': module.params['ipv42AddressStep']
            },
            ipv4AddressPortStep=module.params['ipv42AddressPortStep'],
            gateway={
                'start': module.params['ipv42Gateway'],
                'direction': module.params['ipv42GatewayDirection'],
                'step': module.params['ipv42GatewayStep']
            },
            gatewayPortStep=module.params['ipv42GatewayPortStep'],
            prefix=module.params['ipv42AddressPrefix'],
            resolveGateway=module.params['ipv42ResolveGateway'])

        # flap = true or false.
        #    If there is only one host IP interface, then single value = True or False.
        #    If there are multiple host IP interfaces, then single value = a list ['true', 'false']
        #           Provide a list of total true or false according to the total amount of host IP interfaces.
        bgpObj1 = protocolObj.configBgp(
            ipv4Obj1,
            name=module.params['bgp1Name'],
            enableBgp=module.params['bgp1Enable'],
            holdTimer=module.params['bgp1HoldTimer'],
            dutIp={
                'start': module.params['bgp1DutIp'],
                'direction': module.params['bgp1DutIpDirection'],
                'step': module.params['bgp1DutIpStep']
            },
            localAs2Bytes=module.params['bgp1LocalAsBytes'],
            enableGracefulRestart=module.params['bgp1EnableGracefulRestart'],
            restartTime=module.params['bgp1RestartTime'],
            type=module.params['bgp1Type'])

        bgpObj2 = protocolObj.configBgp(
            ipv4Obj2,
            name=module.params['bgp2Name'],
            enableBgp=module.params['bgp2Enable'],
            holdTimer=module.params['bgp2HoldTimer'],
            dutIp={
                'start': module.params['bgp2DutIp'],
                'direction': module.params['bgp2DutIpDirection'],
                'step': module.params['bgp2DutIpStep']
            },
            localAs2Bytes=module.params['bgp2LocalAsBytes'],
            enableGracefulRestart=module.params['bgp2EnableGracefulRestart'],
            restartTime=module.params['bgp2RestartTime'],
            type=module.params['bgp2Type'])

        networkGroupObj1 = protocolObj.configNetworkGroup(
            create=deviceGroupObj1,
            name=module.params['networkGroup1Name'],
            multiplier=module.params['networkGroup1Multiplier'],
            networkAddress={
                'start': module.params['networkGroup1Address'],
                'step': module.params['networkGroup1AddressStep'],
                'direction': module.params['networkGroup1AddressDirection']
            },
            prefixLength=module.params['networkGroup1PrefixLength'])

        networkGroupObj2 = protocolObj.configNetworkGroup(
            create=deviceGroupObj2,
            name=module.params['networkGroup2Name'],
            multiplier=module.params['networkGroup2Multiplier'],
            networkAddress={
                'start': module.params['networkGroup2Address'],
                'step': module.params['networkGroup2AddressStep'],
                'direction': module.params['networkGroup2AddressDirection']
            },
            prefixLength=module.params['networkGroup2PrefixLength'])

        protocolObj.startAllProtocols()
        protocolObj.verifyProtocolSessionsNgpf()

        # For all parameter options, go to the API configTrafficItem.
        # mode = create or modify
        trafficObj = Traffic(mainObj)
        trafficStatus = trafficObj.configTrafficItem(
            mode='create',
            trafficItem={
                'name': module.params['trafficItemName'],
                'trafficType': module.params['trafficItemType'],
                'biDirectional': module.params['trafficItemBiDirection'],
                'srcDestMesh': module.params['trafficItemSrcDestMesh'],
                'routeMesh': module.params['trafficItemRouteMesh'],
                'allowSelfDestined':
                module.params['trafficItemAllowSelfDestined'],
                'trackBy': module.params['trafficItemTrackBy']
            },
            endpoints=[{
                'name': module.params['endpointName'],
                'sources': [topologyObj1],
                'destinations': [topologyObj2]
            }],
            configElements=[{
                'transmissionType':
                module.params['transmissionType'],
                'frameCount':
                module.params['frameCount'],
                'frameRate':
                module.params['frameRate'],
                'frameRateType':
                module.params['frameRateType'],
                'frameSize':
                module.params['frameSize']
            }])

        trafficItemObj = trafficStatus[0]
        endpointObj = trafficStatus[1][0]
        configElementObj = trafficStatus[2][0]

        trafficObj.startTraffic(regenerateTraffic=True, applyTraffic=True)

        # Check the traffic state before getting stats.
        #    Use one of the below APIs based on what you expect the traffic state should be before calling stats.
        #    'stopped': If you expect traffic to be stopped such as for fixedFrameCount and fixedDuration.
        #    'started': If you expect traffic to be started such as in continuous mode.
        trafficObj.checkTrafficState(expectedState=['stopped'], timeout=45)
        #trafficObj.checkTrafficState(expectedState=['started'], timeout=45)

        statObj = Statistics(mainObj)
        stats = statObj.getStats(viewName='Flow Statistics')

        print(
            '\n{txPort:10} {txFrames:15} {rxPort:10} {rxFrames:15} {frameLoss:10}'
            .format(txPort='txPort',
                    txFrames='txFrames',
                    rxPort='rxPort',
                    rxFrames='rxFrames',
                    frameLoss='frameLoss'))
        print('-' * 90)

        for flowGroup, values in stats.items():
            txPort = values['Tx Port']
            rxPort = values['Rx Port']
            txFrames = values['Tx Frames']
            rxFrames = values['Rx Frames']
            frameLoss = values['Frames Delta']

            print(
                '{txPort:10} {txFrames:15} {rxPort:10} {rxFrames:15} {frameLoss:10} '
                .format(txPort=txPort,
                        txFrames=txFrames,
                        rxPort=rxPort,
                        rxFrames=rxFrames,
                        frameLoss=frameLoss))

        if module.params['releasePortsWhenDone'] == True:
            portObj.releasePorts(module.params['portList'])

        if module.params['osPlatform'] == 'linux':
            mainObj.linuxServerStopAndDeleteSession()

        if module.params['osPlatform'] == 'windowsConnectionMgr':
            mainObj.deleteSession()

        # Tell Ansible test passed
        #result['changed'] = True
        #module.exit_json(changed=True, test='Passed')
        module.exit_json(BGP_Configuration='Passed')

    except (IxNetRestApiException, Exception, KeyboardInterrupt) as errMsg:
        module.fail_json(msg=errMsg, **result)

        if module.params['enableDebugTracing']:
            if not bool(re.search('ConnectionError', traceback.format_exc())):
                logging.ERROR('\n%s' % traceback.format_exc())
                module.fail_json(changed=True, meta=traceback.format_exc())
                #exitArgs = {'module_stderr': traceback.format_exc()}
                #module.exit_json(**exitArgs)

        logging.ERROR('\nException Error! %s\n' % errMsg)
        if 'mainObj' in locals() and module.params['osPlatform'] == 'linux':
            mainObj.linuxServerStopAndDeleteSession()

        if 'mainObj' in locals() and module.params['osPlatform'] in [
                'windows', 'windowsConnectionMgr'
        ]:
            if releasePortsWhenDone and forceTakePortOwnership:
                portObj.releasePorts(module.params['portList'])
            if module.params['osPlatform'] == 'windowsConnectionMgr':
                mainObj.deleteSession()
Esempio n. 7
0
class ClassicProtocol(object):
    def __init__(self, ixnObj=None):
        """
        Parameters
           ixnObj: <str>: The main connection object.
        """
        self.ixnObj = ixnObj
        self.ixNetwork = ixnObj.ixNetwork
        self.portMgmtObj = PortMgmt(self.ixnObj)
        self.statObj = Statistics(self.ixnObj)

    def getPortsByProtocol(self, protocolName):
        """
        Description
            Based on the specified protocol, return all ports associated with the protocol.

        Parameters
           protocolName options:
              bfd, bgp, cfm, eigrp, elmi, igmp, isis, lacp, ldp, linkOam, lisp, mld, mplsOam,
              mplsTp, openFlow, ospf, ospfV3, pimsm, ping, rip, ripng, rsvp, static, stp

        Returns: [chassisIp, cardNumber, portNumber]
                  Example: [['192.168.70.11', '1', '1'],['192.168.70.11', '1', '2']]

        Returns [] if no port is configured with the specified protocolName
        """
        portList = []
        vportList = self.ixNetwork.Vport.find()
        for vport in vportList:
            protocol = protocolName[0].capitalize() + protocolName[1:]
            protocolObj = getattr(vport.Protocols.find(), protocol)
            if protocolObj.Enabled:
                assignedTo = vport.AssignedTo
                currentChassisIp = assignedTo.split(':')[0]
                currentCardNumber = assignedTo.split(':')[1]
                currentPortNumber = assignedTo.split(':')[2]
                currentPort = [
                    currentChassisIp, currentCardNumber, currentPortNumber
                ]
                portList.append(currentPort)
        return portList

    def getProtocolListByPort(self, port):
        """
        Description
            Get all enabled protocols by the specified port.

        Parameters
            port: [chassisIp, cardNumber, portNumber] ->['192.168.70.11', '2', '8']
        """
        self.ixnObj.logInfo('\ngetProtocolListByPort...')
        protocolList = [
            'bfd', 'bgp', 'cfm', 'eigrp', 'elmi', 'igmp', 'isis', 'lacp',
            'ldp', 'linkOam', 'lisp', 'mld', 'mplsOam', 'mplsTp', 'openFlow',
            'ospf', 'ospfV3', 'pimsm', 'ping', 'rip', 'ripng', 'rsvp', 'stp'
        ]
        self.ixnObj.logInfo('\ngetProtocolListByPort...')
        chassis = str(port[0])
        card = str(port[1])
        port = str(port[2])
        portObj = chassis + ":" + card + ":" + port
        enabledProtocolList = []
        vport = self.ixNetwork.Vport.find(AssignedTo=portObj)
        for protocol in protocolList:
            currentProtocol = protocol[0].capitalize() + protocol[1:]
            protocolObj = getattr(vport.Protocols.find(), currentProtocol)
            if protocolObj.Enabled:
                enabledProtocolList.append(str(protocol))
        return enabledProtocolList

    def sendArpOnPort(self, portName):
        """
        Description
            Send Arp request on a specified port

        Parameters
            portName: <str>: Name of the port. eg: '1/1/11'

        Examples
            sendArpOnPort(portName='1/1/11')
        """
        vport = self.portMgmtObj.getVportObjectByName(portName)
        if vport is None:
            raise IxNetRestApiException(
                'PortName {0} not connected to chassis'.format(portName))
        vport.SendArp()

    def getDiscoverdNeighborOnPort(self, portName):
        """
        Description
            Get Arp discovered neighbor on a specified port

        Parameters
            portName: <str>: Name of the port. eg: '1/1/11'

        Examples
            getDiscoverdNeighborOnPort(portName='1/1/11')

        Return
            Discovered mac address
        """
        vport = self.portMgmtObj.getVportObjectByName(portName)
        if vport is None:
            raise IxNetRestApiException(
                'PortName {0} not connected to chassis'.format(portName))
        discoveredNeighborMac = vport.DiscoveredNeighbor.find().NeighborMac
        self.ixnObj.logInfo('Discovered Neighbor: %s' % discoveredNeighborMac)
        return discoveredNeighborMac

    def startStopProtocolOnPort(self, protocol, portName, action='start'):
        """
        Description
            Start and stop a protocol on a specified port

        Parameters
            protocol: <str>: Protocol to start
            portName: <str>: Name of the port, eg: '1/1/11'
            action: <str>: start or stop a protocol, default is start

        Examples
            startStopProtocolOnPort(protocol='ospf', portName='1/1/11')
            startStopProtocolOnPort(protocol='ospf', portName='1/1/11', action='stop')
        """
        vport = self.portMgmtObj.getVportObjectByName(portName)
        if vport is None:
            raise IxNetRestApiException(
                'PortName {0} not connected to chassis'.format(portName))
        protocol = protocol[0].capitalize() + protocol[1:]
        protocolObj = getattr(vport.Protocols.find(), protocol)
        if action == "start":
            protocolObj.Start()
        if action == "stop":
            protocolObj.Stop()

    def getConfiguredProtocols(self):
        """
        Description
            Get the list of protocols configured on vports.

        Return
            A list or one or more congfigured protocols eg: "['ospf','bgp']"
            return [] if no protocol is configured
        """
        configuredProtocolList = []
        availableProtocolList = [
            'bfd', 'bgp', 'cfm', 'eigrp', 'elmi', 'igmp', 'isis', 'lacp',
            'ldp', 'linkOam', 'lisp', 'mld', 'mplsOam', 'mplsTp', 'openFlow',
            'ospf', 'ospfV3', 'pimsm', 'ping', 'rip', 'ripng', 'rsvp', 'stp'
        ]
        vportList = self.ixNetwork.Vport.find()
        if not vportList:
            raise IxNetRestApiException('No ports connected to chassis')

        protocolNextNodeDict = {
            'bgp': 'NeighborRange',
            'igmp': 'Host',
            'mld': 'Host',
            'stp': 'Bridge',
            'cfm': 'Bridge',
            'rsvp': 'NeighborPair',
            'lacp': 'Link',
            'linkOam': 'Link',
            'elmi': 'Uni',
            'openFlow': 'Device'
        }
        protocols = [
            'bgp', 'igmp', 'mld', 'stp', 'cfm', 'rsvp', 'lacp', 'linkOam',
            'elmi', 'openFlow'
        ]
        for eachVport in vportList:
            for protocol in availableProtocolList:
                if protocol in protocols:
                    nextNode = protocolNextNodeDict[protocol]
                else:
                    nextNode = 'Router'
                protocol = protocol[0].capitalize() + protocol[1:]
                protocolResponse = getattr(eachVport.Protocols.find(),
                                           protocol)
                nextNodeObj = getattr(protocolResponse, nextNode)
                routerInstancesObj = nextNodeObj.find()
                if routerInstancesObj:
                    if routerInstancesObj.Enabled and protocolResponse.RunningState == 'started':
                        configuredProtocolList.append(protocol)
        configuredProtocolList = list(set(configuredProtocolList))
        return configuredProtocolList

    def enableProtocolOnPort(self, protocol, portName, enable=True):
        """
        Description
           Enable protocol on a speficied port

        Parameters
            protocol: <str>: Protocol to start
            portName: <str>: Name of the port eg: '1/1/11'
            enable: <bool> enable or disable specified protocol.

        Examples
            enableProtocolOnPort(protocol='ospf', portName='1/1/11')
            enableProtocolOnPort(protocol='ospf', portName='1/1/11', enable=False)
        """
        vport = self.portMgmtObj.getVportObjectByName(portName)
        if vport is None:
            raise IxNetRestApiException(
                'PortName {0} not connected to chassis'.format(portName))

        RouterInstanceList = self.getRouterInstanceByPortAndProtocol(
            protocol=protocol, vport=vport)
        if not RouterInstanceList:
            raise IxNetRestApiException(
                'No Router instance exists in protocol {0}'.format(protocol))
        for eachRouterInstance in RouterInstanceList:
            eachRouterInstance.Enabled = enable

    def getProtocolSessionsStats(self, portName, protocol):
        """
        Description
            Get a protocol session status for a specified protocol on a port

        Parameters
            portName: <str>: Name of the Port eg: "1/1/11"
            protocol: <str>: Name of the protocol. eg: <ospf/ospfV3/bgp/isis/ripng/bfd/rip/ldp/pim>

        Examples
            getProtocolSessionsStats(portName='1/1/11', protocol='ospf')

        Return
            Protocol stats in dictionary format eg: {'ospf': {'Configured': 2, 'Up': 1}}
        """
        protocolStats = {}
        vport = self.portMgmtObj.getVportObjectByName(portName)
        if vport is None:
            raise IxNetRestApiException(
                'PortName {0} not connected to chassis'.format(portName))
        protocolNextNodeDict = {
            'bgp': 'NeighborRange',
            'igmp': 'Host',
            'mld': 'Host',
            'stp': 'Bridge',
            'cfm': 'Bridge',
            'rsvp': 'NeighborPair',
            'lacp': 'Link',
            'linkOam': 'Link',
            'elmi': 'Uni',
            'openFlow': 'Device'
        }
        protocols = [
            'bgp', 'igmp', 'mld', 'stp', 'cfm', 'rsvp', 'lacp', 'linkOam',
            'elmi', 'openFlow'
        ]
        if protocol in protocols:
            nextNode = protocolNextNodeDict[protocol]
        else:
            nextNode = 'Router'
        protocol = protocol[0].capitalize() + protocol[1:]
        protocolResponse = getattr(vport.Protocols.find(), protocol)
        nextNodeObj = getattr(protocolResponse, nextNode)
        routerInstancesObj = nextNodeObj.find()

        if routerInstancesObj:
            if routerInstancesObj.Enabled and (
                    protocolResponse.RunningState == 'started'
                    or protocolResponse.ProtocolState == 'started'):
                if protocol in [
                        'Bfd', 'Bgp', 'Cfm', 'Eigrp', 'Elmi', 'Igmp', 'Isis',
                        'Lacp', 'Ldp', 'Lisp', 'Mld', 'MplsTp', 'MplsOam',
                        'Ospf', 'Rip', 'Rsvp', 'Stp'
                ]:
                    protocolViewName = protocol.upper(
                    ) + 'Aggregated Statistics'
                elif re.search('LinkOam', protocol, re.I):
                    protocolViewName = 'OAM Aggregated Statistics'
                elif re.search('openFlow', protocol, re.I):
                    protocolViewName = 'OpenFlow Switch Aggregated Statistics'
                elif re.search('OspfV3', protocol, re.I):
                    protocolViewName = 'OSPFv3 Aggregated Statistics'
                elif re.search('Pim', protocol, re.I):
                    protocolViewName = 'PIMSM Aggregated Statistics'
                elif re.search('Ripng', protocol, re.I):
                    protocolViewName = 'RIPng Aggregated Statistics'
                else:
                    raise IxNetRestApiException('No viewName defined')
            else:
                raise IxNetRestApiException(
                    'No {0} protocol running or enabled on port {1}'.format(
                        protocol, portName))
        else:
            raise IxNetRestApiException(
                'No {0} protocol configured on port {1}'.format(
                    protocol, portName))

        stats = self.statObj.getStats(viewName=protocolViewName,
                                      displayStats=False)
        self.ixnObj.logInfo('ProtocolViewName: {0}'.format(protocolViewName))
        for session in stats.keys():
            if re.search('BFD', protocolViewName, re.I) or re.search(
                    'RIPng', protocolViewName, re.I):
                sessionsUp = int(stats[session]['Routers Running'])
                totalSessions = int(stats[session]['Routers Configured'])
            elif re.search('BGP', protocolViewName, re.I):
                sessionsUp = int(stats[session]['Sess. Up'])
                totalSessions = int(stats[session]['Sess. Configured'])
            elif re.search('CFM', protocolViewName, re.I):
                sessionsUp = int(stats[session]['Bridges Running'])
                totalSessions = int(stats[session]['Bridges Configured'])
            elif re.search('EIGRP', protocolViewName, re.I) or re.search(
                    'ELMI', protocolViewName, re.I):
                sessionsUp = int(stats[session]['IPv4 Routers Running'])
                totalSessions = int(stats[session]['IPv4 Routers Configured'])
            elif re.search('IGMP', protocolViewName, re.I) or re.search(
                    'MLD', protocolViewName, re.I):
                sessionsUp = int(stats[session]['Host Total Frames Tx'])
                totalSessions = int(stats[session]['Host Total Frames Rx'])
            elif re.search('ISIS', protocolViewName, re.I):
                sessionsUp = int(stats[session]['L2 Sess. Up'])
                totalSessions = int(stats[session]['L2 Sess. Configured'])
            elif re.search('LACP', protocolViewName, re.I):
                sessionsUp = int(stats[session]['LAG Member Ports UP'])
                totalSessions = int(stats[session]['Total LAG Member Ports'])
            elif re.search('LDP', protocolViewName, re.I):
                sessionsUp = int(stats[session]['Targeted Sess. Up'])
                totalSessions = int(
                    stats[session]['Targeted Sess. Configured'])
            elif re.search('OAM', protocolViewName, re.I):
                sessionsUp = int(stats[session]['Links Running'])
                totalSessions = int(stats[session]['Links Configured'])
            elif re.search('LISP', protocolViewName, re.I):
                sessionsUp = int(stats[session]['MS/MR Running'])
                totalSessions = int(stats[session]['MS/MR Configured'])
            elif re.search('MPLSTP', protocolViewName, re.I):
                sessionsUp = int(stats[session]['CCCV Up'])
                totalSessions = int(stats[session]['CCCV Configured'])
            elif re.search('MPLSOAM', protocolViewName, re.I):
                sessionsUp = int(stats[session]['BFD Up-Sessions'])
                totalSessions = int(stats[session]['BFD Session Count'])
            elif re.search('OpenFlow', protocolViewName, re.I):
                sessionsUp = int(stats[session]['OF Channel Configured Up'])
                totalSessions = int(stats[session]['OF Channel Configured'])
            elif re.search('OSPF', protocolViewName, re.I):
                sessionsUp = int(stats[session]['Full Nbrs.'])
                totalSessions = int(stats[session]['Sess. Configured'])
            elif re.search('PIM', protocolViewName, re.I):
                sessionsUp = int(stats[session]['Rtrs. Running'])
                totalSessions = int(stats[session]['Rtrs. Configured'])
            elif re.search('RIP', protocolViewName, re.I):
                sessionsUp = int(stats[session]['Request Packet Tx'])
                totalSessions = int(stats[session]['Routers Configured'])
            elif re.search('RSVP', protocolViewName, re.I):
                sessionsUp = int(stats[session]['Ingress LSPs Up'])
                totalSessions = int(stats[session]['Ingress LSPs Configured'])
            elif re.search('STP', protocolViewName, re.I):
                sessionsUp = int(stats[session]['Forwarding State Count'])
                totalSessions = int(stats[session]['Discarding State Count'])
            else:
                raise IxNetRestApiException('No protocol viewName found')

            if stats[session]['Port Name'] == portName:
                self.ixnObj.logInfo(
                    '\n\tPortName: {0}\n\t   TotalSessionsUp: {1}\n\t   '
                    'TotalSessionsConfigured: {2}'.format(
                        stats[session]['Port Name'], sessionsUp,
                        totalSessions),
                    timestamp=False)
                protocolStats[protocol] = {
                    'Configured': totalSessions,
                    'Up': sessionsUp
                }
        return protocolStats

    def enableRouteRangeOnProtocol(self,
                                   portName,
                                   protocol,
                                   routeRange,
                                   enable=True):
        """
        Description
            Enable a route range for a protocol on a speficied port

        Parameters
            portName: <str>: Name of the port eg: "1/1/11"
            protocol: <str>: protocol to enable route range.
            routeRange: <str>: route range <IPv4|IPv6> address
            enable: <bool>: enable or disable route range, default is True

        Examples:
            enableRouteRangeOnProtocol(protName='1/1/11', protocol='ospf', routeRange='10.10.10.1')
            enableRouteRangeOnProtocol(protName='1/1/11', protocol='ospfv3', routeRange='10::1',
            enable=True)
        """
        vport = self.portMgmtObj.getVportObjectByName(portName)
        if vport is None:
            raise IxNetRestApiException(
                'PortName {0} not connected to chassis'.format(portName))

        RouterInstanceList = self.getRouterInstanceByPortAndProtocol(
            protocol=protocol, vport=vport)
        if not RouterInstanceList:
            raise IxNetRestApiException(
                'No Router instance exists in protocol {0}'.format(protocol))
        argsDict = {'ospf': 'NetworkNumber', 'bgp': 'NetworkAddress'}

        if protocol in ['ospf', 'bgp']:
            args = argsDict[protocol]
        else:
            args = 'firstRoute'

        for eachRouterInstance in RouterInstanceList:
            RouteRangeInstanceList = eachRouterInstance.RouteRange.find()
            self.ixnObj.logInfo('Route Range list %s' % RouteRangeInstanceList)

            for eachRouteRange in RouteRangeInstanceList:
                RouteRangeNetwork = getattr(eachRouteRange, args)
                if RouteRangeNetwork == routeRange:
                    eachRouteRange.Enabled = enable
                    return
            raise IxNetRestApiException(
                'Route range: {0} does not exist in protocol: {1} port: {2}'.
                format(routeRange, protocol, portName))

    def removeRouteRangeOnProtocol(self, portName, protocol, routeRange):
        """
        Description
            Remove a route range for a protocol on a speficied port

        Parameters
            portName: <str>: Name of the port eg: "1/1/11"
            protocol: <str>: protocol to remove route range.
            routeRange: <str>: route range <IPv4|IPv6> address

        Examples:
            removeRouteRangeOnProtocol(protName='1/1/11', protocol='ospf', routeRange='10.10.10.1')
            removeRouteRangeOnProtocol(protName='1/1/11', protocol='ospfv3', routeRange='10::1')
        """
        vport = self.portMgmtObj.getVportObjectByName(portName)
        if vport is None:
            raise IxNetRestApiException(
                'PortName {0} not connected to chassis'.format(portName))

        RouterInstanceList = self.getRouterInstanceByPortAndProtocol(
            protocol=protocol, vport=vport)
        if not RouterInstanceList:
            raise IxNetRestApiException(
                'No Router instance exists in protocol {0}'.format(protocol))

        self.ixnObj.logInfo('Router list %s' % RouterInstanceList)
        argsDict = {'ospf': 'NetworkNumber', 'bgp': 'NetworkAddress'}

        if protocol in ['ospf', 'bgp']:
            args = argsDict[protocol]
        else:
            args = 'firstRoute'

        for eachRouterInstance in RouterInstanceList:
            RouteRangeInstanceList = eachRouterInstance.RouteRange.find()
            self.ixnObj.logInfo('Route Range list %s' % RouteRangeInstanceList)
            for eachRouteRange in RouteRangeInstanceList:
                RouteRangeNetwork = getattr(eachRouteRange, args)
                if RouteRangeNetwork == routeRange:
                    eachRouteRange.remove()
                    return
            raise IxNetRestApiException(
                'Route range: {0} does not exist in protocol: {1} port: {2}'.
                format(routeRange, protocol, portName))

    def createRouteRangeOnProtocol(self, portName, protocol, routeRange):
        """
        Description
            Create a route range for a protocol on a speficied port

        Parameters
            portName: <str>: Name of the port eg: "1/1/11"
            protocol: <str>: protocol to create route range.
            routeRange: <dict>: route range to configure <IPv4|IPv6> address
            eg: {'enabled': 'True', 'mask': 24, 'origin': 'externalType1',
            'networkNumber': '8.7.7.1', 'metric': 10, 'numberOfRoutes': 5}
                {'enabled': 'True', 'maskWidth': 64, 'numberOfRoute': 10, 'firstRoute': '7::1',
                'metric': 10, 'nextHop': '7::2'}

        Examples
            createRouteRangeOnProtocol(portName='1/1/11', protocol='ospf',
            routeRange={'enabled': 'True', 'mask': 24, 'numberOfRoutes': 5,
            'networkNumber': '8.7.7.1', 'metric': 10, 'origin': 'externalType1'}
            createRouteRangeOnProtocol(portName='1/1/11', protocol='ospf',
            routeRange={'networkNumber': '8.7.7.1'}

        """
        vport = self.portMgmtObj.getVportObjectByName(portName)
        if vport is None:
            raise IxNetRestApiException(
                'PortName {0} not connected to chassis'.format(portName))

        RouterInstanceList = self.getRouterInstanceByPortAndProtocol(
            protocol=protocol, vport=vport)
        if not RouterInstanceList:
            raise IxNetRestApiException(
                'No Router instance exists in protocol {0}'.format(protocol))

        self.ixnObj.logInfo('Router list %s' % RouterInstanceList)
        for eachRouterInstance in RouterInstanceList:
            if not eachRouterInstance.RouteRange.find():
                routeRangeObj = eachRouterInstance.RouteRange.add()
            else:
                routeRangeObj = eachRouterInstance.RouteRange.find()
            for key, value in routeRange:
                key = key[0].capitalize() + key[1:]
                setattr(routeRangeObj, key, value)

    def getRouterInstanceByPortAndProtocol(self, protocol, vport):
        """
        Description
            Get router instance for the specified protocol on a speficied vport

        Parameters
            protocol: <str>: protocol to get a router instance
            vport: <str>: vport instance

        Examples
            getRouterInstanceByPortAndProtocol(protocol='ospf', vport=vport object)

        Return
            RouterInstanceList
            Returns [] if no router instance exists
        """
        protocolNextNodeDict = {
            'bgp': 'NeighborRange',
            'igmp': 'Host',
            'mld': 'Host',
            'stp': 'Bridge',
            'cfm': 'Bridge',
            'rsvp': 'NeighborPair',
            'lacp': 'Link',
            'linkOam': 'Link',
            'elmi': 'Uni',
            'openFlow': 'Device'
        }
        protocols = [
            'bgp', 'igmp', 'mld', 'stp', 'cfm', 'rsvp', 'lacp', 'linkOam',
            'elmi', 'openFlow'
        ]
        if protocol in protocols:
            nextNode = protocolNextNodeDict[protocol]
        else:
            nextNode = 'Router'
        RouterInstanceList = []
        protocol = protocol[0].capitalize() + protocol[1:]
        protocolObj = getattr(vport.Protocols.find(), protocol)
        nextNodeObj = getattr(protocolObj, nextNode)
        RouterInstancesList = nextNodeObj.find()
        for eachRouterInstance in RouterInstancesList:
            RouterInstanceList.append(eachRouterInstance)
        self.ixnObj.logInfo('Router Instance list %s' % RouterInstanceList)
        return RouterInstanceList

    def verifyProtocolSessionsUp(self,
                                 protocolViewName='BGP Peer Per Port',
                                 timeout=60):
        """
        Description
            Verify the specified protocol sessions are UP or not.

        Parameters
            protocolViewName: <str>: The protocol view name.
            timeout: <int>: Duration to wait for the protocol sessions to up.Default = 60 seconds.

        protocolViewName options:
            'BFD Aggregated Statistics'
            'BGP Aggregated Statistics'
            'ISIS Aggregated Statistics'
            'OSPF Aggregated Statistics'
            'RIPng Aggregated Statistics'
            'RIP Aggregated Statistics'
            'LDP Aggregated Statistics'
            'PIMSM Aggregated Statistics'
            'MPLSOAM Aggregated Statistics'

        Examples
            verifyProtocolSessionsUp(protcolViewName='ospf Aggregated Statistics')
            verifyProtocolSessionsUp(protcolViewName='ospf Aggregated Statistics',timeout=90)
        """
        totalSessions = 0
        totalPortsUpFlag = 0
        totalExpectedSessionsUp = 0
        sessionsUp = 0
        self.ixnObj.logInfo('Protocol view name %s' % protocolViewName)
        time.sleep(10)
        for counter in range(1, timeout + 1):
            stats = self.statObj.getStats(viewName=protocolViewName,
                                          displayStats=False)
            totalPorts = len(stats.keys())
            self.ixnObj.logInfo('ProtocolName: {0}'.format(protocolViewName))
            for session in stats.keys():
                if re.search('BFD', protocolViewName, re.I) or re.search(
                        'RIPng', protocolViewName, re.I):
                    sessionsUp = int(stats[session]['Routers Running'])
                    totalSessions = int(stats[session]['Routers Configured'])
                elif re.search('BGP', protocolViewName, re.I):
                    sessionsUp = int(stats[session]['Sess. Up'])
                    totalSessions = int(stats[session]['Sess. Configured'])
                elif re.search('CFM', protocolViewName, re.I):
                    sessionsUp = int(stats[session]['Bridges Running'])
                    totalSessions = int(stats[session]['Bridges Configured'])
                elif re.search('EIGRP', protocolViewName, re.I) or \
                        re.search('ELMI', protocolViewName, re.I):
                    sessionsUp = int(stats[session]['IPv4 Routers Running'])
                    totalSessions = int(
                        stats[session]['IPv4 Routers Configured'])
                elif re.search('IGMP', protocolViewName, re.I) or re.search(
                        'MLD', protocolViewName, re.I):
                    sessionsUp = int(stats[session]['Host Total Frames Tx'])
                    totalSessions = int(stats[session]['Host Total Frames Rx'])
                elif re.search('ISIS', protocolViewName, re.I):
                    sessionsUp = int(stats[session]['L2 Sess. Up'])
                    totalSessions = int(stats[session]['L2 Sess. Configured'])
                elif re.search('LACP', protocolViewName, re.I):
                    sessionsUp = int(stats[session]['LAG Member Ports UP'])
                    totalSessions = int(
                        stats[session]['Total LAG Member Ports'])
                elif re.search('LDP', protocolViewName, re.I):
                    sessionsUp = int(stats[session]['Targeted Sess. Up'])
                    totalSessions = int(
                        stats[session]['Targeted Sess. Configured'])
                elif re.search('OAM', protocolViewName, re.I):
                    sessionsUp = int(stats[session]['Links Running'])
                    totalSessions = int(stats[session]['Links Configured'])
                elif re.search('LISP', protocolViewName, re.I):
                    sessionsUp = int(stats[session]['MS/MR Running'])
                    totalSessions = int(stats[session]['MS/MR Configured'])
                elif re.search('MPLSTP', protocolViewName, re.I):
                    sessionsUp = int(stats[session]['CCCV Up'])
                    totalSessions = int(stats[session]['CCCV Configured'])
                elif re.search('MPLSOAM', protocolViewName, re.I):
                    sessionsUp = int(stats[session]['BFD Up-Sessions'])
                    totalSessions = int(stats[session]['BFD Session Count'])
                elif re.search('OpenFlow', protocolViewName, re.I):
                    sessionsUp = int(
                        stats[session]['OF Channel Configured Up'])
                    totalSessions = int(
                        stats[session]['OF Channel Configured'])
                elif re.search('OSPF', protocolViewName, re.I):
                    sessionsUp = int(stats[session]['Full Nbrs.'])
                    totalSessions = int(stats[session]['Sess. Configured'])
                elif re.search('PIM', protocolViewName, re.I):
                    sessionsUp = int(stats[session]['Rtrs. Running'])
                    totalSessions = int(stats[session]['Rtrs. Configured'])
                elif re.search('RIP', protocolViewName, re.I):
                    sessionsUp = int(stats[session]['Request Packet Tx'])
                    totalSessions = int(stats[session]['Routers Configured'])
                elif re.search('RSVP', protocolViewName, re.I):
                    sessionsUp = int(stats[session]['Ingress LSPs Up'])
                    totalSessions = int(
                        stats[session]['Ingress LSPs Configured'])
                elif re.search('STP', protocolViewName, re.I):
                    sessionsUp = int(stats[session]['Forwarding State Count'])
                    totalSessions = int(
                        stats[session]['Discarding State Count'])
                totalExpectedSessionsUp = totalSessions

                if totalExpectedSessionsUp != 0:
                    self.ixnObj.logInfo(
                        '\n\tPortName: {0}\n\t   TotalSessionsUp: {1}\n\t   '
                        'ExpectedTotalSessionsup: {2}'.format(
                            stats[session]['Port Name'], sessionsUp,
                            totalExpectedSessionsUp),
                        timestamp=False)
                    if counter < timeout and sessionsUp != totalExpectedSessionsUp:
                        self.ixnObj.logInfo(
                            '\t   Protocol Session is still down',
                            timestamp=False)

                    if counter < timeout and sessionsUp == totalExpectedSessionsUp:
                        totalPortsUpFlag += 1
                        if totalPortsUpFlag == totalPorts:
                            self.ixnObj.logInfo(
                                'All protocol sessions are up!')
                            return

            if counter == timeout and sessionsUp != totalExpectedSessionsUp:
                raise IxNetRestApiException(
                    'Protocol Sessions failed to come up')

            self.ixnObj.logInfo('\n\tWait {0}/{1} seconds\n'.format(
                counter, timeout),
                                timestamp=False)
            time.sleep(1)

    def verifyAllConfiguredProtocolSessions(self, duration):
        """
        Description
            verify all configured protocol sessions are UP or not

        Parameters
            duration: <int>: duration to wait for the protocol sessions to UP

        Examples
            verifyAllConfiguredProtocolSessions(duration=120)
            verifyAllConfiguredProtocolSessions(120)
        """
        confifuredProtocols = self.getConfiguredProtocols()
        if not confifuredProtocols:
            raise IxNetRestApiException(
                'No protocols Running or Configured or Enabled')

        for protocol in confifuredProtocols:
            if protocol in [
                    'Bfd', 'Bgp', 'Cfm', 'Eigrp', 'Elmi', 'Igmp', 'Isis',
                    'Lacp', 'Ldp', 'Lisp', 'Mld', 'MplsTp', 'MplsOam', 'Ospf',
                    'Rip', 'Rsvp', 'Stp'
            ]:
                protocolViewName = protocol.upper() + 'Aggregated Statistics'
            elif re.search('LinkOam', protocol, re.I):
                protocolViewName = 'OAM Aggregated Statistics'
            elif re.search('openFlow', protocol, re.I):
                protocolViewName = 'OpenFlow Switch Aggregated Statistics'
            elif re.search('OspfV3', protocol, re.I):
                protocolViewName = 'OSPFv3 Aggregated Statistics'
            elif re.search('Pim', protocol, re.I):
                protocolViewName = 'PIMSM Aggregated Statistics'
            elif re.search('Ripng', protocol, re.I):
                protocolViewName = 'RIPng Aggregated Statistics'
            else:
                raise IxNetRestApiException('No viewName defined')
            self.verifyProtocolSessionsUp(protocolViewName=protocolViewName,
                                          timeout=duration)