-
Notifications
You must be signed in to change notification settings - Fork 27
/
aci-preupgrade-validation-script.py
4389 lines (3841 loc) · 189 KB
/
aci-preupgrade-validation-script.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
# SPDX-License-Identifier: Apache-2.0
#
# Copyright 2021 Cisco Systems, Inc. and its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import division
from __future__ import print_function
from six import iteritems
from six.moves import input
from textwrap import TextWrapper
from getpass import getpass
from collections import defaultdict
from datetime import datetime
import warnings
import time
import pexpect
import logging
import subprocess
import json
import sys
import os
import re
SCRIPT_VERSION = "v2.2.1"
DONE = 'DONE'
PASS = 'PASS'
FAIL_O = 'FAIL - OUTAGE WARNING!!'
FAIL_UF = 'FAIL - UPGRADE FAILURE!!'
ERROR = 'ERROR !!'
MANUAL = 'MANUAL CHECK REQUIRED'
POST = 'POST UPGRADE CHECK REQUIRED'
NA = 'N/A'
node_regex = r'topology/pod-(?P<pod>\d+)/node-(?P<node>\d+)'
path_regex = (
r"topology/pod-(?P<pod>\d+)/"
r"(?:prot)?paths-(?P<nodes>\d+|\d+-\d+)/" # direct or PC/vPC
r"(?:ext(?:prot)?paths-(?P<fex>\d+|\d+-\d+)/)?" # FEX (optional)
r"pathep-\[(?P<port>.+)\]" # ethX/Y or PC/vPC IFPG name
)
dom_regex = r"uni/(?:vmmp-[^/]+/)?(?P<type>phys|l2dom|l3dom|dom)-(?P<dom>[^/]+)"
tz = time.strftime('%z')
ts = datetime.now().strftime('%Y-%m-%dT%H-%M-%S')
DIR = 'preupgrade_validator_logs/'
BUNDLE_NAME = 'preupgrade_validator_%s%s.tgz' % (ts, tz)
RESULT_FILE = DIR + 'preupgrade_validator_%s%s.txt' % (ts, tz)
JSON_FILE = DIR + 'preupgrade_validator_%s%s.json' % (ts, tz)
LOG_FILE = DIR + 'preupgrade_validator_debug.log'
fmt = '[%(asctime)s.%(msecs)03d{} %(levelname)-8s %(funcName)20s:%(lineno)-4d] %(message)s'.format(tz)
subprocess.check_output(['mkdir', '-p', DIR])
logging.basicConfig(level=logging.DEBUG, filename=LOG_FILE, format=fmt, datefmt='%Y-%m-%d %H:%M:%S')
warnings.simplefilter(action='ignore', category=FutureWarning)
class OldVerClassNotFound(Exception):
""" Later versions of ACI can have class properties not found in older versions """
pass
class OldVerPropNotFound(Exception):
""" Later versions of ACI can have class properties not found in older versions """
pass
class Connection(object):
"""
Object built primarily for executing commands on Cisco IOS/NXOS devices. The following
methods and variables are available for use in this class:
username (opt) username credential (default 'admin')
password (opt) password credential (default 'cisco')
protocol (opt) telnet/ssh option (default 'ssh')
port (opt) port to connect on (if different from telnet/ssh default)
timeout (opt) wait in seconds between each command (default 30)
prompt (opt) prompt to expect after each command (default for IOS/NXOS)
log (opt) logfile (default None)
verify (opt) verify/enforce strictHostKey values for SSL (disabled by default)
searchwindowsize (opt) maximum amount of data used in matching expressions
extremely important to set to a low value for large outputs
pexpect default = None, setting this class default=256
force_wait (opt) some OS ignore searchwindowsize and therefore still experience high
CPU and long wait time for commands with large outputs to complete.
A workaround is to sleep the script instead of running regex checking
for prompt character.
This should only be used in those unique scenarios...
Default is 0 seconds (disabled). If needed, set to 8 (seconds)
functions:
connect() (opt) connect to device with provided protocol/port/hostname
login() (opt) log into device with provided credentials
close() (opt) close current connection
cmd() execute a command on the device (provide matches and timeout)
Example using all defaults
c = Connection("10.122.140.89")
c.cmd("terminal length 0")
c.cmd("show version")
print "version of code: %s" % c.output
@author [email protected]
@version 07/28/2014
"""
def __init__(self, hostname):
self.hostname = hostname
self.log = None
self.username = 'admin'
self.password = 'cisco'
self.protocol = "ssh"
self.port = None
self.timeout = 30
self.prompt = "#\s.*$" #"[^#]#[ ]*(.*)*[ ]*$"
self.verify = False
self.searchwindowsize = 256
self.force_wait = 0
self.child = None
self.output = "" # output from last command
self._term_len = 0 # terminal length for cisco devices
self._login = False # set to true at first successful login
self._log = None # private variable for tracking logfile state
def __connected(self):
# determine if a connection is already open
connected = (self.child is not None and self.child.isatty())
logging.debug("check for valid connection: %r" % connected)
return connected
@property
def term_len(self):
return self._term_len
@term_len.setter
def term_len(self, term_len):
self._term_len = int(term_len)
if (not self.__connected()) or (not self._login):
# login function will set the terminal length
self.login()
else:
# user changing terminal length during operation, need to explicitly
self.cmd("terminal length %s" % self._term_len)
def start_log(self):
""" start or restart sending output to logfile """
if self.log is not None and self._log is None:
# if self.log is a string, then attempt to open file pointer (do not catch exception, we want it
# to die if there's an error opening the logfile)
if isinstance(self.log, str) or isinstance(self.log, unicode):
self._log = open(self.log, "ab")
else:
self._log = self.log
logging.debug("setting logfile to %s" % self._log.name)
if self.child is not None:
self.child.logfile = self._log
def stop_log(self):
""" stop sending output to logfile """
self.child.logfile = None
self._log = None
return
def connect(self):
# close any currently open connections
self.close()
# determine port if not explicitly set
if self.port is None:
if self.protocol == "ssh":
self.port = 22
if self.protocol == "telnet":
self.port = 23
# spawn new thread
if self.protocol.lower() == "ssh":
logging.debug(
"spawning new pexpect connection: ssh %s@%s -p %d" % (self.username, self.hostname, self.port))
no_verify = " -o StrictHostKeyChecking=no -o LogLevel=ERROR -o UserKnownHostsFile=/dev/null"
if self.verify: no_verify = ""
self.child = pexpect.spawn("ssh %s %s@%s -p %d" % (no_verify, self.username, self.hostname, self.port),
searchwindowsize=self.searchwindowsize)
elif self.protocol.lower() == "telnet":
logging.info("spawning new pexpect connection: telnet %s %d" % (self.hostname, self.port))
self.child = pexpect.spawn("telnet %s %d" % (self.hostname, self.port),
searchwindowsize=self.searchwindowsize)
else:
logging.error("unknown protocol %s" % self.protocol)
raise Exception("Unsupported protocol: %s" % self.protocol)
# start logging
self.start_log()
def close(self):
# try to gracefully close the connection if opened
if self.__connected():
logging.info("closing current connection")
self.child.close()
self.child = None
self._login = False
def __expect(self, matches, timeout=None):
"""
receives a dictionary 'matches' and returns the name of the matched item
instead of relying on the index into a list of matches. Automatically
adds following options if not already present
"eof" : pexpect.EOF
"timeout" : pexpect.TIMEOUT
"""
if "eof" not in matches:
matches["eof"] = pexpect.EOF
if "timeout" not in matches:
matches["timeout"] = pexpect.TIMEOUT
if timeout is None: timeout = self.timeout
indexed = []
mapping = []
for i in matches:
indexed.append(matches[i])
mapping.append(i)
result = self.child.expect(indexed, timeout)
logging.debug("timeout: %d, matched: '%s'\npexpect output: '%s%s'" % (
timeout, self.child.after, self.child.before, self.child.after))
if result <= len(mapping) and result >= 0:
logging.debug("expect matched result[%d] = %s" % (result, mapping[result]))
return mapping[result]
ds = ''
logging.error("unexpected pexpect return index: %s" % result)
for i in range(0, len(mapping)):
ds += '[%d] %s\n' % (i, mapping[i])
logging.debug("mapping:\n%s" % ds)
raise Exception("Unexpected pexpect return index: %s" % result)
def login(self, max_attempts=7, timeout=17):
"""
returns true on successful login, else returns false
"""
logging.debug("Logging into host")
# successfully logged in at a different time
if not self.__connected(): self.connect()
# check for user provided 'prompt' which indicates successful login
# else provide approriate username/password
matches = {
"console": "(?i)press return to get started",
"refuse": "(?i)connection refused",
"yes/no": "(?i)yes/no",
"username": "(?i)(user(name)*|login)[ as]*[ \t]*:[ \t]*$",
"password": "(?i)password[ \t]*:[ \t]*$",
"prompt": self.prompt
}
last_match = None
while max_attempts > 0:
max_attempts -= 1
match = self.__expect(matches, timeout)
if match == "console": # press return to get started
logging.debug("matched console, send enter")
self.child.sendline("\r\n")
elif match == "refuse": # connection refused
logging.error("connection refused by host")
return False
elif match == "yes/no": # yes/no for SSH key acceptance
logging.debug("received yes/no prompt, send yes")
self.child.sendline("yes")
elif match == "username": # username/login prompt
logging.debug("received username prompt, send username")
self.child.sendline(self.username)
elif match == "password":
# don't log passwords to the logfile
self.stop_log()
logging.debug("matched password prompt, send password")
self.child.sendline(self.password)
# restart logging
self.start_log()
elif match == "prompt":
logging.debug("successful login")
self._login = True
# force terminal length at login
self.term_len = self._term_len
return True
elif match == "timeout":
logging.debug("timeout received but connection still opened, send enter")
self.child.sendline("\r\n")
last_match = match
# did not find prompt within max attempts, failed login
logging.error("failed to login after multiple attempts")
return False
def cmd(self, command, **kargs):
"""
execute a command on a device and wait for one of the provided matches to return.
Required argument string command
Optional arguments:
timeout - seconds to wait for command to completed (default to self.timeout)
sendline - boolean flag to use send or sendline fuction (default to true)
matches - dictionary of key/regex to match against. Key corresponding to matched
regex will be returned. By default, the following three keys/regex are applied:
'eof' : pexpect.EOF
'timeout' : pexpect.TIMEOUT
'prompt' : self.prompt
echo_cmd - boolean flag to echo commands sent (default to false)
note most terminals (i.e., Cisco devices) will echo back all typed characters
by default. Therefore, enabling echo_cmd may cause duplicate cmd characters
Return:
returns the key from the matched regex. For most scenarios, this will be 'prompt'. The output
from the command can be collected from self.output variable
"""
sendline = True
timeout = self.timeout
matches = {}
echo_cmd = False
if "timeout" in kargs:
timeout = kargs["timeout"]
if "matches" in kargs:
matches = kargs["matches"]
if "sendline" in kargs:
sendline = kargs["sendline"]
if "echo_cmd" in kargs:
echo_cmd = kargs["echo_cmd"]
# ensure prompt is in the matches list
if "prompt" not in matches:
matches["prompt"] = self.prompt
self.output = ""
# check if we've ever logged into device or currently connected
if (not self.__connected()) or (not self._login):
logging.debug("no active connection, attempt to login")
if not self.login():
raise Exception("failed to login to host")
# if echo_cmd is disabled, then need to disable logging before
# executing commands
if not echo_cmd: self.stop_log()
# execute command
logging.debug("cmd command: %s" % command)
if sendline:
self.child.sendline(command)
else:
self.child.send(command)
# remember to re-enable logging
if not echo_cmd: self.start_log()
# force wait option
if self.force_wait != 0:
time.sleep(self.force_wait)
result = self.__expect(matches, timeout)
self.output = "%s%s" % (self.child.before, self.child.after)
if result == "eof" or result == "timeout":
logging.warning("unexpected %s occurred" % result)
return result
class IPAddress:
"""Custom IP handling class since old APICs do not have `ipaddress` module.
"""
@classmethod
def ip_to_binary(cls, ip):
if ':' in ip:
return cls.ipv6_to_binary(ip)
else:
return cls.ipv4_to_binary(ip)
@staticmethod
def ipv4_to_binary(ipv4):
octets = ipv4.split(".")
octets_bin = [format(int(octet), "08b") for octet in octets]
return "".join(octets_bin)
@staticmethod
def ipv6_to_binary(ipv6):
HEXTET_COUNT = 8
_hextets = ipv6.split(":")
dbl_colon_index = None
if '' in _hextets:
# leading/trailing '::' results in additional '' at the beginning/end.
if _hextets[0] == '':
_hextets = _hextets[1:]
if _hextets[-1] == '':
_hextets = _hextets[:-1]
# Uncompress all zero hextets represented by '::'
dbl_colon_index = _hextets.index('')
skipped_hextets = HEXTET_COUNT - len(_hextets) + 1
hextets = _hextets[:dbl_colon_index]
hextets += ['0'] * skipped_hextets
hextets += _hextets[dbl_colon_index+1:]
else:
hextets = _hextets
hextets_bin = [format(int(hextet, 16), "016b") for hextet in hextets]
return "".join(hextets_bin)
@classmethod
def get_network_binary(cls, ip, pfxlen):
maxlen = 128 if ':' in ip else 32
ip_bin = cls.ip_to_binary(ip)
return ip_bin[0:maxlen-(maxlen-int(pfxlen))]
@classmethod
def ip_in_subnet(cls, ip, subnet):
if "/" not in subnet:
return False
subnet_ip, subnet_pfxlen = subnet.split("/")
subnet_network = cls.get_network_binary(subnet_ip, subnet_pfxlen)
ip_network = cls.get_network_binary(ip, subnet_pfxlen)
return ip_network == subnet_network
class AciVersion():
v_regex = r'(?:dk9\.)?[1]?(?P<major1>\d)\.(?P<major2>\d)(?:\.|\()(?P<maint>\d+)\.?(?P<patch>(?:[a-b]|[0-9a-z]+))\)?'
def __init__(self, version):
self.original = version
v = re.search(self.v_regex, version)
self.version = ('{major1}.{major2}({maint}{patch})'
.format(**v.groupdict()) if v else None)
self.dot_version = ("{major1}.{major2}.{maint}{patch}"
.format(**v.groupdict()) if v else None)
self.simple_version = ("{major1}.{major2}({maint})"
.format(**v.groupdict()) if v else None)
self.major1 = v.group('major1') if v else None
self.major2 = v.group('major2') if v else None
self.maint = v.group('maint') if v else None
self.patch = v.group('patch') if v else None
self.regex = v
if not v:
raise RuntimeError("Parsing failure of ACI version `%s`", version)
def __str__(self):
return self.version
def older_than(self, version):
v = re.search(self.v_regex, version)
if not v: return None
for i in range(1, len(v.groups())+1):
if i < 4:
if int(self.regex.group(i)) > int(v.group(i)): return False
elif int(self.regex.group(i)) < int(v.group(i)): return True
if i == 4:
if self.regex.group(i) > v.group(i): return False
elif self.regex.group(i) < v.group(i): return True
return False
def newer_than(self, version):
return not self.older_than(version) and not self.same_as(version)
def same_as(self, version):
v = re.search(self.v_regex, version)
ver = ('{major1}.{major2}({maint}{patch})'
.format(**v.groupdict()) if v else None)
return self.version == ver
class AciObjectCrawler(object):
"""
Args:
mos (list of dict): MOs in the form of output from the function `icurl()` with
the filter `query-target` that returns a flat list.
"""
def __init__(self, mos):
self.mos = mos
self.mos_per_class = defaultdict(list)
self.init_mos_per_class()
def init_mos_per_class(self):
"""
Create `self.mos_per_class` (dict) which stores lists of MOs per class.
"""
for mo in self.mos:
classname = list(mo.keys())[0]
_mo = {"classname": classname}
_mo.update(mo[classname]["attributes"])
self.mos_per_class[classname].append(_mo)
def get_mos(self, classname):
return self.mos_per_class.get(classname, [])
def get_children(self, parent_dn, children_class):
"""
Args:
parent_dn (str): DN of the parent MO.
children_class (str): Class name of the (grand) children under parent_dn.
Returns:
list of dict: The MOs of children_class under parent_dn.
"""
mos = self.get_mos(children_class)
return [mo for mo in mos if mo["dn"].startswith(parent_dn + "/")]
def get_parent(self, child_dn, parent_class):
"""
Args:
child_dn (str): DN of the child MO.
parent_class (str): Class name of the (grand) parent of child_dn.
Returns:
dict: The parent MO of child_dn.
"""
mos = self.get_mos(parent_class)
for mo in mos:
if child_dn.startswith(mo["dn"] + "/"):
return mo
return {}
def get_rel_targets(self, src_dn, rel_class):
"""
Args:
src_dn (str): DN of the source object.
rel_class (str): Relation class with tDn/tCl. Children of src_dn
Returns:
list of dict: MOs that are pointed by tDn from src_dn
"""
targets = []
rel_mos = self.get_children(src_dn, rel_class)
for rel_mo in rel_mos:
mos = self.get_mos(rel_mo["tCl"])
for mo in mos:
if mo["dn"] == rel_mo["tDn"]:
targets.append(mo)
break
else:
# The target objects may not be in our self.mos_per_class.
# In that case, just return the DN and class.
targets.append({"dn": rel_mo["tDn"], "classname": rel_mo["tCl"]})
return targets
def get_src_from_tDn(self, tDn, rs_class, src_class):
"""
Args:
tDn (str): Target DN. Get all MOs with this DN as the target via rs_class.
rs_class (str): Relation class.
src_class (str): Class name of source MOs that may have tDn as the target
via rs_class.
Returns:
list of dict: MOs that point to tDn via rs_class.
"""
src_mos = []
rs_mos = self.get_mos(rs_class)
for rs_mo in rs_mos:
if rs_mo["tDn"] == tDn:
src_mo = self.get_parent(rs_mo["dn"], src_class)
if src_mo:
src_mos.append(src_mo)
return src_mos
class AciAccessPolicyParser(AciObjectCrawler):
"""
port_data:
key: port_path in the format shown below:
`<node_id>/eth<card_id>/<port_id>`
`<node_id>/<fex_id>/eth<card_id>/<port_id>`
`<node_id>/<IFPG name>`
`<node_id>/<fex_id>/<IFPG name>`
value: {
"ifpg": Name of IFPG
"override_ifpg": Name of override IFPG. Skipped if not override
"pc_type": none|pc|vpc. From the IFPG
"aep": Name of AEP
"domain_dns": List of domain DNs associated to the AEP
"vlan_scope": global or portlocal. From the IFPG
"node": Node ID
"fex": Fex ID or 0
"port": ethX/Y, ethX/Y/Z, IFPG name
}
vpool_per_dom:
key: domain DN
value: {
"name": Name of VLAN Pool
"vlan_ids": List of VLAN IDs. ex) [1,2,3,100,101]
"dom_name": Name of domain
"dom_type": Type of domain (phys, l3dom, vmm)
}
"""
# VLAN Pool
VLANPool = "fvnsVlanInstP"
VLANBlk = "fvnsEncapBlk"
# AEP
AEP = "infraAttEntityP"
# Leaf Interface Profile etc.
IFP = "infraAccPortP"
IFSel = "infraHPortS"
PortBlk = "infraPortBlk"
SubPortBlk = "infraSubPortBlk" # breakout
IFPath = "infraHPathS" # override
# Leaf Switch Profile etc.
SWP = "infraNodeP"
SWSel = "infraLeafS"
NodeBlk = "infraNodeBlk"
# FEX
FEXP = "infraFexP"
FEXPG = "infraFexBndlGrp"
# Leaf Interface Policy Group etc.
IFPG = "infraAccPortGrp"
IFPG_PC = "infraAccBndlGrp"
IFPG_PC_O = "infraAccBndlPolGrp" # override (PC/VPC PG)
# Leaf Interface Policy
IFPol_L2 = "l2IfPol"
# Relation objects (<src>_to_<tDn>)
VLAN_to_Dom = "fvnsRtVlanNs"
AEP_to_Dom = "infraRsDomP"
IFPG_to_AEP = "infraRsAttEntP"
IFSel_to_IFPG = "infraRsAccBaseGrp"
IFPath_to_IFPG = "infraRsPathToAccBaseGrp" # override
IFPath_to_Path = "infraRsHPathAtt" # override
SWP_to_IFP = "infraRsAccPortP"
IFPol_L2_to_IFPG = "l2RtL2IfPol"
def __init__(self, mos):
super(AciAccessPolicyParser, self).__init__(mos)
self.nodes_per_ifp = defaultdict(list)
self.port_data = defaultdict(dict)
self.vpool_per_dom = defaultdict(dict)
self.create_port_data()
self.create_vlanpool_per_domain()
@classmethod
def get_classes(cls):
"""Get all ACI object classes used in this class"""
classes = []
for key, val in iteritems(AciAccessPolicyParser.__dict__):
if key.startswith("__") or not isinstance(val, str):
continue
classes.append(val)
return classes
def get_node_ids_from_ifp(self, ifp_dn):
if ifp_dn in self.nodes_per_ifp:
return self.nodes_per_ifp[ifp_dn]
node_ids = []
swps = self.get_src_from_tDn(ifp_dn, self.SWP_to_IFP, self.SWP)
for swp in swps:
swsels = self.get_children(swp["dn"], self.SWSel)
for swsel in swsels:
node_blks = self.get_children(swsel["dn"], self.NodeBlk)
for node_blk in node_blks:
_from = int(node_blk["from_"])
_to = int(node_blk["to_"])
node_ids += range(_from, _to + 1)
self.nodes_per_ifp[ifp_dn] = node_ids
return node_ids
def get_node_ids_from_ifsel(self, ifsel_dn):
ifp = self.get_parent(ifsel_dn, self.IFP)
if not ifp:
logging.warning("No I/F Profile for Selector (%s)", ifsel_dn)
return []
node_ids = self.get_node_ids_from_ifp(ifp["dn"])
return node_ids
def get_fex_id_from_ifsel(self, ifsel_dn):
"""Get FEX ID if ifsel is FEX NIF"""
fex_id = 0
rs_ifpgs = self.get_children(ifsel_dn, self.IFSel_to_IFPG)
if rs_ifpgs and rs_ifpgs[0]["tCl"] == "infraFexBndlGrp":
fex_id = int(rs_ifpgs[0]["fexId"])
return fex_id
def get_fexnif_ifsels_from_fexhif(self, hif_ifsel_dn):
"""
Get FEX NIF I/F selectors from a FEX HIF I/F Selector
"""
# 1. Get FEXPG from FEX HIF IFSel via the parent (FEXP).
# FEXP -+- IFSel (FEX HIF)
# +- FEXPG
fexp = self.get_parent(hif_ifsel_dn, self.FEXP)
if not fexp:
return []
fexpgs = self.get_children(fexp["dn"], self.FEXPG)
if not fexpgs:
return []
# There should be only one FEXPG for each FEXP
fexpg = fexpgs[0]
# 2. Get FEX NIF IFSels from FEXPG via the relation.
# IFSel (FEX NIF) <--[IFSel_to_IFPG]-- FEXPG
fexnif_ifsels = self.get_src_from_tDn(
fexpg["dn"], self.IFSel_to_IFPG, self.IFSel
)
return fexnif_ifsels
def get_ports_from_ifsel(self, ifsel_dn):
ports = []
port_blks = self.get_children(ifsel_dn, self.PortBlk)
subport_blks = self.get_children(ifsel_dn, self.SubPortBlk)
for port_blk in port_blks + subport_blks:
from_card = int(port_blk["fromCard"])
from_port = int(port_blk["fromPort"])
from_subport = int(port_blk["fromSubPort"]) if port_blk["classname"] == self.SubPortBlk else 0
to_card = int(port_blk["toCard"])
to_port = int(port_blk["toPort"])
to_subport = int(port_blk["toSubPort"]) if port_blk["classname"] == self.SubPortBlk else 0
for card in range(from_card, to_card + 1):
for port in range(from_port, to_port + 1):
for subport in range(from_subport, to_subport + 1):
if subport:
ports.append("eth{}/{}/{}".format(card, port, subport))
else:
ports.append("eth{}/{}".format(card, port))
return ports
def create_port_data(self):
ifsels = self.get_mos(self.IFSel)
for ifsel in ifsels:
# GET Node IDs and FEX IDs
node2fexid = {}
if ifsel["dn"].startswith("uni/infra/fexprof-"):
# When ifsel is of FEX HIF, get node IDs and FEX IDs from FEX NIFs.
# ACI supports only single-homed FEXes with or without vPC.
# One FEX HIF can be tied to 2 nodes, one FEX for each, at maximum.
nifs = self.get_fexnif_ifsels_from_fexhif(ifsel["dn"])
for nif in nifs:
_node_ids = self.get_node_ids_from_ifsel(nif["dn"])
fex_id = self.get_fex_id_from_ifsel(nif["dn"])
for _node_id in _node_ids:
node2fexid[_node_id] = fex_id
node_ids = node2fexid.keys()
if len(node_ids) > 2:
logging.error(
"FEX HIF handling failed as it shows more than 2 nodes."
)
break
else:
node_ids = self.get_node_ids_from_ifsel(ifsel["dn"])
if not node_ids:
continue
# Get IFPG
ifpgs = self.get_rel_targets(ifsel["dn"], self.IFSel_to_IFPG)
if not ifpgs:
continue
ifpg = ifpgs[0]
# Get ports or use IFPG Name for PC/VPC
if ifpg.get("classname") == self.IFPG_PC and ifpg.get("name"):
ports = [ifpg["name"]]
else:
ports = self.get_ports_from_ifsel(ifsel["dn"])
if not ports:
continue
# Get settings from IFPG
pc_type = self.get_pc_type(ifpg)
l2if = self.get_ifpol_l2if_from_ifpg(ifpg["dn"])
vlan_scope = l2if.get("vlanScope", "unknown")
# Get AEP from IFPG
aeps = self.get_rel_targets(ifpg.get("dn", ""), self.IFPG_to_AEP)
aep = aeps[0] if aeps else {}
# Get Domains from AEP
doms = self.get_rel_targets(aep.get("dn", ""), self.AEP_to_Dom)
for node_id in node_ids:
fex_id = node2fexid.get(node_id, 0)
for port in ports:
if fex_id:
path = "/".join([str(node_id), str(fex_id), port])
else:
path = "/".join([str(node_id), port])
self.port_data[path] = {
"node": str(node_id),
"fex": str(fex_id),
"port": port,
"ifpg_name": ifpg.get("name", ""),
"pc_type": pc_type,
"vlan_scope": vlan_scope,
"aep_name": aep.get("name", ""),
"domain_dns": [dom["dn"] for dom in doms],
}
# Override
ifpaths = self.get_mos(self.IFPath)
for ifpath in ifpaths:
# Get Node/FEX/Port ID
override_paths = self.get_children(ifpath["dn"], self.IFPath_to_Path)
if not override_paths:
continue
override_path = override_paths[0]
p = re.search(path_regex, override_path["tDn"])
nodes = p.group("nodes").split("-")
fexes = p.group("fex").split("-") if p.group("fex") else []
port = p.group("port")
# Get IFPG
ifpgs = self.get_rel_targets(ifpath["dn"], self.IFPath_to_IFPG)
if not ifpgs:
continue
ifpg = ifpgs[0]
# Get settings from IFPG
l2if = self.get_ifpol_l2if_from_ifpg(ifpg["dn"])
vlan_scope = l2if.get("vlanScope", "unknown")
# Get AEP from IFPG
aeps = self.get_rel_targets(ifpg.get("dn", ""), self.IFPG_to_AEP)
aep = aeps[0] if aeps else {}
# Get Domains from AEP
doms = self.get_rel_targets(aep.get("dn", ""), self.AEP_to_Dom)
for idx, node in enumerate(nodes):
fex = "0"
if fexes:
fex = fexes[0] if len(fexes) == 1 else fexes[idx]
path = "/".join([node, fex, port])
else:
path = "/".join([node, port])
self.port_data[path].update({
"node": node,
"fex": fex,
"port": port,
"override_ifpg_name": ifpg.get("name", ""),
"vlan_scope": vlan_scope,
"aep_name": aep.get("name", ""),
"domain_dns": [dom["dn"] for dom in doms],
})
def create_vlanpool_per_domain(self):
vlan_pools = self.get_mos(self.VLANPool)
for vlan_pool in vlan_pools:
vlan_ids = []
vlan_blks = self.get_children(vlan_pool["dn"], self.VLANBlk)
for vlan_blk in vlan_blks:
vlan_ids += range(
int(vlan_blk["from"].split("-")[1]),
int(vlan_blk["to"].split("-")[1]) + 1,
)
rs_domains = self.get_children(vlan_pool["dn"], self.VLAN_to_Dom)
for rs_domain in rs_domains:
dom_match = re.search(dom_regex, rs_domain["tDn"])
dom_name = "..." if not dom_match else dom_match.group("dom")
dom_type = "..." if not dom_match else dom_match.group("type")
# No need to worry about overwrite because there can be
# only one VLAN pool per domain.
self.vpool_per_dom[rs_domain["tDn"]] = {
"name": vlan_pool["name"],
"vlan_ids": vlan_ids,
"dom_name": dom_name,
"dom_type": "vmm" if dom_type == "dom" else dom_type,
}
return self.vpool_per_dom
def get_pc_type(self, ifpg):
pc_type = "none"
if ifpg.get("lagT") == "node":
pc_type = "vpc"
elif ifpg.get("lagT") in ["link", "fc-link"]:
pc_type = "pc"
return pc_type
def get_ifpol_l2if_from_ifpg(self, ifpg_dn):
ifpol_l2s = self.get_src_from_tDn(ifpg_dn, self.IFPol_L2_to_IFPG, self.IFPol_L2)
return ifpol_l2s[0] if ifpol_l2s else {}
def is_firstver_gt_secondver(first_ver, second_ver):
""" Used for CIMC version comparison """
result = False
if first_ver[0] > second_ver[0]:
return True
elif first_ver[0] == second_ver[0]:
if first_ver[2] > second_ver[2]:
return True
elif first_ver[2] == second_ver[2]:
if first_ver[4] > second_ver[4]:
return True
elif first_ver[4] == second_ver[4]:
if first_ver[5] >= second_ver[5]:
result = True
return result
def format_table(headers, data,
min_width=5, left_padding=2, hdr_sp='-', col_sp=' '):
""" get string results in table format
Args:
header (list): list of column headers (optional)
each header can either be a string representing the name or a
dictionary with following attributes:
{
name (str): column name
width (int or str): integer width of column. can also be a string 'auto'
which is based on the longest string in column
max_width (int): integer value of max width when combined with
}
data (list): list of rows, where each row is a list of values
corresponding to the appropriate header. If length of row
exceeds length of headers, it is is ignored.
min_width (int, optional): minimum width enforced on any auto-calculated column. Defaults to 5.
left_padding (int, optional): number of spaces to 'pad' left most column. Defaults to 2.
hdr_sp (str, optional): print a separator string between hdr and data row. Defaults to '-'.
col_sp (str, optional): print a separator string between data columns. Defaults to ' '.
Returns:
str: table with columns aligned with spacing
"""
if type(data) is not list or len(data) == 0:
return ""
cl = 800
col_widths = []
rows = []
def update_col_widths(idx, new_width):
if len(col_widths) < idx + 1:
col_widths.append(new_width)
elif col_widths[idx] < new_width:
col_widths[idx] = new_width
for row in data:
if type(row) is not list:
return ""
for idx, col in enumerate(row):
update_col_widths(idx, len(str(col)))
rows.append([str(col) for col in row])
h_cols = []
for idx, col in enumerate(headers):
if isinstance(col, str):
update_col_widths(idx, len(col))
h_cols.append({'name': col, 'width': 'auto'})
elif isinstance(col, dict):
name = col.get('name', '')
width = col.get('width', '')
max_w = col.get('max_width', 0)
update_col_widths(idx, len(name))
if width == 'auto' and max_w:
try:
if int(max_w) < col_widths[idx]:
col_widths[idx] = int(max_w)
except ValueError:
max_w = 0
else:
try:
col_widths[idx] = int(width)
except ValueError:
width = 'auto'
h_cols.append({'name': name, 'width': width})
# Adjust column width to fit the table with
recovery_width = 3 * min_width
total_width = sum(col_widths) + len(col_sp) * len(col_widths) + left_padding
for idx, h in enumerate(h_cols):
if total_width <= cl: break
if h['width'] == 'auto' and col_widths[idx] > recovery_width:
total_width -= col_widths[idx] - recovery_width
col_widths[idx] = recovery_width
pad = ' ' * left_padding
output = []
if headers:
output.append(
get_row(col_widths, [c['name'] for c in h_cols], col_sp, pad)
)
if isinstance(hdr_sp, str):
if len(hdr_sp) > 0:
hsp_sp = hdr_sp[0] # only single char for hdr_sp
values = [hsp_sp * len(c['name']) for c in h_cols]
output.append(
get_row(col_widths, values, col_sp, pad)
)
for row in rows:
output.append(get_row(col_widths, row, col_sp, pad))
return '\n'.join(output)
def get_row(widths, values, spad=" ", lpad=""):
cols = []
row_maxnum = 0
for i, value in enumerate(values):
w = widths[i] if widths[i] > 0 else 1
tw = TextWrapper(width=w)
lines = []
for v in value.split('\n'):
lines += tw.wrap(v)
cols.append({'width': w, 'lines': lines})
if row_maxnum < len(lines): row_maxnum = len(lines)
spad2 = ' ' * len(spad) # space separators except for the 1st line
output = []
for i in range(row_maxnum):
row = []
for c in cols:
if len(c['lines']) > i:
row.append('{:{}}'.format(c['lines'][i], c['width']))
else:
row.append('{:{}}'.format('', c['width']))
if not output: