Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dev convert to restpy #139

Open
wants to merge 7 commits into
base: dev_convertToRestpy
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 28 additions & 57 deletions RestApi/Python/Modules/IxNetRestApi.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@
import datetime
import platform
import time
from ixnetwork_restpy import TestPlatform
import re
import traceback
# from ixnetwork_restpy import TestPlatform
from ixnetwork_restpy import SessionAssistant


class IxNetRestApiException(Exception):
Expand Down Expand Up @@ -51,7 +54,7 @@ def __init__(self, apiServerIp=None, serverIpPort=None,
includeDebugTraceback=True, sessionId=None,
httpsSecured=None, apiKey=None,
generateLogFile=True, robotFrameworkStdout=False,
linuxApiServerTimeout=120):
linuxApiServerTimeout=120, traceLevel='all', clearConfig=False):
"""
Description
Initializing default parameters and making a connection to the API server
Expand Down Expand Up @@ -128,7 +131,8 @@ def __init__(self, apiServerIp=None, serverIpPort=None,
self.password = password
self.apiKey = apiKey
self.verifySslCert = verifySslCert
self.linuxApiServerIp = apiServerIp
self.apiServerIp = apiServerIp
self.deleteSessionAfterTest = deleteSessionAfterTest
self.manageSessionMode = manageSessionMode
self.apiServerPort = serverIpPort
self.webQuickTest = webQuickTest
Expand All @@ -137,6 +141,15 @@ def __init__(self, apiServerIp=None, serverIpPort=None,
self.linuxChassisIp = linuxChassisIp
self.linuxApiServerTimeout = linuxApiServerTimeout
self.sessionId = sessionId
self.clearConfig = clearConfig

logleveldict = {'none':SessionAssistant.LOGLEVEL_NONE,
'info':SessionAssistant.LOGLEVEL_INFO,
'warning':SessionAssistant.LOGLEVEL_WARNING,
'request':SessionAssistant.LOGLEVEL_REQUEST,
'request_response':SessionAssistant.LOGLEVEL_REQUEST_RESPONSE,
'all':SessionAssistant.LOGLEVEL_ALL}
self.logLevel = logleveldict[traceLevel]

# Make Robot print to stdout
if self.robotFrameworkStdout:
Expand All @@ -152,60 +165,18 @@ def __init__(self, apiServerIp=None, serverIpPort=None,

if type(generateLogFile) != bool:
self.restLogFile = generateLogFile

if self.serverOs == 'windows':
if self.apiServerPort is None:
self.apiServerPort = 11009
else:
self.apiServerPort = serverIpPort
self.testPlatform = TestPlatform(ip_address=self.linuxApiServerIp,
rest_port=self.apiServerPort,
platform=self.serverOs,
verify_cert=verifySslCert,
log_file_name=self.restLogFile)
self.session = self.testPlatform.Sessions.add()
self.sessionId = self.session.Id
self.ixNetwork = self.session.Ixnetwork

if self.serverOs == 'windowsConnectionMgr':
if self.sessionId:
self.testPlatform = TestPlatform(
ip_address=self.linuxApiServerIp,
rest_port=self.apiServerPort,
platform=self.serverOs,
verify_cert=verifySslCert,
log_file_name=self.restLogFile)

if self.serverOs == 'linux':
if self.apiServerPort is None:
self.apiServerPort = 443

if username is None or password is None:
self.username = 'admin'
self.password = 'admin'

self.testPlatform = TestPlatform(ip_address=self.linuxApiServerIp,
rest_port=self.apiServerPort,
platform=self.serverOs,
verify_cert=verifySslCert,
log_file_name=self.restLogFile)
self.testPlatform.Authenticate(self.username, self.password)

if apiKey is not None and sessionId is None:
raise IxNetRestApiException('Providing an apiKey must also provide a sessionId.')
# Connect to an existing session on the Linux API server
if apiKey and sessionId:
self.session = self.testPlatform.Sessions.find(Id=sessionId)
self.ixNetwork = self.session.Ixnetwork

if apiKey is None and sessionId:
self.session = self.testPlatform.Sessions.find(Id=sessionId)
self.ixNetwork = self.session.Ixnetwork

if apiKey is None and sessionId is None:
self.session = self.testPlatform.Sessions.add()
self.sessionId = self.session.Id
self.ixNetwork = self.session.Ixnetwork

try:
session = SessionAssistant(IpAddress=self.apiServerIp, UserName=self.username, Password=self.password,
RestPort=serverIpPort, ApiKey=self.apiKey, LogFilename=self.restLogFile,
SessionId=self.sessionId, LogLevel=self.logLevel, ClearConfig=self.clearConfig)
self.ixNetwork = session.Ixnetwork
self.testPlatform = session.TestPlatform
self.sessionId = session.Ixnetwork.parent.Id
except (IxNetRestApiException, Exception, KeyboardInterrupt) as errMsg:
if bool(re.search('ConnectionError', traceback.format_exc())):
print('\n%s' % traceback.format_exc())
raise IxNetRestApiException('Connection Error')

if licenseServerIp or licenseMode or licenseTier:
self.configLicenseServerDetails(
Expand Down
21 changes: 20 additions & 1 deletion RestApi/Python/Modules/IxNetRestApiFileMgmt.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import re
import os
import json
import time

from IxNetRestApi import IxNetRestApiException
from ixnetwork_restpy.files import Files
import datetime
Expand Down Expand Up @@ -28,7 +30,7 @@ def setMainObject(self, mainObject):
"""
self.ixnObj = mainObject

def loadConfigFile(self, configFile, localFile=True):
def loadConfigFile(self, configFile, localFile=True, portList=None):
"""
Description
Load a saved config file.
Expand All @@ -43,11 +45,28 @@ def loadConfigFile(self, configFile, localFile=True):

localFile: (bool): For Windows API server and Connection Mgr running on a Windows
server only. Set to False if the config file is in the Windows API server filesystem.

portList: (list): This takes the list of ports to be connected to once load config is performed
If the value is None(default value), then chassis, slot and port under configuration file are retained.
If not None, chassis, slot and port configurations loaded using configuration file will get replaced with
the given parameters
Example: [['10.39.64.197', '1', '1'],
['10.39.64.197', '1', '2']]
"""

self.ixnObj.logInfo("Loading Config File {}".format(configFile))
try:
self.ixNetwork.LoadConfig(Files(configFile, local_file=localFile))
if portList is not None:
vportList = self.ixNetwork.Vport.find()
chassisIp = portList[0][0]
connectedChassis = self.ixNetwork.AvailableHardware.Chassis.find()
if chassisIp != connectedChassis.Hostname:
self.ixNetwork.AvailableHardware.Chassis.find().remove()
self.ixNetwork.AvailableHardware.Chassis.add(Hostname=chassisIp)
for port, vport in zip(portList, vportList):
vport.update(Location=';'.join(port))

except Exception as err:
self.ixnObj.logInfo("Error with Load config {}".format(err))
raise Exception("Failed to load config file {} ".format(configFile))
Expand Down
4 changes: 2 additions & 2 deletions RestApi/Python/Modules/IxNetRestApiPacketCapture.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,8 +141,8 @@ def packetCaptureGetCurrentPackets(self, getUpToPacketNumber=20, capturePacketsT
'options: enableDataPlane|enableControlPlane')

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

if type(totalDataCapturedPackets) != int:
totalDataCapturedPackets = 0
Expand Down
25 changes: 23 additions & 2 deletions RestApi/Python/Modules/IxNetRestApiPortMgmt.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,19 @@ def getVports(self, portList):
vportList = []

self.ixnObj.logInfo("get vport objects for portList {}".format(portList))
portConnected = False
if len(self.ixnObj.ixNetwork.Vport.find()) == 0:
# this means no ports are configured
return
else:
for vport in self.ixnObj.ixNetwork.Vport.find():
if vport.IsConnected == True:
portConnected = True
break

if portConnected == False:
return

for vport in self.ixnObj.ixNetwork.Vport.find():
assignedTo = vport.AssignedTo
if assignedTo == '':
Expand All @@ -248,6 +261,10 @@ def getVports(self, portList):
port = [chassisIp, cardNum, portNum]
if port in portList:
vportList.append(vport)

if not vportList:
raise Exception("Unable to find vport for the given portList {} ".format(portList))

return vportList

def getPhysicalPortsFromCreatedVports(self):
Expand Down Expand Up @@ -398,9 +415,13 @@ def releasePorts(self, portList):
[[ixChassisIp, str(cardNum), str(portNum)], [], [] ...]
"""
self.ixnObj.logInfo('Release selected ports {} from configuration'.format(portList))
# vportConfiguredList = [vport for vport in self.ixNetwork.Vport.find()]
# if vportConfiguredList != portList[0]:
# return
vportList = self.getVports(portList)
for vport in vportList:
vport.ReleasePort()
if vportList != None:
for vport in vportList:
vport.ReleasePort()

def resetPortCpu(self, vportList=None, portList=None, timeout=90):
"""
Expand Down
4 changes: 4 additions & 0 deletions RestApi/Python/Modules/IxNetRestApiProtocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -589,6 +589,10 @@ def configDhcpClientV4(self, obj, **kwargs):
if 'multiplier' in kwargs:
del kwargs['multiplier']

if 'useRapdCommit' in kwargs:
kwargs['useRapidCommit'] = kwargs['useRapdCommit']
del kwargs['useRapdCommit']

for key, value in kwargs.items():
key = key[0:1].capitalize() + key[1:]
multivalueObj = getattr(dhcpObj, key)
Expand Down
54 changes: 17 additions & 37 deletions RestApi/Python/Modules/IxNetRestApiTraffic.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,13 @@ def configTrafficItem(self, mode=None, obj=None, trafficItem=None, endpoints=Non
trackBy = trafficItem['trackBy']
del trafficItem['trackBy']

if 'srcDestMesh' in trafficItem:
if trafficItem['srcDestMesh'] not in ['fullMesh', 'manyToMany', 'none', 'oneToOne']:
trafficItem['srcDestMesh'] = trafficItem['srcDestMesh'].replace("-", "")
for element in ['fullMesh', 'manyToMany', 'none', 'oneToOne']:
if element.lower() == trafficItem['srcDestMesh'].lower():
trafficItem['srcDestMesh'] = element

for item, value in trafficItem.items():
itemObj = item[0:1].capitalize() + item[1:]
setattr(trafficItemObj, itemObj, value)
Expand Down Expand Up @@ -229,47 +236,20 @@ def configTrafficItem(self, mode=None, obj=None, trafficItem=None, endpoints=Non
self.configConfigElements(trafficItemObj.HighLevelStream.find(), eachHighLevelStream)
pass

# if configElements != "" and trafficItemObj is not None:
# configElementObj = trafficItemObj.ConfigElement.find()
#
# for configEle in configElements:
# if 'transmissionType' in configEle:
# configElementObj.TransmissionControl.Type = configEle['transmissionType']
# del configEle['transmissionType']
#
# if 'frameCount' in configEle:
# configElementObj.TransmissionControl.FrameCount = configEle['frameCount']
# del configEle['frameCount']
#
# if 'frameRate' in configEle:
# configElementObj.FrameRate.Rate = configEle['frameRate']
# del configEle['frameRate']
#
# if 'frameRateType' in configEle:
# configElementObj.FrameRate.Type = configEle['frameRateType']
# del configEle['frameRateType']
#
# if 'frameSize' in configEle:
# configElementObj.FrameSize.FixedSize = configEle['frameSize']
# del configEle['frameSize']
#
# if 'portDistribution' in configEle:
# configElementObj.FrameRateDistribution.PortDistribution \
# = configEle['portDistribution']
# del configEle['portDistribution']
#
# if 'streamDistribution' in configEle:
# configElementObj.FrameRateDistribution.StreamDistribution \
# = configEle['streamDistribution']
# del configEle['streamDistribution']

if mode == 'modify':

if trafficItem is not None:
trafficItemObj = obj
if 'trackBy' in trafficItem:
trackBy = trafficItem['trackBy']
del trafficItem['trackBy']

if 'srcDestMesh' in trafficItem:
if trafficItem['srcDestMesh'] not in ['fullMesh', 'manyToMany', 'none', 'oneToOne']:
trafficItem['srcDestMesh'] = trafficItem['srcDestMesh'].replace("-", "")
for element in['fullMesh', 'manyToMany', 'none', 'oneToOne']:
if element.lower() == trafficItem['srcDestMesh'].lower():
trafficItem['srcDestMesh'] = element

for item, value in trafficItem.items():
itemObj = item[0:1].capitalize() + item[1:]
setattr(trafficItemObj, itemObj, trafficItem[item])
Expand Down Expand Up @@ -837,13 +817,13 @@ def configPacketHeaderField(self, stackIdObj, fieldName, data):
raise IxNetRestApiException('Failed to located your provided fieldName:', fieldName)
self.ixnObj.logInfo('configPacketHeaderFieldId: fieldIdObj: %s' % stackIdObj.href +
'/field/' + str(fieldId), timestamp=False)
if 'auto' in data:
fieldObj.Auto = data['auto']
if data.get('valueType'):
fieldObj.ValueType = data.get('valueType')
else:
fieldObj.ValueType = 'singleValue'
data['valueType'] = 'singleValue'
if data.get('auto'):
fieldObj.Auto = data['auto']
if data.get('valueType') == 'singleValue':
fieldObj.SingleValue = data['fieldValue'] if data.get('fieldValue') else 0
elif data.get('valueType') in ['increment', 'decrement']:
Expand Down