aboutsummaryrefslogtreecommitdiffstats
path: root/functest/opnfv_tests/vnf/ims/ixia/utils/IxLoadUtils.py
blob: 50dfbc661fbf84b17d4376656bca5917b135cd6d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
#!/usr/bin/env python

# Copyright (c) 2017 IXIA and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
# http://www.apache.org/licenses/LICENSE-2.0

import requests
import sys
import time
import logging

from functest.opnfv_tests.vnf.ims.ixia.utils import IxRestUtils


kActionStateFinished = 'finished'
kActionStatusSuccessful = 'Successful'
kActionStatusError = 'Error'
kTestStateUnconfigured = 'Unconfigured'

logger = logging.getLogger(__name__)


def stripApiAndVersionFromURL(url):

    # remove the slash (if any) at the beginning of the url

    if url[0] == '/':
        url = url[1:]

    urlElements = url.split('/')
    if 'api' in url:

        # strip the api/v0 part of the url

        urlElements = urlElements[2:]

    return '/'.join(urlElements)


def waitForActionToFinish(connection, replyObj, actionUrl):
    """
    This method waits for an action to finish executing. after a POST request
    is sent in order to start an action, The HTTP reply will contain,
    in the header, a 'location' field, that contains an URL.
    The action URL contains the status of the action. we perform a GET on that
    URL every 0.5 seconds until the action finishes with a success.
    If the action fails, we will throw an error and
    print the action's error message.
    """

    actionResultURL = replyObj.headers.get('location')
    if actionResultURL:
        actionResultURL = stripApiAndVersionFromURL(actionResultURL)
        actionFinished = False

        while not actionFinished:
            actionStatusObj = connection.httpGet(actionResultURL)

            if actionStatusObj.state == kActionStateFinished:
                if actionStatusObj.status == kActionStatusSuccessful:
                    actionFinished = True
                else:
                    errorMsg = "Error while executing action '%s'." \
                        % actionUrl

                    if actionStatusObj.status == kActionStatusError:
                        errorMsg += actionStatusObj.error

                    print errorMsg

                    sys.exit(1)
            else:
                time.sleep(0.1)


def performGenericOperation(connection, url, payloadDict):
    """
    This will perform a generic operation on the given url,
    it will wait for it to finish.
    """

    data = IxRestUtils.formatDictToJSONPayload(payloadDict)
    reply = connection.httpPost(url=url, data=data)

    waitForActionToFinish(connection, reply, url)

    return reply


def performGenericPost(connection, listUrl, payloadDict):
    """
    This will perform a generic POST method on a given url
    """

    data = IxRestUtils.formatDictToJSONPayload(payloadDict)

    reply = connection.httpPost(url=listUrl, data=data)
    try:
        newObjPath = reply.headers['location']
    except:
        raise Exception('Location header is not present. \
                        Please check if the action was created successfully.')

    newObjID = newObjPath.split('/')[-1]
    return newObjID


def performGenericDelete(connection, listUrl, payloadDict):
    """
    This will perform a generic DELETE method on a given url
    """

    data = IxRestUtils.formatDictToJSONPayload(payloadDict)

    reply = connection.httpDelete(url=listUrl, data=data)
    return reply


def performGenericPatch(connection, url, payloadDict):
    """
    This will perform a generic PATCH method on a given url
    """

    data = IxRestUtils.formatDictToJSONPayload(payloadDict)

    reply = connection.httpPatch(url=url, data=data)
    return reply


def createSession(connection, ixLoadVersion):
    """
    This method is used to create a new session.
    It will return the url of the newly created session
    """

    sessionsUrl = 'sessions'
    data = {'ixLoadVersion': ixLoadVersion}

    sessionId = performGenericPost(connection, sessionsUrl, data)

    newSessionUrl = '%s/%s' % (sessionsUrl, sessionId)
    startSessionUrl = '%s/operations/start' % newSessionUrl

    # start the session

    performGenericOperation(connection, startSessionUrl, {})

    logger.debug('Created session no %s' % sessionId)

    return newSessionUrl


def deleteSession(connection, sessionUrl):
    """
    This method is used to delete an existing session.
    """

    deleteParams = {}
    performGenericDelete(connection, sessionUrl, deleteParams)


def uploadFile(connection, url, fileName, uploadPath, overwrite=True):
    headers = {'Content-Type': 'multipart/form-data'}
    params = {'overwrite': overwrite, 'uploadPath': uploadPath}

    logger.debug('Uploading...')
    try:
        with open(fileName, 'rb') as f:
            resp = requests.post(url, data=f, params=params,
                                 headers=headers)
    except requests.exceptions.ConnectionError, e:
        raise Exception('Upload file failed. Received connection error. \
                        One common cause for this error is the size of the \
                        file to be uploaded.The web server sets a limit of 1GB\
                        for the uploaded file size. \
                        Received the following error: %s' % str(e))
    except IOError, e:
        raise Exception('Upload file failed. Received IO error: %s'
                        % str(e))
    except Exception:
        raise Exception('Upload file failed. Received the following error: %s'
                        % str(e))
    else:
        logger.debug('Upload file finished.')
        logger.debug('Response status code %s' % resp.status_code)
        logger.debug('Response text %s' % resp.text)


def loadRepository(connection, sessionUrl, rxfFilePath):
    """
    This method will perform a POST request to load a repository.
    """

    loadTestUrl = '%s/ixload/test/operations/loadTest' % sessionUrl
    data = {'fullPath': rxfFilePath}

    performGenericOperation(connection, loadTestUrl, data)


def saveRxf(connection, sessionUrl, rxfFilePath):
    """
    This method saves the current rxf to the disk of the machine on
    which the IxLoad instance is running.
    """

    saveRxfUrl = '%s/ixload/test/operations/saveAs' % sessionUrl
    rxfFilePath = rxfFilePath.replace('\\', '\\\\')
    data = {'fullPath': rxfFilePath, 'overWrite': 1}

    performGenericOperation(connection, saveRxfUrl, data)


def runTest(connection, sessionUrl):
    """
    This method is used to start the currently loaded test.
    After starting the 'Start Test' action, wait for the action to complete.
    """

    startRunUrl = '%s/ixload/test/operations/runTest' % sessionUrl
    data = {}

    performGenericOperation(connection, startRunUrl, data)


def getTestCurrentState(connection, sessionUrl):
    """
    This method gets the test current state.
    (for example - running, unconfigured, ..)
    """

    activeTestUrl = '%s/ixload/test/activeTest' % sessionUrl
    testObj = connection.httpGet(activeTestUrl)

    return testObj.currentState


def getTestRunError(connection, sessionUrl):
    """
    This method gets the error that appeared during the last test run.
    If no error appeared (the test ran successfully),
    the return value will be 'None'.
    """

    activeTestUrl = '%s/ixload/test/activeTest' % sessionUrl
    testObj = connection.httpGet(activeTestUrl)

    return testObj.testRunError


def waitForTestToReachUnconfiguredState(connection, sessionUrl):
    """
    This method waits for the current test to reach the 'Unconfigured' state.
    """

    while getTestCurrentState(connection, sessionUrl) \
            != kTestStateUnconfigured:
        time.sleep(0.1)


def pollStats(connection, sessionUrl, watchedStatsDict, pollingInterval=4):
    """
    This method is used to poll the stats.
    Polling stats is per request but this method does a continuous poll.
    """

    statSourceList = watchedStatsDict.keys()
    statsDict = {}

    collectedTimestamps = {}
    testIsRunning = True

    # check stat sources

    for statSource in statSourceList[:]:
        statSourceUrl = '%s/ixload/stats/%s/values' % (sessionUrl, statSource)
        statSourceReply = connection.httpRequest('GET', statSourceUrl)
        if statSourceReply.status_code != 200:
            logger.debug("Warning - Stat source '%s' does not exist. \
                         Will ignore it." % statSource)
            statSourceList.remove(statSource)

    # check the test state, and poll stats while the test is still running

    while testIsRunning:

        # the polling interval is configurable.
        # by default, it's set to 4 seconds

        time.sleep(pollingInterval)

        for statSource in statSourceList:
            valuesUrl = '%s/ixload/stats/%s/values' % (sessionUrl, statSource)

            valuesObj = connection.httpGet(valuesUrl)
            valuesDict = valuesObj.getOptions()

            # get just the new timestamps - that were not previously
            # retrieved in another stats polling iteration

            newTimestamps = [int(timestamp) for timestamp in
                             valuesDict.keys() if timestamp
                             not in collectedTimestamps.get(statSource,
                             [])]
            newTimestamps.sort()

            for timestamp in newTimestamps:
                timeStampStr = str(timestamp)

                collectedTimestamps.setdefault(
                    statSource, []).append(timeStampStr)

                timestampDict = statsDict.setdefault(
                    statSource, {}).setdefault(timestamp, {})

                # save the values for the current timestamp,
                # and later print them

                logger.info(' -- ')
                for (caption, value) in \
                        valuesDict[timeStampStr].getOptions().items():
                    if caption in watchedStatsDict[statSource]:
                        logger.info(' %s -> %s' % (caption, value))
                        timestampDict[caption] = value

        testIsRunning = getTestCurrentState(connection, sessionUrl) \
            == 'Running'

    logger.debug('Stopped receiving stats.')
    return timestampDict


def clearChassisList(connection, sessionUrl):
    """
    This method is used to clear the chassis list.
    After execution no chassis should be available in the chassisListself.
    """

    chassisListUrl = '%s/ixload/chassischain/chassisList' % sessionUrl
    deleteParams = {}
    performGenericDelete(connection, chassisListUrl, deleteParams)


def configureLicenseServer(connection, sessionUrl, licenseServerIp):
    """
    This method is used to clear the chassis list.
    After execution no chassis should be available in the chassisList.
    """

    chassisListUrl = '%s/ixload/preferences' % sessionUrl
    patchParams = {'licenseServer': licenseServerIp}
    performGenericPatch(connection, chassisListUrl, patchParams)


def addChassisList(connection, sessionUrl, chassisList):
    """
    This method is used to add one or more chassis to the chassis list.
    """

    chassisListUrl = '%s/ixload/chassisChain/chassisList' % sessionUrl

    for chassisName in chassisList:
        data = {'name': chassisName}
        chassisId = performGenericPost(connection, chassisListUrl, data)

        # refresh the chassis

        refreshConnectionUrl = '%s/%s/operations/refreshConnection' \
            % (chassisListUrl, chassisId)
        performGenericOperation(connection, refreshConnectionUrl, {})


def assignPorts(connection, sessionUrl, portListPerCommunity):
    """
    This method is used to assign ports from a connected chassis
    to the required NetTraffics.
    """

    communtiyListUrl = '%s/ixload/test/activeTest/communityList' \
        % sessionUrl

    communityList = connection.httpGet(url=communtiyListUrl)

    for community in communityList:
        portListForCommunity = portListPerCommunity.get(community.name)

        portListUrl = '%s/%s/network/portList' % (communtiyListUrl,
                                                  community.objectID)

        if portListForCommunity:
            for portTuple in portListForCommunity:
                (chassisId, cardId, portId) = portTuple
                paramDict = {'chassisId': chassisId, 'cardId': cardId,
                             'portId': portId}

                performGenericPost(connection, portListUrl, paramDict)