def __init__(self, ixnObj=None, portMgmtObj=None):
        """
        Parameters
            ixnObj: The main ixnObj object
            portMgmtObj: (Optional):  The PortMgmt object.
                         If you already have the portMgmt object, then pass it in. 
                         Otherwise, leave portMgmtObj=None

        Example:
            trafficObj = Traffic(mainObj)
            portMgmtObj = PortMgmt(mainObj)
            captureObj = PacketCapture(mainObj, portMgmtObj)
            captureObj.packetCaptureConfigPortMode(port=[ixChassisIp, '2', '1'], enableControlPlane=False, enableDataPlane=True)
            trafficObj.startTraffic()  <-- Make sure traffic is running in continuous mode
            captureObj.packetCaptureStart()
            time.sleep(10)
            captureObj.packetCaptureStop()
            trafficObj.stopTraffic()

            pktCaptureObj.getCapFile(port=[ixChassisIp, '2', '1'], typeOfCapture='data', saveToTempLocation='c:\\Results',
                                     localLinuxLocation='.', appendToSavedCapturedFile=None)

            pktCaptureObj.packetCaptureGetCurrentPackets(getUpToPacketNumber=5, capturePacketsToFile=True,
                                                         getSavedCapturedDotCapFile=True)

            captureObj.packetCaptureClearTabs()
        """
        self.ixnObj = ixnObj
        if portMgmtObj:
            self.portMgmtObj = portMgmtObj
        else:
            self.portMgmtObj = PortMgmt(ixnObj)

        self.enableControlPlane = False
        self.enableDataPlane = False
Example #2
0
 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)
Example #3
0
    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)
class PacketCapture(object):
    """
    ixnObj: The main connection object
    portObj: The port object

    """
    def __init__(self, ixnObj=None, portMgmtObj=None):
        """
        Parameters
            ixnObj: The main ixnObj object
            portMgmtObj: (Optional):  The PortMgmt object.
                         If you already have the portMgmt object, then pass it in. 
                         Otherwise, leave portMgmtObj=None

        Example:
            trafficObj = Traffic(mainObj)
            portMgmtObj = PortMgmt(mainObj)
            captureObj = PacketCapture(mainObj, portMgmtObj)
            captureObj.packetCaptureConfigPortMode(port=[ixChassisIp, '2', '1'], enableControlPlane=False, enableDataPlane=True)
            trafficObj.startTraffic()  <-- Make sure traffic is running in continuous mode
            captureObj.packetCaptureStart()
            time.sleep(10)
            captureObj.packetCaptureStop()
            trafficObj.stopTraffic()

            pktCaptureObj.getCapFile(port=[ixChassisIp, '2', '1'], typeOfCapture='data', saveToTempLocation='c:\\Results',
                                     localLinuxLocation='.', appendToSavedCapturedFile=None)

            pktCaptureObj.packetCaptureGetCurrentPackets(getUpToPacketNumber=5, capturePacketsToFile=True,
                                                         getSavedCapturedDotCapFile=True)

            captureObj.packetCaptureClearTabs()
        """
        self.ixnObj = ixnObj
        if portMgmtObj:
            self.portMgmtObj = portMgmtObj
        else:
            self.portMgmtObj = PortMgmt(ixnObj)

        self.enableControlPlane = False
        self.enableDataPlane = False

    def setMainObject(self, mainObject):
        # For Python Robot Framework support
        self.ixnObj = mainObject
        self.portMgmtObj.setMainObject(mainObject)

    def packetCaptureConfigPortMode(self,
                                    port,
                                    enableControlPlane=True,
                                    enableDataPlane=True):
        """
        Description
           Enable|Disable port capturing for control plane and data plane.

           Values are true or false
              -softwareEnabled == Control Plane
              -hardwareEnabled == Data Plane

        Parameters
            port: [ixChassisIp, 1, 3] => [ixChasssisIp, str(cardNumber), str(portNumber)]
            enableControlPlane: True|False
            enableDataPlane: True|False
        """
        if enableControlPlane == True:
            self.enableControlPlane = True
        if enableDataPlane == True:
            self.enableDataPlane = True

        self.captureRxPort = port
        vport = self.portMgmtObj.getVports([port])[0]
        self.ixnObj.patch(self.ixnObj.httpHeader + vport,
                          data={'rxMode': 'capture'})
        #self.ixnObj.patch(self.ixnObj.httpHeader+vport, data={'rxMode': 'captureAndMeasure'})
        self.ixnObj.patch(self.ixnObj.httpHeader + vport + '/capture',
                          data={
                              'softwareEnabled': enableControlPlane,
                              'hardwareEnabled': enableDataPlane
                          })

    def packetCaptureStart(self):
        """
        Start packet capturing
        """
        self.ixnObj.post(self.ixnObj.sessionUrl + '/operations/startcapture')

    def packetCaptureStop(self):
        """
        Stop packet capturing
        """
        self.ixnObj.post(self.ixnObj.sessionUrl + '/operations/stopcapture')

    def packetCaptureClearTabs(self):
        """
        Remove all captured tabs on Windows IxNetwork GUI
        """
        self.ixnObj.post(self.ixnObj.sessionUrl + '/operations/closeAllTabs')

    def packetCaptureGetCurrentPackets(self,
                                       getUpToPacketNumber=20,
                                       capturePacketsToFile=True):
        """
        Description
           Packet Capturing in wireshark style details. By default, it saved 7209 packet counts.
           It takes a long time to save all the packet header details into a file. 
           This API will default saving 20 packet counts. You could increase the packet count.

        Parameters
            getUpToPacketNumber: None|The last packet number to get. 
                                 Always starts at 1. If you state 10, then this function will get 1-10 packets.
            capturePacketsToFile: True|False
        """
        import subprocess, time

        if capturePacketsToFile:
            timestamp = int(time.time())
            if self.enableDataPlane:
                packetCaptureFilenameData = 'packetCaptureForData_' + str(
                    timestamp)
                subprocess.call(['touch', packetCaptureFilenameData])
            if self.enableControlPlane:
                packetCaptureFilenameControl = 'packetCaptureForControl_' + str(
                    timestamp)
                subprocess.call(['touch', packetCaptureFilenameControl])
            if self.enableDataPlane == False and self.enableControlPlane == False:
                raise IxNetRestApiException(
                    '\nPacketCapture Error: You must enable one of the options: enableDataPlane|enableControlPlane'
                )

        vport = self.portMgmtObj.getVports([self.captureRxPort])[0]
        response = self.ixnObj.get(self.ixnObj.httpHeader + vport + '/capture')
        totalDataCapturedPackets = response.json()['dataPacketCounter']
        totalControlCapturedPackets = response.json()['controlPacketCounter']
        if type(totalDataCapturedPackets) != int:
            totalDataCapturedPackets = 0
        else:
            if getUpToPacketNumber != None:
                totalDataCapturedPackets = getUpToPacketNumber
        if type(totalControlCapturedPackets) != int:
            totalControlCapturedPackets = 0
        else:
            if getUpToPacketNumber != None:
                totalControlCapturedPackets = getUpToPacketNumber

        for eachTypeOfCaptures, totalCapturedPackets in zip(
            ('data', 'control'),
            (totalDataCapturedPackets, totalControlCapturedPackets)):
            self.ixnObj.logInfo(
                'Getting captured packets for: %s totalCapturedPackets:%s' %
                (eachTypeOfCaptures, totalCapturedPackets))

            if capturePacketsToFile and int(totalCapturedPackets) != 0:
                timestamp = int(time.time())
                if self.enableDataPlane:
                    packetCaptureFilenameData = 'packetCaptureForData_' + str(
                        timestamp)
                    subprocess.call(['touch', packetCaptureFilenameData])
                if self.enableControlPlane:
                    packetCaptureFilenameControl = 'packetCaptureForControl_' + str(
                        timestamp)
                    subprocess.call(['touch', packetCaptureFilenameControl])

            for packetIndex in range(1, int(totalCapturedPackets)):
                if self.enableDataPlane and eachTypeOfCaptures == 'data':
                    data = {
                        'arg1': vport + '/capture/currentPacket',
                        'arg2': packetIndex
                    }
                    response = self.ixnObj.post(
                        self.ixnObj.sessionUrl +
                        '/vport/capture/currentPacket/operations/getpacketfromdatacapture',
                        data=data,
                        silentMode=True)
                if self.enableControlPlane and eachTypeOfCaptures == 'control':
                    data = {
                        'arg1': vport + '/capture/currentPacket',
                        'arg2': packetIndex
                    }
                    response = self.ixnObj.post(
                        self.ixnObj.sessionUrl +
                        '/vport/capture/currentPacket/operations/getpacketfromcontrolcapture',
                        data=data,
                        silentMode=True)

                response = self.ixnObj.get(self.ixnObj.httpHeader + vport +
                                           '/capture/currentPacket/stack',
                                           silentMode=True)
                for eachStack in response.json():
                    displayName = eachStack['displayName']
                    stackIdObject = eachStack['links'][0]['href']
                    self.ixnObj.logInfo('\nStack: %s' % displayName)
                    if capturePacketsToFile:
                        if eachTypeOfCaptures == 'data':
                            with open(packetCaptureFilenameData,
                                      'a') as packetCaptureFile:
                                packetCaptureFile.write('\nStack: %s\n' %
                                                        displayName)
                        if eachTypeOfCaptures == 'control':
                            with open(packetCaptureFilenameControl,
                                      'a') as packetCaptureFile:
                                packetCaptureFile.write('\nStack: %s\n' %
                                                        displayName)

                    response = self.ixnObj.get(self.ixnObj.httpHeader +
                                               stackIdObject + '/field',
                                               silentMode=True)
                    for eachField in response.json():
                        fieldId = eachField['id']
                        fieldName = eachField['displayName']
                        fieldValue = eachField['fieldValue']
                        self.ixnObj.logInfo('\t{0}: {1}: {2}'.format(
                            fieldId, fieldName, fieldValue))
                        if capturePacketsToFile:
                            if eachTypeOfCaptures == 'data':
                                with open(packetCaptureFilenameData,
                                          'a') as packetCaptureFile:
                                    packetCaptureFile.write(
                                        '\t{0}: {1}: {2}\n'.format(
                                            fieldId, fieldName, fieldValue))
                            if eachTypeOfCaptures == 'control':
                                with open(packetCaptureFilenameControl,
                                          'a') as packetCaptureFile:
                                    packetCaptureFile.write(
                                        '\t{0}: {1}: {2}\n'.format(
                                            fieldId, fieldName, fieldValue))

    def getCapFile(self,
                   port,
                   typeOfCapture='data',
                   saveToTempLocation='c:\\Temp',
                   localLinuxLocation='.',
                   appendToSavedCapturedFile=None):
        """
        Get the latest captured .cap file from ReST API server to local Linux drive.

        Parameters
            port: Format:[IxiaIpAddress, slotNumber, cardNumber]
                  Example: [ixChassisIp, '2', '1']
            typeOfCapture: data|control
            saveToTempLocation: Where to temporary save the .cap file on the ReST API server: C:\\Temp
                                The folder will be created if it doesn't exists.
            localLinuxLocation: Where to save the .cap file on the Linux machine.
            appendToSavedCapturedFile: Add a text string to the captured file.

        Example:
            captureObj.getCapFile([ixChassisIp, '2', '1'], 'control', 'c:\\Temp', '/home/hgee/test')
        """
        if appendToSavedCapturedFile != None:
            data = {
                'arg1': saveToTempLocation,
                'arg2': appendToSavedCapturedFile
            }
        else:
            data = {'arg1': saveToTempLocation}
        self.ixnObj.post(self.ixnObj.sessionUrl + '/operations/savecapture',
                         data=data)

        if typeOfCapture == 'control':
            capFileToGet = saveToTempLocation + '\\' + port[1] + '-' + port[
                2] + '_SW.cap'
        if typeOfCapture == 'data':
            capFileToGet = saveToTempLocation + '\\' + port[1] + '-' + port[
                2] + '_HW.cap'

        fileMgmtObj = FileMgmt(self.ixnObj)
        fileMgmtObj.copyFileWindowsToLocalLinux(
            windowsPathAndFileName=capFileToGet,
            localPath=localLinuxLocation,
            renameDestinationFile=None)
Example #5
0
                          verifySslCert=False,
                          serverOs='linux',
                          generateLogFile='ixiaDebug.log'
                      )

    if osPlatform in ['windows', 'windowsConnectionMgr']:
        mainObj = Connect(apiServerIp='192.168.70.3',
                          serverIpPort='11009',
                          serverOs=osPlatform,
                          deleteSessionAfterTest=deleteSessionAfterTest,
                          generateLogFile='ixiaDebug.log'
                      )

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

    portObj = PortMgmt(mainObj)
    portObj.connectIxChassis(ixChassisIp)

    if portObj.arePortsAvailable(portList, raiseException=False) != 0:
        if forceTakePortOwnership == True:
            portObj.releasePorts(portList)
            portObj.clearPortOwnership(portList)
        else:
            raise IxNetRestApiException('\nPorts are owned by another user and forceTakePortOwnership is set to False. Exiting test.')

    portObj.releasePorts(portList)
    mainObj.configLicenseServerDetails([licenseServerIp], licenseModel)

    fileMgmtObj = FileMgmt(mainObj)
    fileMgmtObj.importJsonConfigFile(jsonConfigFile, option='newConfig')
Example #6
0
                          serverIpPort='443',
                          username='******',
                          password='******',
                          deleteSessionAfterTest=deleteSessionAfterTest,
                          verifySslCert=False,
                          serverOs=osPlatform)

    if osPlatform in ['windows', 'windowsConnectionMgr']:
        mainObj = Connect(apiServerIp='192.168.70.3',
                          serverIpPort='11009',
                          serverOs=osPlatform,
                          deleteSessionAfterTest=deleteSessionAfterTest)

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

    portObj = PortMgmt(mainObj)
    portObj.connectIxChassis(ixChassisIp)

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

    mainObj.newBlankConfig()

    if configLicense == True:
        portObj.releaseAllPorts()
Example #7
0
                          serverIpPort='11009',
                          serverOs=osPlatform,
                          deleteSessionAfterTest=deleteSessionAfterTest,
                          generateLogFile='ixiaDebug.log')

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

    # Only need to blank the config for Windows because osPlatforms such as Linux and
    # Windows Connection Mgr supports multiple sessions and a new session always come up as a blank config.
    if osPlatform == 'windows':
        mainObj.newBlankConfig()

    mainObj.configLicenseServerDetails([licenseServerIp], licenseModel)

    # Set createVports = True if building config from scratch.
    portObj = PortMgmt(mainObj)
    vportList = portObj.assignPorts(portList,
                                    forceTakePortOwnership,
                                    createVports=True,
                                    rawTraffic=True,
                                    timeout=120)
    portObj.verifyPortState()

    # For all parameter options, please go to the API configTrafficItem
    # mode = create or modify
    trafficObj = Traffic(mainObj)
    trafficStatus = trafficObj.configTrafficItem(mode='create',
                                                 trafficItem={
                                                     'name': 'Raw MPLS/UDP',
                                                     'trafficType': 'raw',
                                                     'trackBy': ['flowGroup0']
Example #8
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)
Example #9
0
        mainObj = Connect(apiServerIp='192.168.70.3',
                          serverIpPort='11009',
                          serverOs=osPlatform,
                          deleteSessionAfterTest=deleteSessionAfterTest,
                          generateLogFile='ixiaDebug.log')

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

    # Only need to blank the config for Windows because osPlatforms such as Linux and
    # Windows Connection Mgr supports multiple sessions and a new session always come up as a blank config.
    if osPlatform == 'windows':
        mainObj.newBlankConfig()

    mainObj.configLicenseServerDetails([licenseServerIp], licenseModel)

    portObj = PortMgmt(mainObj)
    portObj.assignPorts(portList, forceTakePortOwnership)

    protocolObj = Protocol(mainObj)
    topologyObj1 = protocolObj.createTopologyNgpf(portList=[portList[0]],
                                                  topologyName='Topo1')

    deviceGroupObj1 = protocolObj.createDeviceGroupNgpf(topologyObj1,
                                                        multiplier=1,
                                                        deviceGroupName='DG1')

    topologyObj2 = protocolObj.createTopologyNgpf(portList=[portList[1]],
                                                  topologyName='Topo2')

    deviceGroupObj2 = protocolObj.createDeviceGroupNgpf(topologyObj2,
                                                        multiplier=1,
Example #10
0
                          serverIpPort='443',
                          username='******',
                          password='******',
                          deleteSessionAfterTest=deleteSessionAfterTest,
                          verifySslCert=False,
                          serverOs='linux')

    if osPlatform in ['windows', 'windowsConnectionMgr']:
        mainObj = Connect(apiServerIp='10.36.79.226',
                          serverIpPort='11009',
                          serverOs=osPlatform,
                          deleteSessionAfterTest=deleteSessionAfterTest)

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

    portObj = PortMgmt(mainObj)
    portObj.connectIxChassis(ixChassisIp)
    '''
    if portObj.arePortsAvailable(portList, raiseException=False) != 0:
        if forceTakePortOwnership == True:
            portObj.releasePorts(portList)
            portObj.clearPortOwnership(portList)
        else:
            raise IxNetRestApiException('Ports are owned by another user and forceTakePortOwnership is set to False')
    '''
    if configLicense == True:
        portObj.releaseAllPorts()
        mainObj.configLicenseServerDetails([licenseServerIp], licenseModel, licenseTier)

    fileMgmtObj = FileMgmt(mainObj)
    fileMgmtObj.loadConfigFile(configFile)
Example #11
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'}
    }

    # 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 BGP Module'
    # manipulate or modify the state as needed (this is going to be the
    # part where your module will do what it needs to do)
    result['message'] = 'A custom message'
    result['Result'] = 'Passed'

    # use whatever logic you need to determine whether or not this module
    # made any modifications to your target
    #if module.params['new']:
    #    result['changed'] = True
    #result['changed'] = True

    # during the execution of the module, if there is an exception or a
    # conditional state that effectively causes a failure, run
    # AnsibleModule.fail_json() to pass in the message and the result
    #if module.params['name'] == 'fail me':
    #    module.fail_json(msg='You requested this to fail', **result)

    # in the event of a successful module execution, you will want to
    # simple AnsibleModule.exit_json(), passing the key/value results
    #module.exit_json(**result)
    #module.exit_json(changed=False, meta=module.params)

    # 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'], timeout=2)

        # Exit Ansible playbook test as passed.
        module.exit_json(changed=False)
        #module.exit_json(**result)

    except (IxNetRestApiException, Exception, KeyboardInterrupt) as errMsg:
        module.fail_json(msg=errMsg, **result)
        #module.fail_json(changed=False, meta=traceback.format_exc())

        if module.params['enableDebugTracing']:
            if not bool(re.search('ConnectionError', traceback.format_exc())):
                logging.ERROR('\nMY Failure: %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()
Example #12
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)
Example #13
0
                          serverIpPort='11009',
                          serverOs=osPlatform,
                          deleteSessionAfterTest=deleteSessionAfterTest)

    if osPlatform in ['windowsConnectionMgr']:
        mainObj = Connect(apiServerIp='192.168.70.3',
                          serverIpPort='11009',
                          serverOs=osPlatform,
                          deleteSessionAfterTest=deleteSessionAfterTest,
                          sessionId=8021,
                          httpsSecured=False)

    trafficObj = Traffic(mainObj)
    statObj = Statistics(mainObj)
    protocolObj = Protocol(mainObj)
    portObj = PortMgmt(mainObj)
    fileMgmtObj = FileMgmt(mainObj)

    # How to enable/disable many traffic items at once
    # Step 1of2: Get all the traffic item xpaths
    trafficItemJsonObj = fileMgmtObj.exportJsonConfigToDict(
        ['/traffic/descendant-or-self::*'])
    jsonData = []
    for trafficItem in trafficItemJsonObj['traffic']['trafficItem']:
        data = {'xpath': trafficItem['xpath'], 'enabled': True}
        jsonData.append(data)

    # Step 2of2: Use API to send all the xpath data and modify them all at once.
    fileMgmtObj.importJsonConfigObj(dataObj=jsonData, option='modify')

except (IxNetRestApiException, Exception, KeyboardInterrupt) as errMsg:
Example #14
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()
Example #15
0
    if osPlatform in ['windows', 'windowsConnectionMgr']:
        mainObj = Connect(apiServerIp='192.168.70.3',
                          serverIpPort='11009',
                          serverOs=osPlatform,
                          deleteSessionAfterTest=deleteSessionAfterTest,
                          generateLogFile='ixiaDebug.log')

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

    if osPlatform == 'windows':
        mainObj.newBlankConfig()

    mainObj.configLicenseServerDetails([licenseServerIp], licenseModel)

    portObj = PortMgmt(mainObj)
    portObj.assignPorts(portList, forceTakePortOwnership, createVports=True)

    protocolObj = Protocol(mainObj)
    topologyObj1 = protocolObj.createTopologyNgpf(portList=[portList[0]],
                                                  topologyName='Topo1')
    topologyObj2 = protocolObj.createTopologyNgpf(portList=[portList[1]],
                                                  topologyName='Topo2')

    # Device Group For LACP in Topology Group 1
    deviceGroupObj1 = protocolObj.createDeviceGroupNgpf(
        topologyObj1, multiplier=1, deviceGroupName='DG1-LACP')
    # Device Group For LACP in Topology Group 2
    deviceGroupObj2 = protocolObj.createDeviceGroupNgpf(
        topologyObj2, multiplier=1, deviceGroupName='DG2-LACP')
            username=param['usename'],
            password=param['password'],
            deleteSessionAfterTest=param['deleteSessionAfterTest'],
            verifySslCert=param['verifySslCert'],
            serverOs=osPlatform)

    if osPlatform in ['windows', 'windowsConnectionMgr']:
        mainObj = Connect(
            apiServerIp=param['windowsApiServerIp'],
            serverIpPort=param['windowsServerIpPort'],
            serverOs=osPlatform,
            deleteSessionAfterTest=param['deleteSessionAfterTest'])

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

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

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

    mainObj.newBlankConfig()

    # If the license is activated on the chassis's license server, this variable should be True.
    # Otherwise, if the license is in a remote server or remote chassis, this variable should be False.
                          deleteSessionAfterTest=True,
                          generateLogFile=logFile
                          )
        
    # Only need to blank the config for Windows because osPlatforms such as Linux and
    # Windows Connection Mgr supports multiple sessions and a new session always come up as a blank config.
    if osPlatform == 'windows':
        mainObj.newBlankConfig()
    else:
        if api_session_id != None:
            mainObj.newBlankConfig() # Existing session, clear config


    mainObj.configLicenseServerDetails([licenseServerIp], licenseModel)

    portObj = PortMgmt(mainObj)
    portObj.assignPorts(portList, forceTakePortOwnership)
    portObj.modifyPortMediaType(portList, portMediaType)

    protocolObj = Protocol(mainObj)
    topologyObj1 = protocolObj.createTopologyNgpf(portList=[portList[0]],
                                              topologyName='Topo1')

    deviceGroupObj1 = protocolObj.createDeviceGroupNgpf(topologyObj1,
                                                    multiplier=100,
                                                    deviceGroupName='DG1')

    topologyObj2 = protocolObj.createTopologyNgpf(portList=[portList[1]],
                                              topologyName='Topo2')

    deviceGroupObj2 = protocolObj.createDeviceGroupNgpf(topologyObj2,
Example #18
0
class PacketCapture(object):
    """
    ixnObj: The main connection object
    portObj: The port object

    """
    def __init__(self, ixnObj=None, portMgmtObj=None):
        """
        Parameters
            ixnObj: The main ixnObj object
            portMgmtObj: (Optional):  The PortMgmt object.
                         If you already have the portMgmt object, then pass it in. 
                         Otherwise, leave portMgmtObj=None

        Example:
            trafficObj = Traffic(mainObj)
            portMgmtObj = PortMgmt(mainObj)
            captureObj = PacketCapture(mainObj, portMgmtObj)
            captureObj.packetCaptureConfigPortMode(port=[ixChassisIp, '2', '1'], enableControlPlane=False, enableDataPlane=True)
            trafficObj.startTraffic()  <-- Make sure traffic is running in continuous mode
            captureObj.packetCaptureStart()
            time.sleep(10)
            captureObj.packetCaptureStop()
            trafficObj.stopTraffic()

            pktCaptureObj.getCapFile(port=[ixChassisIp, '2', '1'], typeOfCapture='data', saveToTempLocation='c:\\Results',
                                     localLinuxLocation='.', appendToSavedCapturedFile=None)

            pktCaptureObj.packetCaptureGetCurrentPackets(getUpToPacketNumber=5, capturePacketsToFile=True,
                                                         getSavedCapturedDotCapFile=True)

            captureObj.packetCaptureClearTabs()
        """
        self.ixnObj = ixnObj
        if portMgmtObj:
            self.portMgmtObj = portMgmtObj
        else:
            self.portMgmtObj = PortMgmt(ixnObj)

        self.enableControlPlane = False
        self.enableDataPlane = False

    def setMainObject(self, mainObject):
        # For Python Robot Framework support
        self.ixnObj = mainObject
        self.portMgmtObj.setMainObject(mainObject)

    def packetCaptureConfigPortMode(self,
                                    port,
                                    portRxMode='capture',
                                    enableControlPlane=True,
                                    enableDataPlane=True):
        """
        Description
           Enable|Disable port capturing for control plane and data plane.

           Values are true or false
              -softwareEnabled == Control Plane
              -hardwareEnabled == Data Plane

        Parameters
            port: <list>:  [ixChassisIp, '1', '3'] => [ixChasssisIp, str(cardNumber), str(portNumber)]
            portRxMode: <str>: capture|captureAndMeasure
            enableControlPlane: <bool>
            enableDataPlane: <bool>
        """
        if enableControlPlane == True:
            self.enableControlPlane = True
        if enableDataPlane == True:
            self.enableDataPlane = True

        self.captureRxPort = port
        vport = self.portMgmtObj.getVports([port])[0]
        self.ixnObj.patch(self.ixnObj.httpHeader + vport,
                          data={'rxMode': portRxMode})
        self.ixnObj.patch(self.ixnObj.httpHeader + vport + '/capture',
                          data={
                              'softwareEnabled': enableControlPlane,
                              'hardwareEnabled': enableDataPlane
                          })

    def packetCaptureStart(self):
        """
        Start packet capturing
        """
        response = self.ixnObj.post(self.ixnObj.sessionUrl +
                                    '/operations/startcapture')
        self.ixnObj.waitForComplete(
            response, self.ixnObj.sessionUrl + '/operations/startcapture/' +
            response.json()['id'])

    def packetCaptureStop(self):
        """
        Stop packet capturing
        """
        response = self.ixnObj.post(self.ixnObj.sessionUrl +
                                    '/operations/stopcapture')
        self.ixnObj.waitForComplete(
            response, self.ixnObj.sessionUrl + '/operations/stopcapture/' +
            response.json()['id'])

    def packetCaptureClearTabs(self):
        """
        Remove all captured tabs on Windows IxNetwork GUI
        """
        response = self.ixnObj.post(self.ixnObj.sessionUrl +
                                    '/operations/closeAllTabs')
        self.ixnObj.waitForComplete(
            response, self.ixnObj.sessionUrl + '/operations/closeAllTabs/' +
            response.json()['id'])

    def packetCaptureGetCurrentPackets(self,
                                       getUpToPacketNumber=20,
                                       capturePacketsToFile=True):
        """
        Description
           Packet Capturing in wireshark style details. By default, it saved 7209 packet counts.
           It takes a long time to save all the packet header details into a file. 
           This API will default saving 20 packet counts. You could increase the packet count.

        Parameters
            getUpToPacketNumber: None|The last packet number to get. 
                                 Always starts at 1. If you state 10, then this function will get 1-10 packets.
            capturePacketsToFile: True|False
        """
        import subprocess, time

        if capturePacketsToFile:
            timestamp = int(time.time())
            if self.enableDataPlane:
                packetCaptureFilenameData = 'packetCaptureForData_' + str(
                    timestamp)
                subprocess.call(['touch', packetCaptureFilenameData])

            if self.enableControlPlane:
                packetCaptureFilenameControl = 'packetCaptureForControl_' + str(
                    timestamp)
                subprocess.call(['touch', packetCaptureFilenameControl])

            if self.enableDataPlane == False and self.enableControlPlane == False:
                raise IxNetRestApiException(
                    '\nPacketCapture Error: You must enable one of the options: enableDataPlane|enableControlPlane'
                )

        vport = self.portMgmtObj.getVports([self.captureRxPort])[0]
        response = self.ixnObj.get(self.ixnObj.httpHeader + vport + '/capture')
        totalDataCapturedPackets = response.json()['dataPacketCounter']
        totalControlCapturedPackets = response.json()['controlPacketCounter']

        if type(totalDataCapturedPackets) != int:
            totalDataCapturedPackets = 0
        else:
            if getUpToPacketNumber != None:
                totalDataCapturedPackets = getUpToPacketNumber

        if type(totalControlCapturedPackets) != int:
            totalControlCapturedPackets = 0
        else:
            if getUpToPacketNumber != None:
                totalControlCapturedPackets = getUpToPacketNumber

        for eachTypeOfCaptures, totalCapturedPackets in zip(
            ('data', 'control'),
            (totalDataCapturedPackets, totalControlCapturedPackets)):
            self.ixnObj.logInfo(
                'Getting captured packets for capture type: {0}'.format(
                    eachTypeOfCaptures))

            if capturePacketsToFile and int(totalCapturedPackets) != 0:
                timestamp = int(time.time())
                if self.enableDataPlane:
                    packetCaptureFilenameData = 'packetCaptureForData_' + str(
                        timestamp)
                    subprocess.call(['touch', packetCaptureFilenameData])

                if self.enableControlPlane:
                    packetCaptureFilenameControl = 'packetCaptureForControl_' + str(
                        timestamp)
                    subprocess.call(['touch', packetCaptureFilenameControl])

            for packetIndex in range(1, int(totalCapturedPackets)):
                self.ixnObj.logInfo(
                    'Getting captured packet index number: {}/{}'.format(
                        packetIndex, getUpToPacketNumber))

                if self.enableDataPlane and eachTypeOfCaptures == 'data':
                    data = {
                        'arg1': vport + '/capture/currentPacket',
                        'arg2': packetIndex
                    }
                    response = self.ixnObj.post(
                        self.ixnObj.sessionUrl +
                        '/vport/capture/currentPacket/operations/getpacketfromdatacapture',
                        data=data,
                        silentMode=False)
                    self.ixnObj.waitForComplete(
                        response, self.ixnObj.sessionUrl +
                        '/vport/capture/currentPacket/operations/getpacketfromdatacapture/'
                        + response.json()['id'])

                if self.enableControlPlane and eachTypeOfCaptures == 'control':
                    data = {
                        'arg1': vport + '/capture/currentPacket',
                        'arg2': packetIndex
                    }
                    response = self.ixnObj.post(
                        self.ixnObj.sessionUrl +
                        '/vport/capture/currentPacket/operations/getpacketfromcontrolcapture',
                        data=data,
                        silentMode=False)

                    self.ixnObj.waitForComplete(
                        response, self.ixnObj.sessionUrl +
                        '/vport/capture/currentPacket/operations/getpacketfromcontrolcapture/'
                        + response.json()['id'])

                response = self.ixnObj.get(self.ixnObj.httpHeader + vport +
                                           '/capture/currentPacket/stack',
                                           silentMode=False)

                for eachStack in response.json():
                    displayName = eachStack['displayName']
                    stackIdObject = eachStack['links'][0]['href']
                    self.ixnObj.logInfo('\nStack: %s' % displayName)
                    if capturePacketsToFile:
                        if eachTypeOfCaptures == 'data':
                            with open(packetCaptureFilenameData,
                                      'a') as packetCaptureFile:
                                packetCaptureFile.write('\nStack: %s\n' %
                                                        displayName)

                        if eachTypeOfCaptures == 'control':
                            with open(packetCaptureFilenameControl,
                                      'a') as packetCaptureFile:
                                packetCaptureFile.write('\nStack: %s\n' %
                                                        displayName)

                    response = self.ixnObj.get(self.ixnObj.httpHeader +
                                               stackIdObject + '/field',
                                               silentMode=False)
                    for eachField in response.json():
                        fieldId = eachField['id']
                        fieldName = eachField['displayName']
                        fieldValue = eachField['fieldValue']
                        self.ixnObj.logInfo('\t{0}: {1}: {2}'.format(
                            fieldId, fieldName, fieldValue))

                        if capturePacketsToFile:
                            if eachTypeOfCaptures == 'data':
                                with open(packetCaptureFilenameData,
                                          'a') as packetCaptureFile:
                                    packetCaptureFile.write(
                                        '\t{0}: {1}: {2}\n'.format(
                                            fieldId, fieldName, fieldValue))

                            if eachTypeOfCaptures == 'control':
                                with open(packetCaptureFilenameControl,
                                          'a') as packetCaptureFile:
                                    packetCaptureFile.write(
                                        '\t{0}: {1}: {2}\n'.format(
                                            fieldId, fieldName, fieldValue))

    def packetCaptureGetCurrentPacketsHex(self, getUpToPacketNumber=20):
        """
        Description
           Returns captured packets in hex format.   
           This API will default return 20 packet hex. You could increase the packet count.

        Parameters
            getUpToPacketNumber: None|The last packet number to get. 
                                 Always starts at 1. If you state 10, then this function will get 1-10 packets.
            
        Return
            capturedData:  dictionary.   key is 'data' and/or 'control'
                capturedData['data']  is dictionary of packet hex data for Data Capture Buffer
                capturedData['control']  is dictionary of packet hex data for Control Capture Buffer
        """
        import time

        vport = self.portMgmtObj.getVports([self.captureRxPort])[0]
        response = self.ixnObj.get(self.ixnObj.httpHeader + vport + '/capture')
        totalDataCapturedPackets = response.json()['dataPacketCounter']
        totalControlCapturedPackets = response.json()['controlPacketCounter']

        if type(totalDataCapturedPackets) != int:
            totalDataCapturedPackets = 0
        else:
            if getUpToPacketNumber != None:
                totalDataCapturedPackets = getUpToPacketNumber

        if type(totalControlCapturedPackets) != int:
            totalControlCapturedPackets = 0
        else:
            if getUpToPacketNumber != None:
                totalControlCapturedPackets = getUpToPacketNumber

        capturedData = {}
        for eachTypeOfCaptures, totalCapturedPackets in zip(
            ('data', 'control'),
            (totalDataCapturedPackets, totalControlCapturedPackets)):
            self.ixnObj.logInfo(
                'Getting captured packets for capture type: {0}'.format(
                    eachTypeOfCaptures))

            capturedData[eachTypeOfCaptures] = {}
            for packetIndex in range(1, int(totalCapturedPackets)):
                self.ixnObj.logInfo(
                    'Getting captured packet index number: {}/{}'.format(
                        packetIndex, getUpToPacketNumber))

                if totalDataCapturedPackets > 0:
                    data = {
                        'arg1': vport + '/capture/currentPacket',
                        'arg2': packetIndex
                    }
                    response = self.ixnObj.post(
                        self.ixnObj.sessionUrl +
                        '/vport/capture/currentPacket/operations/getpacketfromdatacapture',
                        data=data,
                        silentMode=False)
                    self.ixnObj.waitForComplete(
                        response, self.ixnObj.sessionUrl +
                        '/vport/capture/currentPacket/operations/getpacketfromdatacapture/'
                        + response.json()['id'])

                if totalControlCapturedPackets > 0:
                    data = {
                        'arg1': vport + '/capture/currentPacket',
                        'arg2': packetIndex
                    }
                    response = self.ixnObj.post(
                        self.ixnObj.sessionUrl +
                        '/vport/capture/currentPacket/operations/getpacketfromcontrolcapture',
                        data=data,
                        silentMode=False)

                    self.ixnObj.waitForComplete(
                        response, self.ixnObj.sessionUrl +
                        '/vport/capture/currentPacket/operations/getpacketfromcontrolcapture/'
                        + response.json()['id'])

                data = {'arg1': '-packetHex'}
                response = self.ixnObj.get(self.ixnObj.httpHeader + vport +
                                           '/capture/currentPacket',
                                           data=data,
                                           silentMode=False)
                packetHex = response.json()['packetHex']
                capturedData[eachTypeOfCaptures][packetIndex] = packetHex
            return capturedData

    def getCapFile(self,
                   port,
                   typeOfCapture='data',
                   saveToTempLocation='c:\\Temp',
                   localLinuxLocation='.',
                   appendToSavedCapturedFile=None):
        """
        Get the latest captured .cap file from ReST API server to local Linux drive.

        Parameters
            port: Format:[IxiaIpAddress, slotNumber, cardNumber]
                  Example: [ixChassisIp, '2', '1']

            typeOfCapture: data|control

            saveToTempLocation: For Windows:
                                    Where to temporary save the .cap file on the ReST API server: 
                                    Provide any path with double backslashes: C:\\Temp.
                                    The folder will be created if it doesn't exists.

                                For Linux, value= 'linux'.
 
            localLinuxLocation: Where to save the .cap file on the local Linux machine.

            appendToSavedCapturedFile: Add a text string to the captured file.

        Example:
            captureObj.getCapFile([ixChassisIp, '2', '1'], 'control', 'c:\\Temp', '/home/hgee/test')

        Syntaxes:
               PATCH: /vport/2
               DATA: {'rxMode': 'captureAndMeasure'}

               PATCH: /vport/2/capture
               DATA: {'softwareEnabled': False, 'hardwareEnabled': True}
 
               # Set traffic item to send continuous packets
               PATCH: /traffic/trafficItem/1/configElement/<id>/transmissionControl
               DATA: {'type': 'continuous'}

               POST: /traffic/trafficItem/operations/generate
               DATA: {"arg1": ["/api/v1/sessions/<id>/ixnetwork/traffic/trafficItem/1"]}

               POST: /traffic/operations/apply
               DATA: {"arg1": "/api/v1/sessions/<id>/ixnetwork/traffic"}

               POST: /traffic/operations/start
               DATA: {"arg1": "https://192.168.70.12/api/v1/sessions/<id>/ixnetwork/traffic"}

               Start continuous traffic

               POST: /ixnetwork/operations/startcapture
               POST: /ixnetwork/operations/stopcapture
               POST: /ixnetwork/operations/savecapturefiles
               DATA: {"arg1": "packetCaptureFolder"}  <-- This could be any name.  Just a temporary folder to store the captured file.

               Wait for the /operations/savecapturefiles/<id> to complete.  May take up to a minute or more.

               For Windows API server:
                  POST: /ixnetwork/operations/copyfile
                  DATA: {"arg1": "c:\\Results\\port2_HW.cap", "arg2": "/api/v1/sessions/1/ixnetwork/files/port2_HW.cap"}
                  GET: /ixnetwork/files?filename=port2_HW.cap

               For Linux API server:
                  POST: /ixnetwork/operations/copyfile
                  DATA: {"arg1": "captures/packetCaptureFolder/port2_HW.cap", "arg2": "/api/v1/sessions/<id>/ixnetwork/files/port2_HW.cap"}
                  GET: /ixnetwork/files?filename=captures/packetCaptureFolder/port2_HW.cap
        """

        # For Linux API server
        if '\\' not in saveToTempLocation:
            # For Linux API server, need to give a name for a temporary folder
            saveToTempLocation = 'packetCaptureFolder'

            # For Linux API server, must get the vport name and cannot modify the vport name.
            vport = self.portMgmtObj.getVports([port])[0]
            response = self.ixnObj.get(self.ixnObj.httpHeader + vport)
            vportName = response.json()['name']

            vportName = vportName.replace('/', '_')
            vportName = vportName.replace(' ', '_')
            self.ixnObj.logInfo('vportName: {}'.format(vportName))

        if appendToSavedCapturedFile != None:
            data = {
                'arg1': saveToTempLocation,
                'arg2': appendToSavedCapturedFile
            }
        else:
            data = {'arg1': saveToTempLocation}

        response = self.ixnObj.post(self.ixnObj.sessionUrl +
                                    '/operations/savecapturefiles',
                                    data=data)
        self.ixnObj.waitForComplete(response,
                                    self.ixnObj.httpHeader +
                                    response.json()['url'],
                                    timeout=300)
        capfilePathName = response.json()['result'][0]
        # example capfilePathName: 'c:\\Results\\1-7-2_HW.cap'
        if typeOfCapture == 'control':
            if '\\' not in saveToTempLocation:
                # For Linux
                capFileToGet = '/home/ixia_apps/web/platform/apps-resources/ixnetworkweb/configs/captures/{0}/{1}_SW.cap'.format(
                    saveToTempLocation, vportName)
            else:
                # For Windows
                capFileToGet = capfilePathName

        if typeOfCapture == 'data':
            if '\\' not in saveToTempLocation:
                # For Linux
                capFileToGet = '/home/ixia_apps/web/platform/apps-resources/ixnetworkweb/configs/captures/{0}/{1}_HW.cap'.format(
                    saveToTempLocation, vportName)
            else:
                capFileToGet = capfilePathName

        fileMgmtObj = FileMgmt(self.ixnObj)

        if self.ixnObj.serverOs in ['windows', 'windowsConnectionMgr']:
            fileMgmtObj.copyFileWindowsToLocalLinux(
                windowsPathAndFileName=capFileToGet,
                localPath=localLinuxLocation,
                renameDestinationFile=None)
        if self.ixnObj.serverOs == 'linux':
            # Parse out captures/packetCaptureFolder/<vportName>_HW.cap
            match = re.search('.*(captures.*)', capFileToGet)
            pathExtension = match.group(1)

            fileMgmtObj.copyFileLinuxToLocalLinux(
                linuxApiServerPathAndFileName=capFileToGet,
                localPath=localLinuxLocation,
                renameDestinationFile=None,
                linuxApiServerPathExtension=pathExtension)
Example #19
0
                          username='******',
                          password='******',
                          deleteSessionAfterTest=deleteSessionAfterTest,
                          verifySslCert=False,
                          serverOs=osPlatform)

    if osPlatform in ['windows', 'windowsConnectionMgr']:
        mainObj = Connect(apiServerIp='192.168.70.3',
                          serverIpPort='11009',
                          serverOs=osPlatform,
                          deleteSessionAfterTest=deleteSessionAfterTest,
                          httpInsecure=True)

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

    portObj = PortMgmt(mainObj)
    portObj.connectIxChassis(ixChassisIp)

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

    mainObj.newBlankConfig()

    # If the license is activated on the chassis's license server, this variable should be True.
    # Otherwise, if the license is in a remote server or remote chassis, this variable should be False.
class PacketCapture(object):
    """
    ixnObj: The main connection object
    portObj: The port object

    """
    def __init__(self, ixnObj=None, portMgmtObj=None):
        """
        Parameters
            ixnObj: The main ixnObj object
            portMgmtObj: (Optional):  The PortMgmt object. If you already have the portMgmt
            object, then pass it in.
                         Otherwise, leave portMgmtObj=None
        Example:
            trafficObj = Traffic(mainObj)
            portMgmtObj = PortMgmt(mainObj)
            captureObj = PacketCapture(mainObj, portMgmtObj)
            captureObj.packetCaptureConfigPortMode(port=[ixChassisIp, '2', '1'],
            enableControlPlane=False, enableDataPlane=True)
            trafficObj.startTraffic()  <-- Make sure traffic is running in continuous mode
            captureObj.packetCaptureStart()
            time.sleep(10)
            captureObj.packetCaptureStop()
            trafficObj.stopTraffic()

            pktCaptureObj.getCapFile(port=[ixChassisIp, '2', '1'], typeOfCapture='data',
            saveToTempLocation='c:\\Results', localLinuxLocation='.',
            appendToSavedCapturedFile=None)

            pktCaptureObj.packetCaptureGetCurrentPackets(getUpToPacketNumber=5,
            capturePacketsToFile=True, getSavedCapturedDotCapFile=True)

            captureObj.packetCaptureClearTabs()
        """
        self.ixnObj = ixnObj
        self.ixNetwork = ixnObj.ixNetwork
        if portMgmtObj:
            self.portMgmtObj = portMgmtObj
        else:
            self.portMgmtObj = PortMgmt(ixnObj)

        self.enableControlPlane = False
        self.enableDataPlane = False

    def setMainObject(self, mainObject):
        # For Python Robot Framework support
        self.ixnObj = mainObject
        self.portMgmtObj.setMainObject(mainObject)

    def packetCaptureConfigPortMode(self,
                                    port,
                                    portRxMode='capture',
                                    enableControlPlane=True,
                                    enableDataPlane=True):
        """
        Description
           Enable|Disable port capturing for control plane and data plane.

           Values are true or false
              -softwareEnabled == Control Plane
              -hardwareEnabled == Data Plane

        Parameters
            port: <list>:[ixChassisIp, '1', '3'] => [ixChasssisIp, str(cardNumber), str(portNumber)]
            portRxMode: <str>: capture|captureAndMeasure
            enableControlPlane: <bool>
            enableDataPlane: <bool>
        """
        self.ixnObj.logInfo(
            "Configuring and enable control/data plane capture")
        if enableControlPlane:
            self.enableControlPlane = True
        if enableDataPlane:
            self.enableDataPlane = True

        self.captureRxPort = port
        vport = self.portMgmtObj.getVports([port])[0]
        vport.RxMode = portRxMode

        vport.Capture.SoftwareEnabled = enableControlPlane
        vport.Capture.HardwareEnabled = enableDataPlane

    def packetCaptureStart(self):
        """
        Start packet capturing
        """
        try:
            self.ixNetwork.StartCapture()
        except Exception as err:
            self.ixnObj.logInfo("Error {} ".format(err))
            raise Exception('\n Failed to start captures')

    def packetCaptureStop(self):
        """
        Stop packet capturing
        """
        try:
            self.ixNetwork.StopCapture()
        except Exception as err:
            self.ixnObj.logInfo("Error {} ".format(err))
            raise Exception('\n Failed to stop captures')

    def packetCaptureClearTabs(self):
        """
        Remove all captured tabs on Windows IxNetwork GUI
        """
        try:
            self.ixNetwork.CloseAllTabs()
        except Exception as err:
            self.ixnObj.logInfo("Error {} ".format(err))
            raise Exception('\n Failed closing all tabs')

    def packetCaptureGetCurrentPackets(self,
                                       getUpToPacketNumber=20,
                                       capturePacketsToFile=True):
        """
        Description
           Packet Capturing in wireshark style details. By default, it saved 7209 packet counts.
           It takes a long time to save all the packet header details into a file.
           This API will default saving 20 packet counts. You could increase the packet count.

        Parameters
            getUpToPacketNumber: None|The last packet number to get. Always starts at 1.
                                 If you state 10, then this function will get 1-10 packets.
            capturePacketsToFile: True|False
        """

        if capturePacketsToFile:
            timestamp = int(time.time())
            if self.enableDataPlane:
                packetCaptureFilenameData = 'packetCaptureForData_' + str(
                    timestamp)

            if self.enableControlPlane:
                packetCaptureFilenameControl = 'packetCaptureForControl_' + str(
                    timestamp)

            if not self.enableDataPlane and not self.enableControlPlane:
                raise IxNetRestApiException(
                    '\n PacketCapture Error: You must enable one of the '
                    'options: enableDataPlane|enableControlPlane')

        vport = self.portMgmtObj.getVports([self.captureRxPort])[0]
        totalDataCapturedPackets = vport.Capture.DataPacketCounter
        totalControlCapturedPackets = vport.Capture.ControlPacketCounter

        if type(totalDataCapturedPackets) != int:
            totalDataCapturedPackets = 0
        else:
            if getUpToPacketNumber is not None:
                totalDataCapturedPackets = getUpToPacketNumber

        if type(totalControlCapturedPackets) != int:
            totalControlCapturedPackets = 0
        else:
            if getUpToPacketNumber is not None:
                totalControlCapturedPackets = getUpToPacketNumber

        for eachTypeOfCaptures, totalCapturedPackets in \
                zip(('data', 'control'), (totalDataCapturedPackets, totalControlCapturedPackets)):
            self.ixnObj.logInfo(
                'Getting captured packets for capture type: {0}'.format(
                    eachTypeOfCaptures))

            if capturePacketsToFile and int(totalCapturedPackets) != 0:
                timestamp = int(time.time())
                if self.enableDataPlane:
                    packetCaptureFilenameData = 'packetCaptureForData_' + str(
                        timestamp)

                if self.enableControlPlane:
                    packetCaptureFilenameControl = 'packetCaptureForControl_' + str(
                        timestamp)

            for packetIndex in range(1, int(totalCapturedPackets)):
                self.ixnObj.logInfo(
                    'Getting captured packet index number: {}/{}'.format(
                        packetIndex, getUpToPacketNumber))

                if self.enableDataPlane and eachTypeOfCaptures == 'data':
                    vport.Capture.CurrentPacket.GetPacketFromDataCapture(
                        Arg2=packetIndex)

                if self.enableControlPlane and eachTypeOfCaptures == 'control':
                    vport.Capture.CurrentPacket.GetPacketFromControlCapture(
                        Arg2=packetIndex)

                stackObj = vport.Capture.CurrentPacket.Stack.find()

                for eachStack in stackObj:
                    displayName = eachStack.DisplayName
                    self.ixnObj.logInfo('\n Stack: %s' % displayName)
                    if capturePacketsToFile:
                        if eachTypeOfCaptures == 'data':
                            with open(packetCaptureFilenameData,
                                      'a') as packetCaptureFile:
                                packetCaptureFile.write('\n Stack: %s\n' %
                                                        displayName)

                        if eachTypeOfCaptures == 'control':
                            with open(packetCaptureFilenameControl,
                                      'a') as packetCaptureFile:
                                packetCaptureFile.write('\n Stack: %s\n' %
                                                        displayName)

                    for eachFieldObj in eachStack.Field.find():
                        fieldId = eachFieldObj.href.split('/')[-1]
                        fieldName = eachFieldObj.DisplayName
                        fieldValue = eachFieldObj.FieldValue
                        self.ixnObj.logInfo('\t{0}: {1}: {2}'.format(
                            fieldId, fieldName, fieldValue))

                        if capturePacketsToFile:
                            if eachTypeOfCaptures == 'data':
                                with open(packetCaptureFilenameData,
                                          'a') as packetCaptureFile:
                                    packetCaptureFile.write(
                                        '\t{0}: {1}: {2}\n'.format(
                                            fieldId, fieldName, fieldValue))

                            if eachTypeOfCaptures == 'control':
                                with open(packetCaptureFilenameControl,
                                          'a') as packetCaptureFile:
                                    packetCaptureFile.write(
                                        '\t{0}: {1}: {2}\n'.format(
                                            fieldId, fieldName, fieldValue))

    def packetCaptureGetCurrentPacketsHex(self, getUpToPacketNumber=10):
        """
        Description
           Returns captured packets in hex format.
           This API will default return 20 packet hex. You could increase the packet count.

        Parameters
            getUpToPacketNumber: None|The last packet number to get.
                                 Always starts at 1. If you state 10,
                                 then this function will get 1-10 packets.

        Return
            capturedData:  dictionary.   key is 'data' and/or 'control'
                capturedData['data']  is dictionary of packet hex data for Data Capture Buffer
                capturedData['control']  is dictionary of packet hex data for Control Capture Buffer
        """

        vport = self.portMgmtObj.getVports([self.captureRxPort])[0]
        totalDataCapturedPackets = vport.Capture.DataPacketCounter
        totalControlCapturedPackets = vport.Capture.ControlPacketCounter

        if type(totalDataCapturedPackets) != int:
            totalDataCapturedPackets = 0
        else:
            if getUpToPacketNumber is not None:
                totalDataCapturedPackets = getUpToPacketNumber

        if type(totalControlCapturedPackets) != int:
            totalControlCapturedPackets = 0
        else:
            if getUpToPacketNumber is not None:
                totalControlCapturedPackets = getUpToPacketNumber

        capturedData = {}
        for eachTypeOfCaptures, totalCapturedPackets in \
                zip(('data', 'control'), (totalDataCapturedPackets, totalControlCapturedPackets)):
            self.ixnObj.logInfo(
                'Getting captured packets for capture type: {0}'.format(
                    eachTypeOfCaptures))

            capturedData[eachTypeOfCaptures] = {}
            for packetIndex in range(1, int(totalCapturedPackets)):
                self.ixnObj.logInfo(
                    'Getting captured packet index number: {}/{}'.format(
                        packetIndex, getUpToPacketNumber))

                if totalDataCapturedPackets > 0:
                    vport.Capture.CurrentPacket.GetPacketFromDataCapture(
                        Arg2=packetIndex)

                if totalControlCapturedPackets > 0:
                    vport.Capture.CurrentPacket.GetPacketFromControlCapture(
                        Arg2=packetIndex)

                packetHex = vport.Capture.CurrentPacket.PacketHex
                capturedData[eachTypeOfCaptures][packetIndex] = packetHex
            return capturedData

    def getCapFile(self,
                   port,
                   typeOfCapture='data',
                   saveToTempLocation='c:\\Temp',
                   localLinuxLocation='.',
                   appendToSavedCapturedFile=None):
        """
        Get the latest captured .cap file from ReST API server to local Linux drive.

        Parameters
            port: Format:[IxiaIpAddress, slotNumber, cardNumber]
                  Example: [ixChassisIp, '2', '1']

            typeOfCapture: data|control

            saveToTempLocation: For Windows:
                                    Where to temporary save the .cap file on the ReST API server:
                                    Provide any path with double backslashes: C:\\Temp.
                                    The folder will be created if it doesn't exists.

                                For Linux, value= 'linux'.

            localLinuxLocation: Where to save the .cap file on the local Linux machine.

            appendToSavedCapturedFile: Add a text string to the captured file.

        Example:
            captureObj.getCapFile([ixChassisIp, '2', '1'], 'control', 'c:\\Temp', '/home/hgee/test')

        Syntaxes:

               DATA: {"arg1": "packetCaptureFolder"}  <-- This could be any name.
                                                Just a temporary folder to store the captured file.

               Wait for the /operations/savecapturefiles/<id> to complete.
                            May take up to a minute or more.

               For Windows API server:

                  DATA: {"arg1": "c:\\Results\\port2_HW.cap",
                         "arg2": "/api/v1/sessions/1/ixnetwork/files/port2_HW.cap"}

               For Linux API server:

                  DATA: {"arg1": "captures/packetCaptureFolder/port2_HW.cap",
                         "arg2": "/api/v1/sessions/<id>/ixnetwork/files/port2_HW.cap"}

        """

        vport = self.portMgmtObj.getVports([port])[0]
        vportName = vport.Name

        if appendToSavedCapturedFile is not None:
            self.ixNetwork.SaveCaptureFiles(Arg1=saveToTempLocation,
                                            Arg2=appendToSavedCapturedFile)
        else:
            self.ixNetwork.SaveCaptureFiles(Arg1=saveToTempLocation)

        # example capfilePathName: 'c:\\Results\\1-7-2_HW.cap'
        if typeOfCapture == 'control':
            if self.ixnObj.serverOs in ['windows', 'windowsConnectionMgr']:
                capFileToGet = saveToTempLocation + "\\" + vportName + "_SW.cap"
                filename = vportName + "_HW.cap"
            else:
                capFileToGet = saveToTempLocation + "/" + vportName + "_SW.cap"
                filename = vportName + "_HW.cap"

        if typeOfCapture == 'data':
            if self.ixnObj.serverOs in ['windows', 'windowsConnectionMgr']:
                capFileToGet = saveToTempLocation + "\\" + vportName + "_HW.cap"
                filename = vportName + "_HW.cap"
            else:
                capFileToGet = saveToTempLocation + "/" + vportName + "_HW.cap"
                filename = vportName + "_HW.cap"

        try:
            self.ixNetwork.CopyFile(
                Files(capFileToGet, local_file=False),
                localLinuxLocation + "\\" + filename + ".cap")
        except Exception as err:
            self.ixnObj.logInfo("Error {} ".format(err))
            self.ixNetwork.CopyFile(
                Files(capFileToGet, local_file=False),
                localLinuxLocation + "/" + filename + ".cap")