-
Notifications
You must be signed in to change notification settings - Fork 7
/
cvpServices.py
2964 lines (2716 loc) · 124 KB
/
cvpServices.py
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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2015 Arista Networks, Inc. All rights reserved.
# Arista Networks, Inc. Confidential and Proprietary.
'''
@Copyright: 2015-2016 Arista Networks, Inc.
Arista Networks, Inc. Confidential and Proprietary.
CvpServices script is used for making request to the Cvp web-serves.
These requests comprise of addition, modification, deletion and retrieval of
Cvp instance.
It contains 2 classes
CvpError -- Handles exceptions
CvpService -- Handles requests
'''
import json
import uuid
import os
import errorCodes
import base64
import time
import requests
import string
from requests.utils import quote
try:
# squelch annoying warnings
requests.packages.urllib3.disable_warnings()
except AttributeError:
pass # not applicable to older versions of requests
DEFAULT_USER = "cvpadmin"
DEFAULT_PASSWORD = "cvpadmin"
UNDEF_CONTAINER_KEY = 'undefined_container'
UNDEF_CONTAINER_NAME = 'Undefined'
ROOT_CONTAINER_KEY = 'root'
ONBOARD_DEVICE_BATCH_SIZE = 200
DEVICE_MOVE_BATCH_SIZE = 200
PROVISION_STREAMING_DEVICE_BATCH_SIZE = 200
trace = ( 'cvpServices' in os.getenv( 'TRACE', '' ).split( ',' ) )
class CvpError( Exception ):
'''CvpError is a class for containing the exception information and passing that
exception information upwards to the application layer
Public methods:
__str__()
Instance variables:
errorMessage -- information corresponding to the error code in response
errorCode -- error code value provided in response to the HTTP/HTTPS request
'''
def __init__( self, errorCode, errorMessage='', response=None ):
if not errorMessage:
if errorCode in errorCodes.ERROR_MAPPING:
errorMessage = errorCodes.ERROR_MAPPING.get( errorCode )
else:
errorMessage = 'Unknown Error Code: {} not listed in errorCodes.py'.format( errorCode )
# Pass errorMessage for repr in Exception class to work
super( CvpError, self ).__init__( errorMessage )
# Few errorCodes are in alphanumeric and string format, adding the additional
# check before casting to int
if str( errorCode ).isdigit():
self.errorCode = int( errorCode )
else:
self.errorCode = errorCode
self.errorMessage = errorMessage
self.response = response # The original response in its entirety,
# when available
def __str__( self ):
'''returns string value of the object'''
return "{} : {}".format( self.errorCode, self.errorMessage if self.errorMessage else '' )
class CvpService( object ):
'''CvpService class is responsible for hitting endpoints of the Cvp web-server
for retrieving, updating, adding and deleting state of Cvp
Public methods:
authenticate( username, password )
getConfigletsInfo()
getConfigletBuilder( configletBuilderKey )
imageBundleAppliedContainers(imageBundleName )
searchContainer( containerName )
imageBundleAppliedDevices( imageBundleName )
addImage( imageName )
downloadImage( imageName, imageId, filePath )
firstLoginDefaultPasswordReset( newPassword, emaildId )
getInventory()
configAppliedContainers( configletName )
configAppliedDevices ( configletName )
getImagesInfo()
addConfiglet( configletName, configletContent )
addConfigletBuilder( ConfigletBuilder )
getConfigletByName( configletName )
updateConfiglet( configletName, configletContent, configletKey,
waitForTaskIds )
deleteConfiglet( configletName, configletKey )
deleteConfigletBuilder( ConfigletBuilder )
saveImageBundle( imageBundleName, imageBundleCertified, imageInfoList )
getImageBundleByName( imageBundleName )
updateImageBundle( imageBundleName, imageBundleCertified, imageInfoList,
imageBundleKey )
addToInventory( deviceIpAddress, parentContainerId )
saveInventory()
retryAddToInventory( deviceKey, deviceIpAddress, username, password )
executeTask( taskId )
getTasks( status )
addNoteToTask( taskId, note )
getImageBundles()
deleteImageBundle( imageBundleKey, imageBundleName )
deleteImageBundles( imageBundleInfos )
deleteDuplicateDevice( tempDeviceId )
deleteContainer( containerName, containerKey, parentContainerName,
parentKey )
deleteDevice( deviceKey, parentContainerName, containerKey )
factoryResetDevice( self, containerName, containerKey, deviceFqdn, deviceKey )
applyConfigToDevice( deviceIpAddress, deviceFqdn, deviceKey,
configNameList, configKeyList )
applyConfigToContainer( containerName, containerKey, configNameList,
configKeyList )
removeConfigFromContainer( containerName, containerKey, configNameList,
configKeyList )
addContainer( containerName, containerParentName, parentContainerId )
applyImageBundleToDevice( deviceKey, deviceFqdn, imageBundleName,
imageBundleKey )
applyImageBundleToContainer( containerName, containerKey,imageBundleName,
imageBundleKey )
deviceComplianceCheck( deviceConfigIdList, deviceMacAddress )
changeContainerName( oldName, newName, containerKey )
generateAutoConfiglet( deviceKeyList, configletBuilderKey,
configletBuilderName, containerKey, pageType )
generateFormConfiglet( deviceKeyList, configletBuilderKey,
configletBuilderName, containerKey, formValues, pageType )
deployDevice( self, device, targetContainer, info, configletList, image )
cvpVersionInfo()
getRoles()
addRole( roleName, roleModuleList )
getRole( roleId )
updateRole( roleName, description, moduleList, roleKey )
updateConfigletBuilder( ConfigletBuilderName, formList, mainScript,
configletBuilderId, waitForTaskIds )
addTaskLog( taskId, message, src )
getSnapshotTemplates()
deleteSnapshotTemplates( templateList )
getTemplateInfo( key )
getTemplatesInfo( keys )
captureDeviceSnapshot()
scheduleSnapshotTemplate()
getRollbackDeviceConfigs( deviceId, current, timestamp )
addTempRollbackAction( rollbackTimestamp, netElementId,
rollbackType, targetIp, configRollbackInfo,
imageRollbackInfo )
addNetworkRollbackTempActions( containerId, rollbackTime, rollbackType,
startIndex, endIndex )
addNetworkRollbackChangeControl()
getLabels( label )
getLabelDevInfo( label )
provisionStreamingDevice( deviceIDs, useBatching )
Instance variables:
port -- Port where Http/Https request made to web server
url -- denotes the host sub-part of the URL
headers -- headers required for the Http/Https requests
hostname -- name of the host
cookies -- cookies of the session establised
tmpDir -- temporary directory enclosing file operations
'''
def __init__( self, host, ssl, port, tmpDir='' ):
self.host = host
self.ssl = ssl
self.port = port
self.tmpDir = tmpDir
self.cookies = {}
self.url_ = self.url()
self.headers = { 'Accept' : 'application/json',
'Content-Type' : 'application/json' }
def isCloudService( self ):
return False
def getSuperUser( self ):
return 'cvpadmin'
def getDefaultUsers( self ):
return [ 'cvpadmin' ]
def setInitialPassword( self, user, password, email ):
self.authenticate( 'cvpadmin', 'cvpadmin' )
self.firstLoginDefaultPasswordReset( password, email )
def hostIs( self, host ):
self.host = host
self.url_ = self.url()
def url( self ):
self.url_ = '%s://%s:%d' % ( 'https' if self.ssl else 'http',
self.host, self.port )
return self.url_
def doRequest( self, method, url, *args, **kwargs ):
'''Issues an Http request
Arguments:
method -- Http method
url -- endpoint of the request
*args -- multiple arguments passed
**kwargs -- multiple arguments passed that need to be handled using name
Returns:
response -- Json response from the endpoint
Raises:
CvpError -- If response is not json or response contains error code
If parameter data structures are incorrect
'''
if not 'cookies' in kwargs:
kwargs[ 'cookies' ] = self.cookies
kwargs[ 'verify' ] = False
if trace:
print url
response = method( url, *args, **kwargs )
if not response.ok:
# raise_for_status() does not provide response.text in the exception data
print 'response.text:', response.text
response.raise_for_status()
responseJson = response.json()
# grpc can return an empty response. e.g. to a GetAll
if responseJson is not None and 'errorCode' in responseJson:
if trace:
print responseJson
errorCode = responseJson.get( 'errorCode', 0 )
errorMessage = responseJson.get( 'errorMessage', '' )
raise CvpError( errorCode, errorMessage, response=responseJson )
return responseJson
def _authenticationRequest( self, method, url, *args, **kwargs ):
'''Issues an Http request for authentication
Arguments:
method -- Http method
url -- endpoint of the request
*args -- multiple arguments passed
**kwargs -- multiple arguments passed that need to be handled using name
Returns:
response -- Information of the established session
(cookies, access_token etc.)
Raises:
CvpError -- If response contains error code or response is not json
If parameter data structures are incorrect
'''
kwargs[ 'verify' ] = False
response = method( url, *args, **kwargs )
response.raise_for_status()
responseJson = response.json()
if 'errorCode' in response.text:
errorCode = responseJson.get( 'errorCode', 0 )
errorMessage = responseJson.get( 'errorMessage', '' )
raise CvpError( errorCode, errorMessage, response=responseJson )
return response
def getConfigletsInfo( self ):
'''Retrieves information of all configlets.
Returns:
configlets[ 'data' ] -- List of configlets with details
( type : List of Dict )
'''
configlets = self.doRequest( requests.get,
'%s/cvpservice/configlet/getConfiglets.do?startIndex=%d&endIndex=%d'
% ( self.url_, 0, 0 ) )
return configlets[ 'data' ]
def getConfigletBuilder( self, configletBuilderKey ):
''' Retrieves information about a particular Configlet Builder
Arguments:
configletBuilderKey -- unique key associated with the Configlet Builder
Response:
Information like name, form list, mainscript about Configlet Builder
'''
configletBuilderData = self.doRequest( requests.get,
'%s/cvpservice/configlet/getConfigletBuilder.do?type=&id=%s'
% ( self.url_, configletBuilderKey ) )
return configletBuilderData[ 'data' ]
def validateAndCompareConfiglets( self, deviceMacAddress, configletKeyList ):
''' Validates the configlet list on a device.
Arguments:
deviceMacAddress -- MAC address of the device
configletKeyList -- list of unique keys associated with the configlets
Returns:
response -- Designed Config, Running Config and Reconciled config
'''
requestPayload = { 'netElementId' : deviceMacAddress,
'configIdList' : configletKeyList,
'pageType' : 'validateConfig'
}
validateResponse = self.doRequest( requests.post,
'%s/cvpservice/provisioning/v2/validateAndCompareConfiglets.do'
% self.url_,
data=json.dumps( requestPayload ) )
return validateResponse
def reconcileContainer( self, containerId, reconcileAll=False ):
'''Initiates a reconcile opertion on the container identified by 'containerId'
Arguments:
containerId: ID of the container.
Returns:
response: ID of the event that was generated as a result of the reconcile
'''
result = self.doRequest( requests.get,
'%s/cvpservice/provisioning/containerLevelReconcile.do?containerId=%s'
'&reconcileAll=%s' % ( self.url_, containerId, reconcileAll ) )
return result
def deviceComplianceCheck( self, deviceMacAddress ):
''' Runs compliance check on the device. Finds differences in
designed configuration according to Cvp application and actual
running configuration on the device.
Arguments:
deviceConfigIdList -- Configlet Id list of configlets applied to device
as per the Designed configuration
deviceMacAddress -- Mac address of the device
Returns:
complianceReport -- Information about the compliance check of the
device.
Raises:
CvpError -- If device Mac-Address is invalid
If parameter data structures are incorrect
'''
return self.complianceCheck( 'netelement', deviceMacAddress )
def complianceCheck( self, nodeType, nodeId ):
'''Initiate compliance check on the specified node.
Arguments:
nodeType: 'netelement' or 'container'
nodeId: MAC address (in case of netelement), or
Container ID (in case of container)
'''
assert nodeType in ( 'netelement', 'container' )
data = { 'nodeId' : nodeId,
'nodeType' : nodeType
}
result = self.doRequest( requests.post,
'%s/cvpservice/ztp/checkCompliance.do'
% self.url_, data=json.dumps( data ) )
return result
def authenticate( self, username, password ):
'''Authentication with the web server
Arguments:
username -- login username ( type : String )
password -- login password ( type : String )
Raises:
CvpError -- If username and password combination is invalid
If parameter data structures are incorrect
'''
authData = { 'userId' : username, 'password' : password }
authentication = self._authenticationRequest( requests.post,
'%s/cvpservice/login/authenticate.do' % self.url_, data=json.dumps( authData ),
headers=self.headers )
self.cookies[ 'access_token' ] = authentication.cookies[ 'access_token' ]
# 'role' cookie is mandatory for older releases of CVP i.e. 2015.*
# and 2016.1.0
if 'role' in authentication.cookies:
self.cookies[ 'role' ] = authentication.cookies[ 'role' ]
def authenticateOauth( self, provider, user ):
'''Authentication with an oauth provider
Arguments:
provider -- registered oauth provider name
user -- login username
Raises:
CvpError -- If status code of response is >= 400
'''
def trim_padding( text ):
if not text.endswith( '=' ):
return text
text = text[ :len( text ) - 1 ]
return trim_padding( text )
redirect = trim_padding( base64.b64encode( 'false' ) )
authUrl = '%s/api/v1/oauth?provider=%s&org=Default&user=%s&next=%s' % ( self.url_,
provider, user, redirect )
resp = requests.get( authUrl, verify=False )
if not resp.ok:
raise CvpError( resp.status_code, resp.content )
self.cookies[ 'access_token' ] = resp.cookies[ 'access_token' ]
def logout( self ):
'''Log out from web server
Raises:
CvpError -- If session cookies are invalid
'''
self.doRequest( requests.post,
'%s/cvpservice/login/logout.do' % self.url_ )
def imageBundleAppliedContainers( self, imageBundleName ):
'''Retrieves containers to which the image bundle is applied to.
Warning -- Method deosn't check existence of the image bundle
Arguments:
imageBundleName -- name of the image bundle ( type : String )
Returns:
containers[ 'data' ] -- List of containers ( type : List of Dict )
Raises:
CvpError -- If parameter data structures are incorrect
'''
name = quote( imageBundleName )
containers = self.doRequest( requests.get,
'%s/cvpservice/image/getImageBundleAppliedContainers.do?'
'imageName=%s&startIndex=%d&endIndex=%d&queryparam='
% ( self.url_, name, 0, 0 ) )
return containers[ 'data' ]
def changeContainerName( self, oldName, newName, containerKey ):
'''Changes the container name from old container name to
the new name
Arguments:
oldName -- original name of the container
containerKey -- unique Id associated with the container
newName -- desired new name of the container
Raises:
CvpError -- If the oldName is invalid
CvpError -- If containerKey is invalid
'''
data = { "data" :
[ { "info" : "Container " + newName + " renamed from " + oldName,
"infoPreview" : "Container " + newName + " renamed from " +
oldName,
"action" : "update",
"nodeType" : "container",
"nodeId" : containerKey,
"toId" : "",
"fromId" : "",
"nodeName" : newName,
"fromName" : "",
"toName" : "",
"toIdType" : "container",
"oldNodeName" : oldName
} ] }
self.doRequest( requests.post,
'%s/cvpservice/ztp/addTempAction.do?format=topology&queryParam=&nodeId=%s' %
( self.url_, containerKey ), data=json.dumps( data ) )
return self._saveTopology( [] )[ 'taskIds' ]
def searchContainer( self, containerName ):
'''Retrieves information about a container
Arguments:
containerName -- name of the container ( type : String )
Returns:
containers -- Containers with given name
( type : List of Dict )
Raises:
CvpError -- If parameter data structures are incorrect
'''
containers = self.doRequest( requests.get,
'%s/cvpservice/inventory/containers?name=%s' %
(self.url_, quote(containerName)) )
return containers
def getDevicesInContainer( self, containerId, containerName ):
'''Retrieves the set of devices under the container
Arguments:
containerId -- key of the container
containerName -- name of the container
Returns:
resp[ 'containerList' ] -- List consisting of MAC Address of devices
and container name and key ( type : Dict )
Raises:
CvpError -- If parameter data structures are incorrect
'''
resp = self.doRequest( requests.get,
'%s/cvpservice/provisioning/getAllNetElementList.do?nodeId=%s&nodeName=%s'
'&queryParam=&contextQueryParam=&ignoreAdd=true&startIndex=%d'
'&endIndex=%d' % ( self.url_, containerId, containerName, 0, 0 ) )
return resp[ 'containerList' ]
def searchTopology( self, objectName ):
'''Retrieves information about all objects whose name contains objectName
Arguments:
objectName -- name of the object ( type : String )
Returns:
topology -- Complete information about all the objects keyed with
categories ( type : Dict )
Raises:
CvpError -- If parameter data structures are incorrect
'''
name = quote( objectName )
topology = self.doRequest( requests.get,
'%s/cvpservice/provisioning/searchTopology.do?queryParam=%s'
'&startIndex=%d&endIndex=%d' % ( self.url_, name, 0, 0 ) )
return topology
def filterTopology( self, nodeId='root' , outputFormat='topology' ):
''' Filters the topology and retrieves information about all the elements
added under the node with id nodeId
Retrieves information about all objects whose name contains objectName
Arguments:
nodeId -- id of the parent node ( type : String )
Returns:
topology -- Complete information about all the objects added under this
node ( type : Dict )
Raises:
CvpError -- If parameter data structures are incorrect
'''
topology = self.doRequest( requests.get,
'%s/cvpservice/provisioning/filterTopology.do?nodeId=%s&format=%s'
'&startIndex=%d&endIndex=%d' % ( self.url_, nodeId, outputFormat, 0,
0 ) )
return topology[ 'topology' ]
def imageBundleAppliedDevices( self, imageBundleName):
'''Retrieves devices to which the image bundle is applied to.
Warning -- Method deosn't check existence of the image bundle
Arguments:
imagebundleName -- name of the image bundle ( type : String )
Returns:
devices[ 'data' ] -- List of devices ( type : List of Dict )
Raises:
CvpError -- If parameter data structures are incorrect
'''
name = quote( imageBundleName )
devices = self.doRequest( requests.get,
'%s/cvpservice/image/getImageBundleAppliedDevices.do?'
'imageName=%s&startIndex=%d&endIndex=%d&queryparam='
% ( self.url_, name, 0, 0 ) )
return devices[ 'data' ]
def addImage( self, imageName, strDirPath='' ):
'''Add image to Cvp instance
Warning -- image file with imageName as file should exist
Argument:
imageName -- name of the image ( type : String )
Raises:
CvpError -- If image already exists in Cvp instance
Returns:
imageInfo -- information of image added to the cvp instance
'''
assert isinstance( imageName, ( str, unicode ) )
filePath = ''
if strDirPath:
filePath = os.path.join( strDirPath, imageName )
elif self.tmpDir:
filePath = os.path.join( self.tmpDir, imageName )
elif os.path.isfile( imageName ):
filePath = imageName
else:
raise CvpError( errorCodes.INVALID_IMAGE_ADDITION )
with open( filePath, 'r' ) as f:
imageInfo = self.doRequest( requests.post,
'%s/cvpservice/image/addImage.do' % self.url_, files={ 'file' : f } )
return imageInfo
def downloadImage( self, imageName, imageId, filePath='' ):
'''Download the image file from Cvp Instance and stores at corresponding
file path or current directory
Arguments:
imageName -- name of image (type : string )
imageId -- unique Id assigned to the image ( type : string )
filePath -- storage path in the local system (optional)( type : string )
'''
fileName = os.path.join( filePath, imageName )
# Note that we're not calling doRequest() here since it will return the
# swi file as a json encoded string which caches the file in memory and
# bloats it. Instead we're streaming the binary file to disk which keeps
# things sane.
kwargs = {}
kwargs[ 'cookies' ] = self.cookies
kwargs[ 'verify' ] = False
resp = requests.get( '%s/cvpservice/services/image/getImagebyId/%s' %
( self.url_, imageId ),
stream=True, **kwargs )
if resp.status_code == 200:
with open( fileName, 'wb' ) as f:
for chunk in resp:
f.write( chunk )
else:
raise CvpError( errorCodes.FILE_DOWNLOAD_ERROR,
'Error %d downloading %s to %s' %
( resp.status_code, imageName, fileName ) )
def firstLoginDefaultPasswordReset( self, newPassword, emailId ):
'''Reset the password for the first login into the Cvp Web-UI
Warning -- Method doesn;t check the validity of emailID
Arguments:
newPassword -- new password for password reset ( type : String )
emailId -- emailId assigned to the user ( type : String )
Raises:
CvpError -- If parameter data structures are incorrect
'''
data = { "userId" : DEFAULT_USER,
"oldPassword" : DEFAULT_PASSWORD,
"currentPassword" : newPassword,
"email" : emailId
}
self.doRequest( requests.post, '%s/cvpservice/login/changePassword.do'
% self.url_, data=json.dumps( data ) )
def runCmdsOnDevice( self, ipAddress, deviceId, username, cmds ):
'''Run commands on the device using DI exposed rest end point.
Arguments:
ipAddress -- ip address of the device ( type : String )
device Id -- ID of the device ( type : String )
username -- user for authentication on device ( type : String )
cmds -- list of commands to be run( type: list of commands ( Command ) )
'''
data = {
"host": ipAddress,
"deviceId": deviceId,
"cmds": cmds,
"username" : username
}
resp = self.doRequest( requests.post, '%s/cvpservice/di/internal/runcmds'
% self.url_, data=json.dumps( data, default=lambda ob: ob.__dict__ ) )
return resp
def getInventory( self, populateParentContainerKeyMap=True, provisioned=True ):
'''Retrieve information about devices provisioned by the Cvp instance
Arguments:
provisioned- False would get all onboarded devices,True would get only the provisioned ones
Returns:
devices -- List of information of all devices
( type : List of Dict )
containers -- Information of parent container names of devices
( type : Dict )
'''
devices = self.doRequest( requests.get,
'%s/cvpservice/inventory/devices?provisioned=%s'
% (self.url_, provisioned) )
if not populateParentContainerKeyMap:
return ( devices, {} )
parentContainerKeyMap = {}
for device in devices:
containerKey = device["parentContainerKey"]
if containerKey == "":
continue
containerName = self.getContainerInfoByKey( containerKey )['name']
parentContainerKeyMap[device["systemMacAddress"]] = containerName
return ( devices, parentContainerKeyMap )
def configletAppliedContainers( self, configletName ):
'''Retrieves containers to which the configlet is applied to.
Warning -- Method deosn't check existence of the configlet
Arguments:
configletName -- name of the configlet ( type : String )
Returns:
containers[ 'data' ] -- List of container to which configlet is applied
( type : List of Dict )
Raises:
CvpError -- If parameter data structures are incorrect
'''
name = quote( configletName )
containers = self.doRequest( requests.get,
'%s/cvpservice/configlet/getAppliedContainers.do?configletName=%s'
'&startIndex=%d&endIndex=%d&queryparam='
'&configletId=1'
% ( self.url_, name, 0, 0 ) )
return containers[ 'data' ]
def configletAppliedDevices( self, configletName ):
'''Retrieves devices to which the configlet is applied to.
Warning -- Method deosn't check existence of the configlet
Arguments:
configletName -- name of the configlet ( type : String )
Returns:
devices[ 'data' ] -- List of devices to which configlet is applied
( type : List of Dict )
Raises:
CvpError -- If parameter data structures are incorrect
'''
name = quote( configletName )
devices = self.doRequest( requests.get,
'%s/cvpservice/configlet/getAppliedDevices.do?configletName=%s'
'&startIndex=%d&endIndex=%d&queryparam='
'&configletId=1'
% ( self.url_, name, 0, 0 ) )
return devices[ 'data' ]
def getImagesInfo( self ):
'''Get information about all the images
Returns:
images[ 'data' ] -- List of details of all the images
( type : List of Dict )
'''
images = self.doRequest( requests.get,
'%s/cvpservice/image/getImages.do?queryparam=&startIndex=%d&endIndex=%d'
% ( self.url_, 0, 0 ) )
return images[ 'data' ]
def addConfiglet( self, configletName, configletContent ):
'''Add configlet to Cvp inventory
Arguments:
configletName -- name of the configlet ( type : String )
configletContent -- content of the configlet ( type : String )
Raises:
CvpError -- If configlet with same name already exists
If parameter data structures are incorrect
'''
configlet = { 'config' : configletContent,
'name' : configletName
}
self.doRequest( requests.post,
'%s/cvpservice/configlet/addConfiglet.do' % self.url_,
data=json.dumps( configlet ) )
def addGeneratedConfiglet( self, configletName, config, containerId, deviceMac,
builderId ):
'''Adds the mapping between the generated configlets, containers and devices'''
data = { "data" : {
"configlets" : [ {
"config" : config,
"name" : configletName,
"type" : "Generated" } ]
} }
self.doRequest( requests.post,
'%s/cvpservice/configlet/addConfigletsAndAssociatedMappers.do'
% self.url_, data=json.dumps( data ) )
configletInfo = self.getConfigletByName( configletName )
configletId = configletInfo[ 'key' ]
data = { "data" : {
"generatedConfigletMappers" : [ {
"containerId" : containerId,
"configletId" : configletId,
"netElementId" : deviceMac,
"configletBuilderId" : builderId,
"action" : 'assign',
"previewValues" : [],
"previewValuesListSize": 0,
"objectType": None,
"key": ""
} ],
"configletMappers" : [ {
"objectId" : deviceMac,
"containerId" : None,
"configletId" : configletId,
"configletType": "Generated",
"type": "netelement"
} ] } }
self.doRequest( requests.post,
'%s/cvpservice/configlet/addConfigletsAndAssociatedMappers.do'
% self.url_, data=json.dumps( data ) )
def addReconciledConfiglet( self, configletName, config, deviceMac ):
'''Adds the mapping between the generated configlets, containers and devices'''
data = { "data" : {
"configlets" : [ {
"config" : config,
"name" : configletName,
"type" : "Static",
"reconciled" : True
} ] } }
self.doRequest( requests.post,
'%s/cvpservice/configlet/addConfigletsAndAssociatedMappers.do'
% self.url_, data=json.dumps( data ) )
configletInfo = self.getConfigletByName( configletName )
configletId = configletInfo[ 'key' ]
data = { "data" : {
"configletMappers" : [ {
"objectId" : deviceMac,
"containerId" : None,
"configletId" : configletId,
"configletType": "Static",
"type": "netelement"
} ] } }
self.doRequest( requests.post,
'%s/cvpservice/configlet/addConfigletsAndAssociatedMappers.do'
% self.url_, data=json.dumps( data ) )
def addConfigletBuilder( self, configBuilderName, formList, mainScript ):
'''Add configlet Builder to Cvp inventory
Arguments:
configletBuilder -- Information of the Configlet Builder to be
added ( type : ConfigletBuilder( class ) )
Raises:
CvpError -- If Configlet Builder information format is invalid
'''
data = { "name" : configBuilderName,
"data" : { "formList" : formList,
"main_script" : { 'data' : mainScript, 'key': None }
}
}
response = self.doRequest( requests.post,
'%s/cvpservice/configlet/addConfigletBuilder.do?isDraft=false'
% self.url_, data=json.dumps( data ) )
pythonError = response.get( 'pythonError' )
if pythonError:
raise CvpError( errorCodes.CONFIGLET_BUILDER_PYTHON_ERROR,
pythonError[ 'errorMessage' ],
response=response )
def deleteConfigletBuilder( self, configletBuilderKey ):
'''Remove a configlet from the Cvp instance
Arguments:
configletBuilder -- Information of the Configlet Builder to be
removed ( type : ConfigletBuilder( class ) )
Raises:
CvpError -- If Configlet Builder name or key is invalid
'''
self.doRequest( requests.post,
'%s/cvpservice/configlet/cancelConfigletBuilder.do?id=%s'
% ( self.url_, configletBuilderKey ) )
def getConfigletByName( self, configletName ):
'''Get information about configlet
Arguments:
configName -- name of the configlet ( type : String )
Returns:
configlet -- information about the configlet ( type : Dict )
Raises:
CvpError -- If configlet name is invalid
If parameter data structures are incorrect
'''
name = quote( configletName )
configlet = self.doRequest( requests.get,
'%s/cvpservice/configlet/getConfigletByName.do?name=%s'
% ( self.url_, name ) )
return configlet
def getConfigletMapper( self ):
'''Retrieves the mapping between the configlets, devices and containers'''
mapperInfo = self.doRequest( requests.get,
'%s/cvpservice/configlet/getConfigletsAndAssociatedMappers.do' %
self.url_ )
return mapperInfo[ 'data' ]
def updateConfiglet( self, configletName, configletContent, configletKey,
waitForTaskIds=False ):
'''Update configlet information
Arguments:
configletName -- name of configlet( type : String )
configletContent -- content of the configlet ( type : String )
configletKey -- key assigned to the configlet ( type : String )
waitForTaskIds -- should the API return task ids ( type : Boolean )
Returns:
if waitForTaskIds is True, this function waits for any tasks to be created
as a result of updating the configlet, and returns the task IDs.
Otherwise, None.
List of Task IDs -- list of the generated tasks ( type : List of Strings )
Raises:
CvpError -- If configlet key is invalid
If parameter data structures are incorrect
'''
configlet = { 'config' : configletContent,
'name' : configletName,
'key' : configletKey,
'waitForTaskIds' : waitForTaskIds
}
tasks = self.doRequest( requests.post,
'%s/cvpservice/configlet/updateConfiglet.do' % ( self.url_ ),
data=json.dumps( configlet ) )
return tasks.get( 'taskIds' )
def updateReconciledConfiglet( self, configletName, configletContent,
configletKey, mac ):
'''Update a reconcile configlet
Arguments:
configletName -- name of configlet (type: string)
configletContent -- content of the configlet (type: string)
configletKey -- key assigned to the configlet (type: string)
mac -- Mac address of the device this configlet is attached to(type: string)
Raises:
CvpError -- on any error
'''
data = { 'config' : configletContent,
'name' : configletName,
'key' : configletKey,
'reconciled' : True
}
return self.doRequest( requests.post,
'%s/cvpservice/provisioning/updateReconcileConfiglet.do?netElementId=%s'
% ( self.url_, mac ),
data=json.dumps( data ) )[ 'data' ]
def deleteConfiglet( self, configletName, configletKey ):
'''Removes the configlet from Cvp instance
Arguments:
configletName -- name of the configlet ( type : String )
configletKey -- Key assigned to the configlet ( type : String )
Raises:
CvpError -- If the configlet key is invalid
If parameter data structures are incorrect
'''
configlet = [ { 'key' : configletKey,
'name' : configletName
} ]
self.doRequest( requests.post,
'%s/cvpservice/configlet/deleteConfiglet.do' % self.url_,
data=json.dumps( configlet ) )
def saveImageBundle( self, imageBundleName, imageBundleCertified,
imageInfoList ):
'''Add image bundle to Cvp instance.
Arguments:
imageBundleName -- Name of image Bundle ( type : String )
imageBundleCertified -- image bundle certified ( type : bool )
imageInfoList -- details of images present in image bundle
( type : List of Dict )
Raises:
CvpError -- If image bundle name is invalid
If image details are invalid
If parameter data structures are incorrect
'''
data = { 'name' : imageBundleName,
'isCertifiedImage' : str( imageBundleCertified ).lower(),
'images' : imageInfoList
}
self.doRequest( requests.post,
'%s/cvpservice/image/saveImageBundle.do' % self.url_,
data=json.dumps( data ) )
def getImageBundleByName( self, imageBundleName ):
'''Returns image bundle informations
Arguments:
imageBundleName -- Name of the Image bundle ( type : String )
Returns:
imageBundle -- Complete information about the imagebundle ( type : Dict )
Raises:
CvpError -- If parameter data structures are incorrect
'''
name = quote( imageBundleName )
imageBundle = self.doRequest( requests.get,
'%s/cvpservice/image/v2/getImageBundleByName.do?name=%s'
% ( self.url_, name ) )
return imageBundle
def updateImageBundle( self, imageBundleName, imageBundleCertified,
imageInfoList, imageBundleKey ):
'''Update image bundle information.
Arguments:
imageBundleName -- Name of image Bundle ( type : String )
imageBundleCertified -- image bundle certified ( type : bool )
imageInfoList -- details of images present in image bundle
( type : List of dict )
imageBundleKey -- key assigned to image bundle ( type : String )
Raises:
CvpError -- If image bundle name or key are invalid
If information of image to be mapped to image bundle is invalid
If parameter data structures are incorrect
'''
data = { 'name' : imageBundleName,
'isCertifiedImage' : str( imageBundleCertified ).lower(),
'images' : imageInfoList,
'id' : imageBundleKey
}
self.doRequest( requests.post,
'%s/cvpservice/image/updateImageBundle.do' % ( self.url_ ),
data=json.dumps( data ) )
def waitForDevicesToBeInInventory( self, ipAddressOrNameList, timeout=360 ):
endTime = time.time() + timeout
ipAddressOrNameList = set( ipAddressOrNameList )
while True:
devicesInfo, _ = self.getInventory(populateParentContainerKeyMap=False)
if len(devicesInfo) < len(ipAddressOrNameList):
time.sleep(0.5)
continue
found = {}
for device in devicesInfo:
hostname = device['hostname']
if len(device['domainName']) > 0:
suffix = '.' + device['domainName']
if hostname.endswith( suffix ):
hostname = hostname[:-len( suffix )]
if device['ipAddress'] in ipAddressOrNameList:
found[ device['ipAddress'] ] = device['systemMacAddress']
elif hostname in ipAddressOrNameList:
found[ hostname ] = device['systemMacAddress']
elif device['fqdn'] in ipAddressOrNameList:
found[ device['fqdn'] ] = device['systemMacAddress']
if set(found.keys()) == ipAddressOrNameList:
return found
if time.time() > endTime:
break
time.sleep(0.5)
raise CvpError( errorCodes.TIMEOUT )
def addToInventory( self, deviceIpAddress, parentContainerId ):
'''Add device to the Cvp inventory. Warning -- Method doesn't check the
existance of the parent container
Arguments:
deviceIpAddress -- ip address of the device to be added ( type : String )
parentContainerId -- Id of parent container ( type : String )
Returns:
taskId -- Id of the generated task, if any, or None if no task is
generated
Raises:
CvpError -- If parameter data structures are incorrect
'''
# Onboard the device
resp = self.onboardDevices( [deviceIpAddress] )
if 'failed' in resp.get('data', {}):
try:
onboardResponse = json.loads(resp['data']['failed'][0][deviceIpAddress])
raise CvpError(onboardResponse['errorCode'], onboardResponse['errorMessage'])