forked from darkiesan/CV-EOS-Conversion
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cvp.py
3218 lines (2954 loc) · 137 KB
/
cvp.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.
Cvp.py is a library which can be used to perform various
actions over the cvp instance. There are numerous methods each
corresponding to each action. Methods are listed below in the Cvp class.
'''
from __future__ import print_function
import os
import time
import cvpServices
import errorCodes
import socket
import re
import base64
import io
import zipfile
# Compliance codes for devices and containers
DEVICE_IN_COMPLIANCE = 0
DEVICE_CONFIG_OUT_OF_SYNC = 1
DEVICE_IMAGE_OUT_OF_SYNC = 2
DEVICE_IMG_CONFIG_OUT_OF_SYNC = 3
DEVICE_IMG_CONFIG_IN_SYNC = 4
DEVICE_NOT_REACHABLE = 5
DEVICE_IMG_UPGRADE_REQD = 6
DEVICE_EXTN_OUT_OF_SYNC = 7
DEVICE_CONFIG_IMG_EXTN_OUT_OF_SYNC = 8
DEVICE_CONFIG_EXTN_OUT_OF_SYNC = 9
DEVICE_IMG_EXTN_OUT_OF_SYNC = 10
DEVICE_UNAUTHORIZED_USER = 11
complianceCodes = {
DEVICE_IN_COMPLIANCE : 'In compliance',
DEVICE_CONFIG_OUT_OF_SYNC : 'Config out of sync',
DEVICE_IMAGE_OUT_OF_SYNC : 'Image out of sync',
DEVICE_IMG_CONFIG_OUT_OF_SYNC : 'Image and Config out of sync',
DEVICE_IMG_CONFIG_IN_SYNC : 'Unused', # was: 'Image and Config in sync'
DEVICE_NOT_REACHABLE : 'Device not reachable',
DEVICE_IMG_UPGRADE_REQD : 'Image upgrade required',
DEVICE_EXTN_OUT_OF_SYNC : 'Extensions out of sync',
DEVICE_CONFIG_IMG_EXTN_OUT_OF_SYNC : 'Config, Image and Extensions out of sync',
DEVICE_CONFIG_EXTN_OUT_OF_SYNC : 'Config and Extensions out of sync',
DEVICE_IMG_EXTN_OUT_OF_SYNC : 'Image and Extensions out of sync',
DEVICE_UNAUTHORIZED_USER : 'Unauthorized User',
}
# AAA settings notation
AAA_SETTINGS = [ 'Local', 'RADIUS', 'TACACS' ]
class EncryptionAlgorithm( object ):
rsa = 'RSA'
class DigestAlgorithm( object ):
sha256rsa = 'SHA256withRSA'
def encoder( obj ):
'''Returns JSON-serializable version of the obj'''
if hasattr( obj, 'jsonable' ):
return obj.jsonable()
else:
raise TypeError
class Jsonable( object ):
'''This class represents a JSON-serializable object. The default serialization
is to just return the class' __dict__.'''
def __init__( self ):
pass
def jsonable( self ):
''' Returns modules namespace as dictionary'''
return self.__dict__
class Image( Jsonable ):
'''Image class, stores all required information about
an image.
state variables:
name -- name fo the image
rebootRequired -- Reboot required after applying this image( True/False )
'''
def __init__( self, name, rebootRequired=False ):
super( Image, self ).__init__( )
self.name = name
self.rebootRequired = rebootRequired
def __repr__( self ):
return 'Image "%s"' % self.name
class Theme( Jsonable ):
'''Theme class, stores all required information about a theme.
state variables:
name -- file name
themeType -- either backgroundImage or logo
isActive -- is active theme
'''
def __init__( self, name, themeType, isActive ):
super( Theme, self ).__init__( )
self.name = name
self.themeType = themeType
self.isActive = isActive
def __repr__( self ):
return 'Theme "%s"' % self.name
class Container( Jsonable ):
'''Container class, stores all required information about
a container
State variables:
name -- name of the container
configlets -- list of configlet name assigned to container
imageBundle -- name of the image bundle assigned to container
parentName -- Name of the parent container
'''
def __init__( self, name, parentName, configlets='', imageBundle=''):
super( Container, self ).__init__( )
self.name = name
self.configlets = configlets
self.imageBundle = imageBundle
self.parentName = parentName
def __repr__( self ):
return 'Container "%s"' % self.name
class Task( Jsonable ):
''' Task class, Stores information about a Task
State variables:
taskId -- work order Id assigned to the task
description -- information explaining what task is about
'''
COMPLETED = 'Completed'
PENDING = 'Pending'
FAILED = 'Failed'
CANCELED = 'Cancelled'
CONFIG_PUSH_IN_PROGRESS = 'Configlet Push In Progress'
IMAGE_PUSH_IN_PROGRESS = 'Image Push In Progress'
DEVICE_REBOOT_IN_PROGRESS = 'Device Reboot In Progress'
def __init__( self, taskId, status, description='' ):
super( Task, self ).__init__( )
self.taskId = int( taskId )
self.status = status
self.description = description
def __repr__( self ):
return 'Task "%s"' % self.taskId
class CCTask( Task ):
''' A Class for Tasks associated with Change Control.
State variables:
taskOrder -- Order of the task executed in a Change control
'''
def __init__( self, taskId, status, description, taskOrder = 1,
cloneId = None ):
super( CCTask, self ).__init__( taskId, status, description )
self.taskOrder = taskOrder
self.parentCCId = cloneId
class ChangeControl( Jsonable ):
''' Change Control class, that stores information about change controls
State variables:
Id(type: int) -- Id of the change control
Name -- Name assigned to the change control
schedule -- timeDate in local time zone to schedule a change control
snapshotTemplateKey -- snapshot template key for the change control
taskList -- List of CCTask objects to be included for the change control
status -- Status of change control
'''
COMPLETED = 'Completed'
PENDING = 'Pending'
FAILED = 'Failed'
CANCELLED = 'Cancelled'
ABORTED = 'Aborted'
NEW = 'New'
# Making ccTaskList default None as when we call getChangeControls API,
# returned data from change control does not have ccTaskList field.
def __init__( self, ccName, ccTaskList, scheduleTime=None,
snapshotTemplateKey=None, status=NEW, ccId=None ):
super( ChangeControl, self ).__init__()
self.Id = ccId
self.Name = ccName
self.schedule = scheduleTime
self.snapshotTemplateKey = snapshotTemplateKey
self.taskList = ccTaskList
self.status = status
class Rollback( Jsonable ):
''' Rollback class, stores information about the rollback variables
State variables:
rollbackType -- Type of rollback
rollbackTime -- Unix time to which rollback is to happen
device -- an Device object that indicates the device being rolledback
configRollbackInfo -- Information regards to the snapshot or task from
which the config details are being used to
rollback the device config. Its a Dict with
'taskId' and 'snapshot' as keys
imageRollbackInfo -- Information regards to the snapshot or task from
which the image details are being used to
rollback the device image. Image should be
available in the Cvp for the rollabck to occur.
Its a Dict with 'taskId' and 'snapshot' as keys
'''
def __init__( self, rollbackType, rollbackTime, device ):
super( Rollback, self ).__init__()
assert isinstance( device, Device )
self.rollbackType = rollbackType
self.rollbackTime = rollbackTime
self.device = device
self.configRollbackInfo = None
self.imageRollbackInfo = None
class NetworkRollback( Jsonable ):
''' NetworkRollback class to host network rollback information
State variables:
container -- An instance of Container rolled back
rollbackType -- The type of the rollback
rollbackTime -- Unix time to which rollback is to happen
startIndex - pagination start index
endIndex - pagination end index
cc -- An instance of Change Control that handles the network rollback
tasks
'''
CONFIG_ROLLBACK = 'Config Rollback'
IMAGE_ROLLBACK = 'Image Rollback'
CONFIG_IMAGE_ROLLBACK = 'Config and Image Rollback'
def __init__( self, container, rollbackTime, rollbackType,
startIndex=0, endIndex=15 ):
super( NetworkRollback, self ).__init__()
self.container = container
self.rollbackTime = rollbackTime
self.rollbackType = rollbackType
self.startIndex = startIndex
self.endIndex = endIndex
self.cc = None
class Device( Jsonable ):
''' Device class helps store all the information about a particular device
state variables:
ipAddress -- ip address of the device
fqdn -- fully qualified domain name for the device
macAddress -- mac address of the device
containerName -- name of the parent container
imageBundle -- name of the imageBundle assigned to device
configlets -- list of names of configlets assigned to the device
status -- Device's registration status
model -- Device's model number
sn -- Device's serial number
complianceCode -- Device's compliance status
'''
UNKNOWN = 'Unknown'
REG_IN_PROGRESS = 'Registration_In_Progress'
REGISTERED = 'Registered'
AUTO_UPGRADE_FAILED = 'Auto image upgrade failed'
DCA_INSTALLATION_IN_PROGRESS = 'Certificate installation in-progress'
DCA_INSTALLATION_FAILED = 'Certificate installation failed'
def __init__( self, ipAddress, fqdn, macAddress, containerName, imageBundle=None,
configlets=None, status=UNKNOWN, model=None, sn=None,
complianceCode=None ):
super( Device, self ).__init__( )
self.ipAddress = ipAddress
self.fqdn = fqdn
self.macAddress = macAddress
self.containerName = containerName
self.imageBundle = imageBundle
self.configlets = configlets
self.status = status
self.model = model
self.sn = sn
self.cc = complianceCode
def __repr__( self ):
return 'Device "%s"' % self.fqdn or self.ipAddress or self.macAddress
class Configlet( Jsonable ):
'''Configlet class stores all the information necessary about the
configlet
state variables:
name -- name of the configlet
config -- configuration information inside configlet
type -- to store the type of the configlet
user -- the user that created this configlet. Pre-loaded configlets have
'cvp system' as the user.
sslConfig -- A Boolean indicating if this is a system pre-loaded special ssl configlet for
secure device communication.
'''
def __init__( self, name, config, configletType='Static', user=None,
sslConfig=False ):
super( Configlet, self ).__init__( )
self.name = name
self.config = config
self.configletType = configletType
self.user = user
self.sslConfig = sslConfig
def __repr__( self ):
return 'Configlet "%s"' % self.name
class ConfigletBuilder( Configlet ):
''' ConfigletBuilder class stores all the information about the Configlet
builder
state variables:
name -- name of the Configlet Builder
formList -- list of forms part of configlet builder
mainScript -- the configlet builder mainscript
'''
def __init__( self, name, formList, mainScript, **kwargs ):
super( ConfigletBuilder, self ).__init__( name, '', **kwargs )
self.formList = formList
self.mainScript = mainScript
self.configletType = 'Builder'
class GeneratedConfiglet( Configlet ):
'''GeneratedConfiglet class stores information about the generated configlets.
Mapping between the generated configlet, configlet builder, container and device
State variables:
builderName -- name of the configlet builder that generated this configlet
ContainerName -- Name of the container to which the builder was assigned
deviceMac -- Mac address of the device to which this configlet is assigned
'''
def __init__( self, name, config, builderName, containerName, deviceMac, **kwargs ):
super( GeneratedConfiglet, self ).__init__( name, config, **kwargs )
self.builderName = builderName
self.containerName = containerName
self.deviceMac = deviceMac
self.configletType = 'Generated'
class ReconciledConfiglet( Configlet ):
'''ReconciledConfiglet class stores information about the reconciled configlets.
State variables:
deviceMac -- Mac address of the devices
'''
def __init__( self, name, config, deviceMac, **kwargs ):
super( ReconciledConfiglet, self ).__init__( name, config, **kwargs )
self.deviceMac = deviceMac
self.configletType = 'Reconciled'
class User( Jsonable ):
''' User class stores all the information about an users
State variables:
userId -- unique user id of the user
firstName -- first name of user
LastName -- last name of the user
emailID -- email ID of the user
contactNumber -- contact number for the user
'''
def __init__( self, userId, email, roleList, userStatus='DISABLED',
firstName='', lastName='', contactNumber='', userType='Local' ):
super( User, self ).__init__( )
self.userId = userId
self.email = email
self.roleList = roleList
self.userStatus = userStatus
self.firstName = firstName
self.lastName = lastName
self.contactNumber = contactNumber
self.userType = userType
def __repr__( self ):
return 'User "%s"' % self.userId
class Role( Jsonable ):
''' Stores all essential information about a specific role
State variables:
name -- name of the role
description -- Description about the Role
moduleList -- list of permissions
key -- key of the role
'''
def __init__( self, name, description, moduleList, key=None ):
super( Role, self ).__init__( )
self.key = key
self.name = name
self.description = description
self.moduleList = moduleList
def __repr__( self ):
return 'Role "%s"' % self.name
class ImageBundle( Jsonable ):
'''ImageBundle class objects stores all necessary information about the
bundle
state variables:
name -- name of the image bundle
imageNames -- keys corresponding to images present in this image bundle
certified -- indicates whether image bundle is certified or not
user -- User that created this bundle
'''
def __init__( self, name, imageNames, certified=False, user=None ):
super( ImageBundle, self ).__init__( )
self.name = name
self.imageNames = imageNames
self.certified = certified
self.user = user
def __repr__( self ):
return 'ImageBundle "%s"' % self.name
class AaaServer( Jsonable ):
'''
Aaa Server Class object holds all information about
AAA server
state variables:
serverType -- AAA server type Local, TACACS, RADIUS
authType -- authorization type Local, TACACS, RADIUS
port -- Port
ipAddress -- Ip address of remote AAA server
authMode -- authorization mode ASCII, PAD, CHAP
status -- Status of AAA server Enabled, Disabled
'''
ENABLED = "Enabled"
DISABLED = "Disabled"
def __init__( self, serverType, authType, port,
ipAddress, authMode, accountPort,
status=ENABLED, key=None ):
assert ( status == self.ENABLED or status == self.DISABLED ), 'status can' \
' be %s or %s.' %( self.ENABLED, self.DISABLED )
super( AaaServer, self ).__init__( )
self.serverType = serverType
self.authType = authType
self.port = port
self.ipAddress = ipAddress
self.authMode = authMode
self.status = status
self.createdDateInLongFormat = int( round( time.time() * 1000 ) )
self.accountPort = accountPort
self.key = key
def __repr__( self ):
return 'AAAServer "%s"' % self.ipAddress
class AaaUser( Jsonable ):
'''
User object representing user need to be tested
agaist AAA server.
'''
def __init__( self, userId, password ):
super( AaaUser, self ).__init__( )
self.userId = userId
self.password = password
def __repr__( self ):
return 'AAAUser "%s"' % self.userId
class AaaSettings( Jsonable ):
'''
AAA settings object which stores inforamtion about Authentication and
Authorization server type.
'''
def __init__( self, authenticationServerType, authorizationServerType ):
super( AaaSettings, self ).__init__( )
self.authenticationServerType = authenticationServerType
self.authorizationServerType = authorizationServerType
class Event( Jsonable ):
'''
Event class that represents events such as compliance check, reconcile.
'''
INITIALIZED = 'INITIALIZED'
IN_PROGRESS = 'IN_PROGRESS'
COMPLETED = 'COMPLETED'
CANCELED = 'CANCELLED'
def __init__( self, eventId, parentEventId, objectId, eventType, status,
complianceCode, message, errors, warnings, addlData ):
super( Event, self ).__init__()
self.eventId = eventId
self.parentEventId = parentEventId
self.objectId = objectId
self.eventType = eventType
self.status = status
self.complianceCode = complianceCode
self.message = message
self.errors = errors
self.warnings = warnings
# addlData contains additional data about this event, which is the device
# structure as of now. If "unAuthorized" field is set, it means the
# complianceCode is not current, but the last known state.
self.addlData = addlData
def __repr__( self ):
return 'Event "%s"' % self.eventId
class Backup( Jsonable ):
'''
Backup class that represents CVP backups.
'''
def __init__( self, key, name, createdTimestamp, location, size ):
super( Backup, self ).__init__()
self.key = key
self.name = name
self.createdTimestamp = createdTimestamp
self.location = location
self.size = size
def __repr__( self ):
return 'Backup "%s"' % self.key
class CertificateInfo( Jsonable ):
'''
This is the base class for certificates.
'''
def __init__( self, commonName, subjectAlternateNameIPList,
subjectAlternateNameDNSList, organization, organizationUnit, location,
state, country, encryptionAlgorithm, digestAlgorithm, keyLength,
description ):
# No other instance variable should be added as this object will be converted
# to dictionary/json and used in Cvp.generateCertificate().
super( CertificateInfo, self ).__init__()
self.commonName = commonName
self.subjectAlternateNameIPList = subjectAlternateNameIPList
self.subjectAlternateNameDNSList = subjectAlternateNameDNSList
self.country = country
self.state = state
self.location = location
self.organization = organization
self.organizationUnit = organizationUnit
self.encryptAlgorithm = encryptionAlgorithm
self.digestAlgorithm = digestAlgorithm
self.keyLength = keyLength
self.description = description
def getSubject( self ):
return "CN=%s, O=%s, OU=%s, L=%s, ST=%s, C=%s" % ( self.commonName,
self.organization, self.organizationUnit, self.location, self.state,
self.country )
class Certificate( CertificateInfo ):
'''
This class represents a X.509 certificate.
'''
CVP = 'cvpCert'
DCA = 'dcaCert'
def __init__( self, certType, commonName, subjectAlternateNameIPList,
subjectAlternateNameDNSList, organization, organizationUnit, location,
state, country, encryptionAlgorithm, digestAlgorithm, keyLength,
validity, description, skipTypeCheck=False ):
super( Certificate, self ).__init__( commonName, subjectAlternateNameIPList,
subjectAlternateNameDNSList, organization, organizationUnit, location,
state, country, encryptionAlgorithm, digestAlgorithm, keyLength,
description )
# No other instance variable should be added as this object will be converted
# to dictionary/json and used in Cvp.generateCertificate().
if not skipTypeCheck:
Certificate.checkCertificateType( certType )
self.certType = certType
self.validity = validity
@classmethod
def checkCertificateType( cls, certType ):
'''
Checks the certificate type and raises an assertion if it is invalid.
'''
assert certType in [ cls.DCA, cls.CVP ], (
'Invalid certificate type: %s' % certType )
def __repr__( self ):
return 'Certificate("%s", %s)' % ( self.commonName, self.certType )
class CSR( CertificateInfo ):
'''
This class represents a X.509 certificate signing request.
'''
def __init__( self, commonName, subjectAlternateNameIPList,
subjectAlternateNameDNSList, organization, organizationUnit, location,
state, country, encryptionAlgorithm, digestAlgorithm, keyLength,
emailId, description ):
super( CSR, self ).__init__( commonName, subjectAlternateNameIPList,
subjectAlternateNameDNSList, organization, organizationUnit, location,
state, country, encryptionAlgorithm, digestAlgorithm, keyLength,
description )
# No other instance variable should be added as this object will be converted
# to dictionary/json and used in Cvp.generateCSR().
self.emailId = emailId
def getSubject( self ):
return "CN=%s, O=%s, OU=%s, L=%s, ST=%s, C=%s/emailAddress=%s" % ( self.commonName,
self.organization, self.organizationUnit, self.location, self.state,
self.country, self.emailId )
class Cvp( Jsonable ):
'''Class Cvp represents an instance of CVP. It provides high level python
APIs to retrieve and modify CVP state.'''
def __init__( self, host, ssl=True, port=443, tmpDir='' ):
super( Cvp, self ).__init__( )
self.cvpService = cvpServices.CvpService( host, ssl, port, tmpDir )
def __repr__( self ):
return 'Cvp "%s"' % self.url()
def hostIs( self, host ):
self.cvpService.hostIs( host )
def url( self ):
return self.cvpService.url( )
def sessionIs( self, sessionId ):
'''Choose a particular user session. This is meant to be used from a
configbuilder to avoid authenticating with a username/password and to
instead use session id.
Arguments:
sessionId - id of an already open user session.
'''
self.cvpService.sessionIs( sessionId )
def authenticate( self, username, password ):
'''Authenticate the user login credentials
Arguments:
username -- username for login ( type : string )
password -- login pasword (type : String )
Raises:
CvpError -- If invalid login credentials
'''
self.cvpService.authenticate( username, password )
def logout( self ):
'''Logging session out
Raises:
CvpError -- If invalid session
'''
self.cvpService.logout()
def _getContainerConfigletMap( self, configletNameList ):
'''Finds which configlets are mapped to which containers'''
configletMap = {}
for configletName in configletNameList:
containersInfo = self.cvpService.configletAppliedContainers( configletName )
for containerInfo in containersInfo:
configletNameList = []
key = containerInfo[ 'containerName' ]
if key in configletMap:
configletNameList = configletMap[ containerInfo[ 'containerName' ] ]
configletNameList.append( configletName )
configletMap[ containerInfo[ 'containerName' ] ] = configletNameList
else :
configletNameList.append( configletName )
configletMap[ containerInfo[ 'containerName' ] ] = configletNameList
return configletMap
def _getContainerImageBundleMap( self, imageBundleNameList ):
'''Finds which image bundle is mapped to which containers.'''
imageBundleMap = {}
for imageBundleName in imageBundleNameList:
containersInfo = self.cvpService.imageBundleAppliedContainers(
imageBundleName )
for containerInfo in containersInfo:
imageBundleMap[ containerInfo[ 'containerName' ] ] = imageBundleName
return imageBundleMap
def _getDeviceImageBundleMap( self, imageBundleNameList ):
'''Finds which image bundle is mapped to which devices.'''
imageBundleMap = {}
for imageBundleName in imageBundleNameList:
devicesInfo = self.cvpService.imageBundleAppliedDevices( imageBundleName )
for deviceInfo in devicesInfo:
imageBundleMap[ deviceInfo [ 'ipAddress' ] ] = imageBundleName
return imageBundleMap
def _getImageBundleNameList( self ):
''' finds the list of image bundles present in the cvp instance'''
imageBundleNameList = []
imageBundlesInfo = self.cvpService.getImageBundles()
for imageBundleInfo in imageBundlesInfo:
imageBundleNameList.append( imageBundleInfo[ 'name' ] )
return imageBundleNameList
def _getConfigletNameList( self ):
'''finds the list of configlets present in the cvp instance'''
configletNameList = []
configletsInfo = self.cvpService.getConfigletsInfo()
for configletInfo in configletsInfo:
configletNameList.append( configletInfo[ 'name' ] )
return configletNameList
def getDevices( self, provisioned=True ):
'''Collect information of all the devices. Information of device consist
of the device specifications like ip address, mac address( key ), configlets
and image bundle applied to device.
Arguments:
provisioned- False would get all onboarded devices,True would get only the provisioned ones
Returns:
deviceList -- List of device ( type : List of Device ( class ) )
'''
imageBundleNameList = self._getImageBundleNameList()
imageBundleMap = self._getDeviceImageBundleMap( imageBundleNameList )
devicesInfo, containersInfo = self.cvpService.getInventory( provisioned=provisioned)
deviceList = []
for deviceInfo in devicesInfo:
deviceMacAddress = deviceInfo[ 'systemMacAddress' ]
if deviceMacAddress not in containersInfo:
if provisioned:
raise cvpServices.CvpError( errorCodes.INVALID_CONTAINER_NAME )
else:
parentContainerName = ""
configletNames = None
else:
parentContainerName = containersInfo[ deviceInfo[ 'systemMacAddress' ] ]
configletsInfo = self.cvpService.getDeviceConfiglets( deviceMacAddress )
configletNames = [ configlet[ 'name' ] for configlet in configletsInfo ]
appliedImageBundle = []
if deviceInfo[ 'ipAddress' ] in imageBundleMap:
appliedImageBundle = imageBundleMap[ deviceInfo[ 'ipAddress' ] ]
cc = DEVICE_IN_COMPLIANCE if not deviceInfo[ 'complianceCode' ] else \
int( deviceInfo[ 'complianceCode'] )
deviceList.append( Device( ipAddress=deviceInfo[ 'ipAddress' ],
fqdn= deviceInfo[ 'fqdn' ],
macAddress=deviceMacAddress,
containerName=parentContainerName,
imageBundle=appliedImageBundle,
configlets=configletNames,
status=deviceInfo[ 'status' ],
model=deviceInfo[ 'modelName' ],
sn=deviceInfo[ 'serialNumber' ],
complianceCode=cc ) )
return deviceList
def _getContainerInfo( self, containerName ):
'''Returns container information for given container name'''
containersInfo = self.cvpService.searchTopology(
containerName )[ 'containerList' ]
if not containersInfo:
raise cvpServices.CvpError( errorCodes.INVALID_CONTAINER_NAME )
for containerInfo in containersInfo:
# Container names are not case sensitive
if containerInfo[ 'name' ].lower() == containerName.lower():
return containerInfo
return None
def getDevice( self, deviceMacAddress, provisioned=True ):
'''Retrieve information about device like ip address, mac address( key ),
configlets and image bundle applied to device.
Arguments:
provisioned- False would get all onboarded devices,True would get only the provisioned ones
Returns:
device -- Information about the device ( type : Device ( class ) )
'''
imageBundleNameList = self._getImageBundleNameList()
imageBundleMap = self._getDeviceImageBundleMap( imageBundleNameList )
devicesInfo, containersInfo = self.cvpService.getInventory( provisioned=provisioned )
for deviceInfo in devicesInfo:
if deviceInfo[ "systemMacAddress" ] != deviceMacAddress:
continue
if deviceMacAddress not in containersInfo:
raise cvpServices.CvpError( errorCodes.INVALID_CONTAINER_NAME )
parentContainerName = containersInfo[ deviceMacAddress ]
configletsInfo = self.cvpService.getDeviceConfiglets(
deviceInfo[ "systemMacAddress"] )
configletNames = [ configlet[ 'name' ] for configlet in configletsInfo ]
appliedImageBundle = []
if deviceInfo[ 'ipAddress' ] in imageBundleMap:
appliedImageBundle = imageBundleMap[ deviceInfo[ 'ipAddress' ] ]
cc = DEVICE_IN_COMPLIANCE if not deviceInfo[ 'complianceCode' ] else \
int( deviceInfo[ 'complianceCode'] )
device = Device( ipAddress=deviceInfo[ 'ipAddress' ],
fqdn=deviceInfo[ 'fqdn' ],
macAddress=deviceMacAddress,
containerName=parentContainerName,
imageBundle=appliedImageBundle,
configlets=configletNames,
status=deviceInfo[ 'status' ],
model=deviceInfo[ 'modelName' ],
sn=deviceInfo[ 'serialNumber' ],
complianceCode=cc )
return device
return None
def getConfiglets( self, configletNames='' ):
'''Retrieve the full set of Configlets
Returns:
configletList -- information of all configlets
( type : List of Configlet ( class ) )
'''
configletList = []
configlets = []
configletsInfo = self.cvpService.getConfigletsInfo()
for configletInfo in configletsInfo:
# getConfiglet returns unused configlets as None
configlet = self.getConfiglet( configletInfo[ 'name' ] )
if configlet:
configletList.append( configlet )
if configletNames:
configlets = [ configlet for configlet in configletList if
str( configlet.name ).lower() in configletNames ]
else:
configlets = configletList
return configlets
def getContainers( self ):
'''Retrieve the hierarchy of the containers and store information on all
of these containers. Information of container consist of specifications
like container name, configlets and image bundle applied to container.
Returns:
containers -- list of container informations
( type : List of Container ( class ) )
'''
imageBundleNameList = self._getImageBundleNameList()
imageBundleMap = self._getContainerImageBundleMap( imageBundleNameList )
containersInfo = self.cvpService.filterTopology()
rawContainerInfoList = []
rawContainerInfoList.append( containersInfo )
containers = []
containers = self._recursiveParse( containers, rawContainerInfoList,
imageBundleMap, '' )
return containers
def _recursiveParse( self, containers, childContainerInfoList,
imageBundleMap, parentContainerName):
''' internal function for recursive depth first search to obtain container
information from the container hierarchy. It handles different cases
like the configlet applied or not, image bundle applied or not to containers'''
for containerInfo in childContainerInfoList:
if containerInfo[ 'childContainerList' ]:
containers = self._recursiveParse( containers,
containerInfo[ 'childContainerList' ],
imageBundleMap, containerInfo[ 'name' ] )
containerName = containerInfo[ 'name' ]
containerKey = containerInfo[ 'key' ]
configletsInfo = self.cvpService.getContainerConfiglets( containerKey )
configletNames = [ configlet[ 'name' ] for configlet in configletsInfo ]
appliedImageBundle = None
if containerName in imageBundleMap:
appliedImageBundle = imageBundleMap[ containerName ]
containers.append( Container( containerName, parentContainerName,
configletNames, appliedImageBundle ) )
return containers
def getContainer( self, containerName ):
'''Retrieve container Information like container name, configlets and
image bundle applied to the container
Arguments
ContainerName -- name of the container ( type : String )
Raises:
CvpError -- If container name is invalid
Returns:
containerInfo -- Information about the container
( type : Container( class ) )
'''
containerInfo = self._getContainerInfo( containerName )
imageBundleNameList = self._getImageBundleNameList()
imageBundleMap = self._getContainerImageBundleMap( imageBundleNameList )
parentName = ''
containerName = containerInfo[ 'name' ]
containerKey = containerInfo[ 'key' ]
if containerInfo[ 'key' ] != 'root':
parentName = self.cvpService.getContainerInfoByKey(
containerKey )[ 'parentName' ]
configletsInfo = self.cvpService.getContainerConfiglets( containerKey )
configletNames = [ configlet[ 'name' ] for configlet in configletsInfo ]
appliedImageBundle = None
if containerName in imageBundleMap:
appliedImageBundle = imageBundleMap[ containerName ]
return Container( containerName, parentName, configletNames,
appliedImageBundle )
def getUndefContainerInfo( self ):
''' retrieves information about the undefined container
Returns:
containerInfo -- Information about the undefined container
( type : Container( class ) )
'''
containerInfo = self.cvpService.getContainerInfoByKey(
cvpServices.UNDEF_CONTAINER_KEY )
return self.getContainer( containerInfo[ 'name' ] )
def getThemes( self, storageDirPath='' ):
'''Themes are downloaded and saved to the directory given by "storageDirPath"
Argument:
storageDirPath -- path to directory for storing theme files ( optional )
( type : String )
Returns:
themeList -- List of themes downloaded
( type : List of Theme ( class ) )'''
themeList = []
themeFilenamesByType = self.cvpService.getThemes( storageDirPath )
for themeType in themeFilenamesByType.keys():
themeFilenames = themeFilenamesByType[ themeType ]
for i in range( len( themeFilenames ) ):
themeFilename = themeFilenames[ i ]
# first theme is the active theme
themeList.append( Theme( themeFilename, themeType,
isActive=( i == 0 ) ) )
return themeList
def getImages( self , storageDirPath='', download=False ):
'''Images are downloaded and saved in directory path given by "storageDirPath"
Argument:
storageDirPath -- path to directory for storing image files ( optional )
( type : String )
Returns:
imageNameList -- List of inforamtion of images downloaded
( type : List of Image ( class ) )'''
imageList = []
imagesInfo = self.cvpService.getImagesInfo()
for imageInfo in imagesInfo:
rebootRequired = ( imageInfo[ 'isRebootRequired' ] == 'true' )
imageList.append( Image( imageInfo[ 'name' ], rebootRequired ) )
if download:
self.cvpService.downloadImage( imageInfo[ 'name' ],
imageInfo[ 'imageId' ],
storageDirPath )
return imageList
def reconcileDeviceConfig( self, device, configlets ):
'''
Validate the given "configlets", and reconcile against "device".
If a reconcile configlet is generated as a result, return that, or None.
Note that the reconcile configlet needs to be explicitly added to CVP and
mapped to the device by the caller, if desired.
Arguments:
device -- device object
configlets -- List of configlets applied to device
Returns
Reconcile configlet, or None
'''
configletKeyList = self._getConfigletKeys( [ c.name for c in configlets ] )
return self._getReconciledConfiglet( device, configletKeyList )
def _getReconciledConfiglet( self, device, configletKeyList ):
'''
Validate the configlets with keys in "configleyKeyList", and reconcile
against "device".
If a reconcile configlet is generated as a result, return that, or None.
Note that the reconcile configlet needs to be explicitly added to CVP and
mapped to the device by the caller, if desired.
Arguments:
device -- device object
configletKeyList -- List of keys of configlets applied to device
Returns
Reconcile configlet, or None
'''
validateResponse = self.cvpService.validateAndCompareConfiglets(
device.macAddress, configletKeyList )
if not validateResponse[ 'reconciledConfig' ]:
# No reconcile configlet generated
return None
reconcile = ReconciledConfiglet(
validateResponse[ 'reconciledConfig' ][ 'name' ],
validateResponse[ 'reconciledConfig' ][ 'config' ],
device.macAddress )
return reconcile
def reconcileContainer( self, container, wait=True, timeout=0 ):
'''Initiate a reconcile operation on 'container'. This generates an event.
If wait == True, wait for the event to finish, and return the consolidated
report for all devices under the container. timeout is the number of seconds
to wait for, or indefinitely if 0.
If wait == False, Otherwise, just return an event
ID. The caller can call getEvent*() later to query its status.
Returns: Event results or event ID.
Raises: CvpError in case of any error.
'''
assert isinstance( container, Container )
containerInfo = self._getContainerInfo( container.name )
if not containerInfo:
raise cvpServices.CvpError( errorCodes.INVALID_CONTAINER_NAME )
containerId = containerInfo.get( 'key' )
eventId = self.cvpService.reconcileContainer( containerId )[ 'data' ]
if wait:
# wait for the event to complete
end = time.time() + timeout
while True:
if timeout != 0 and time.time() >= end:
break
parentEventData = self.cvpService.getEvent( eventId )[ 'data' ]
if parentEventData[ 'status' ] == 'COMPLETED':
childEventData = self.cvpService.getChildEventData( eventId )
assert parentEventData[ 'total' ] == childEventData[ 'total' ]
events = []
for subEvent in childEventData[ 'data' ]:
assert eventId == subEvent[ 'parentKey' ]
assert subEvent[ 'status' ] == 'COMPLETED'
events.append( Event( subEvent[ 'key' ],
subEvent[ 'parentKey' ],
subEvent[ 'objectId' ],