-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathminigraph.py
2967 lines (2598 loc) · 134 KB
/
minigraph.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
from __future__ import print_function
import ipaddress
import math
import os
import sys
import json
import jinja2
import subprocess
from collections import defaultdict
from lxml import etree as ET
from lxml.etree import QName
from natsort import natsorted, ns as natsortns
from portconfig import get_port_config, get_fabric_port_config, get_fabric_monitor_config
from sonic_py_common.interface import backplane_prefix
from sonic_py_common.multi_asic import is_multi_asic, get_asic_id_from_name
# TODO: Remove this once we no longer support Python 2
if sys.version_info.major == 3:
UNICODE_TYPE = str
else:
UNICODE_TYPE = unicode
try:
if os.environ["CFGGEN_UNIT_TESTING_TOPOLOGY"] == "multi_asic":
import mock
is_multi_asic = mock.MagicMock(return_value=True)
except KeyError:
pass
"""minigraph.py
version_added: "1.9"
author: Guohan Lu ([email protected])
short_description: Parse minigraph xml file and device description xml file
"""
ns = "Microsoft.Search.Autopilot.Evolution"
ns1 = "http://schemas.datacontract.org/2004/07/Microsoft.Search.Autopilot.Evolution"
ns2 = "Microsoft.Search.Autopilot.NetMux"
ns3 = "http://www.w3.org/2001/XMLSchema-instance"
# Device types
spine_chassis_frontend_role = 'SpineChassisFrontendRouter'
chassis_backend_role = 'ChassisBackendRouter'
backend_device_types = ['BackEndToRRouter', 'BackEndLeafRouter']
console_device_types = ['MgmtTsToR']
dhcp_server_enabled_device_types = ['BmcMgmtToRRouter']
mgmt_device_types = ['BmcMgmtToRRouter', 'MgmtToRRouter', 'MgmtTsToR']
leafrouter_device_types = ['LeafRouter']
# Counters disabled on management devices
mgmt_disabled_counters = ["BUFFER_POOL_WATERMARK", "PFCWD", "PG_DROP", "PG_WATERMARK", "PORT_BUFFER_DROP", "QUEUE", "QUEUE_WATERMARK"]
VLAN_SUB_INTERFACE_SEPARATOR = '.'
VLAN_SUB_INTERFACE_VLAN_ID = '10'
FRONTEND_ASIC_SUB_ROLE = 'FrontEnd'
BACKEND_ASIC_SUB_ROLE = 'BackEnd'
FABRIC_ASIC_SUB_ROLE = 'Fabric'
dualtor_cable_types = ["active-active", "active-standby"]
# Default Virtual Network Index (VNI)
vni_default = 8000
# Defination of custom acl table types
acl_table_type_defination = {
'BMCDATA': {
"ACTIONS": ["PACKET_ACTION", "COUNTER"],
"BIND_POINTS": ["PORT"],
"MATCHES": ["SRC_IP", "DST_IP", "ETHER_TYPE", "IP_TYPE", "IP_PROTOCOL", "IN_PORTS", "L4_SRC_PORT", "L4_DST_PORT", "L4_SRC_PORT_RANGE", "L4_DST_PORT_RANGE"]
},
'BMCDATAV6': {
"ACTIONS": ["PACKET_ACTION", "COUNTER"],
"BIND_POINTS": ["PORT"],
"MATCHES": ["SRC_IPV6", "DST_IPV6", "ETHER_TYPE", "IP_TYPE", "IP_PROTOCOL", "IN_PORTS", "L4_SRC_PORT", "L4_DST_PORT", "L4_SRC_PORT_RANGE", "L4_DST_PORT_RANGE", "ICMPV6_TYPE", "ICMPV6_CODE", "TCP_FLAGS"]
}
}
# Chassis card type
CHASSIS_CARD_VOQ = 'VoQ'
CHASSIS_CARD_PACKET = 'chassis-packet'
CHASSIS_CARD_FABRIC = 'Fabric'
voq_internal_intfs = ['cpu', 'recirc', 'inband']
def get_asic_switch_id(slot_index, asic_name):
asic_id = 0
if slot_index is None:
return None
if asic_name is not None:
asic_id = int(asic_name[len('ASIC'):])
switch_id = 2*(2*(int(slot_index)-1) + asic_id)
return switch_id
def get_asic_hostname_from_asic_name(chassis_type, asic_name, hostname):
if is_multi_asic() == True and asic_name is None:
return asic_name
if is_minigraph_for_chassis(chassis_type):
# for chassis in the minigraph the asic hostname is <asic_name>-<hostname>
if is_multi_asic():
asic_id = get_asic_id_from_name(asic_name)
else:
asic_id = '0'
asic_hostname = "{}-ASIC{:02d}".format(hostname, int(asic_id ))
else:
# for multi_asic pizza boxes the asic_hostname is same as asic_name
asic_hostname = asic_name
return asic_hostname
def get_linecard_slot_index(hostname, chassis_linecard_info):
for lc_slot, lc_name in chassis_linecard_info.items():
if hostname.lower() == lc_name['hostname'].lower():
return lc_slot
return None
def get_voq_intf_attributes(ports):
voq_intf_attributes = {}
for port in ports:
role = ports.get(port, {}).get('role', None)
if role.lower() == 'inb' or role.lower() == 'rec':
core_id = None
core_port_index = None
speed = None
for k,v in ports.get(port, {}).items():
if k.lower() == 'core_id':
core_id = v
if k.lower() == 'core_port_id':
core_port_index = v
if k.lower() == 'speed':
speed = v
voq_intf_attributes.setdefault(role.lower(), {}).update({'core_id': core_id, 'core_port_index': core_port_index, 'speed' : speed})
return voq_intf_attributes
def get_chassis_type_and_hostname(root, hname):
chassis_type = None
chassis_hostname = None
for child in root:
if child.tag == str(QName(ns, "MetadataDeclaration")):
devices = child.find(str(QName(ns, "Devices")))
for device_meta in devices.findall(str(QName(ns1, "DeviceMetadata"))):
device_name = device_meta.find(str(QName(ns1, "Name"))).text
if device_name != hname:
continue
properties = device_meta.find(str(QName(ns1, "Properties")))
for device_property in properties.findall(str(QName(ns1, "DeviceProperty"))):
name = device_property.find(str(QName(ns1, "Name"))).text
value = device_property.find(str(QName(ns1, "Value"))).text
if name == "ForwardingMethod":
chassis_type = value
if name == "ParentRouter":
chassis_hostname = value
return chassis_type, chassis_hostname
def is_chassis_lc_macsec_enabled(root, hname):
macsec_enble = None
for child in root:
if child.tag == str(QName(ns, "MetadataDeclaration")):
devices = child.find(str(QName(ns, "Devices")))
for device_meta in devices.findall(str(QName(ns1, "DeviceMetadata"))):
device_name = device_meta.find(str(QName(ns1, "Name"))).text
if device_name != hname:
continue
properties = device_meta.find(str(QName(ns1, "Properties")))
for device_property in properties.findall(str(QName(ns1, "DeviceProperty"))):
name = device_property.find(str(QName(ns1, "Name"))).text
value = device_property.find(str(QName(ns1, "Value"))).text
if name == "MacSecEnabled":
macsec_enble = value
return macsec_enble
def is_minigraph_for_chassis(chassis_type):
if chassis_type in [CHASSIS_CARD_VOQ, CHASSIS_CARD_PACKET]:
return True
return False
def normailize_port_map_for_chassis(asic_name, port_map):
if asic_name is None:
return port_map
new_port_map = {}
for k,v in port_map.items():
if asic_name.lower() in v.lower():
v = v.split('-')[0]
if asic_name.lower() in k.lower():
k = k.split('-')[0]
new_port_map.update({k:v})
return new_port_map
###############################################################################
#
# Minigraph parsing functions
#
###############################################################################
def parse_chassis_metadata(root,hname, lcname):
"""
Parses the chassis metadata from the XML root.
This function iterates over the XML root to find the metadata declaration. It then extracts the device metadata,
specifically the name, properties, and slot index. If the device name matches the provided hostname or linecard name,
it extracts the total count of VoQ and the max count of cores. The function also updates a dictionary with slot indices
and corresponding hostnames.
Args:
root: The root of the minigraph.xml.
hname (str): chassis hostname.
lcname (str): The linecard name or supervisor hostname.
Returns:
max_num_core (int): The maximum number of cores, only appliable for voq chassis
num_voq (int): The total count of VoQ per port, only appliable for voq chassis
chassis_linecards (dict): A dictionary of slot indices and corresponding LC hostnames.
"""
chassis_linecards = {}
max_num_core = None
num_voq = None
for child in root:
if child.tag == str(QName(ns, "MetadataDeclaration")):
devices = child.find(str(QName(ns, "Devices")))
for device_meta in devices.findall(str(QName(ns1, "DeviceMetadata"))):
slot_index = None
device_name = device_meta.find(str(QName(ns1, "Name"))).text
properties = device_meta.find(str(QName(ns1, "Properties")))
for device_property in properties.findall(str(QName(ns1, "DeviceProperty"))):
name = device_property.find(str(QName(ns1, "Name"))).text
value = device_property.find(str(QName(ns1, "Value"))).text
if device_name == hname or device_name == lcname:
if name == "TotalCountOfVoQ":
num_voq = value
if name == "MaxCountOfCores":
max_num_core = 64
if name == "SlotIndex":
slot_index = value
if slot_index is not None:
chassis_linecards.update({slot_index:{'hostname':device_name}})
return max_num_core, num_voq, chassis_linecards
def parse_chassis_deviceinfo_intf_metadata(device_info, chassis_linecards_info, chassis_hwsku, num_voq, chassis_type, chassis_intf_map, voq_intf_attributes):
"""
This function iterates InterfaceMetadata for every port in the chassis and genetate the configuration for
systemport, chassis port alias and port default speeds.d.
Args:
device_info: The XML element containing device info.
chassis_linecards_info (dict): A dictionary mapping slot indices to hostnames.
chassis_hwsku (str): The hardware SKU of the chassis.
num_voq (str): The number of VoQ.
chassis_type (str): The type of the chassis.
chassis_intf_map (dict): A dictionary mapping interface names to their properties.
voq_intf_attributes (dict): A dictionary mapping VoQ interface names to their properties.
Returns:
system_ports (dict): A dictionary of system ports, only for voq chassis
chassis_port_alias (dict): A dictionary of chassis port aliases.
port_default_speed (dict): A dictionary of port default speeds.
"""
system_ports = {}
chassis_port_alias = {}
port_default_speed = {}
system_port_id = 1
interface_metadata = device_info.find(str(QName(ns, "InterfaceMetadata")))
for interface in interface_metadata.findall(str(QName(ns1, "DeviceInterfaceMetadata"))):
linecard_name = None
asic_name = None
core_port_id = None
core_id = None
switch_id = None
slot_index = None
intf_name = interface.find(str(QName(ns1, "InterfaceName"))).text
# ignore the managment interfaces
if any(mgmt_intf in intf_name for mgmt_intf in ['Management', 'console']) == True:
continue
if intf_name not in chassis_intf_map:
print('Warning cannot find metadata for interface {}'.format(
intf_name), file=sys.stderr)
continue
intf_sonic_name = chassis_intf_map[intf_name].get('sonic_name', None)
if intf_sonic_name is None:
print('Warning cannot find sonic name for interface {}'.format(
intf_name), file=sys.stderr)
continue
intf_speed = chassis_intf_map[intf_name].get('speed', None)
if intf_speed is None:
print('Warning cannot find speed for interface' %
(intf_name), file=sys.stderr)
continue
intf_properties = interface.find(str(QName(ns1, "Properties")))
if intf_properties is None:
print('Warning cannot find interface porperties for interface' %
(intf_name), file=sys.stderr)
continue
for intf_property in intf_properties.findall(str(QName(ns1, "InterfaceProperty"))):
name = intf_property.find(str(QName(ns1, "Name"))).text
value = intf_property.find(str(QName(ns1, "Value"))).text
if name == "CoreId":
core_id = value
if name == "SlotIndex":
slot_index = value
if name == "ProviderChipName":
asic_name = value
if name == "LineCardSku":
lc_sku = value
if name == "AsicInterfaceIndex":
core_port_id = value
if name == "AsicSwitchId":
switch_id = value
if intf_sonic_name.startswith('cpu'):
core_id = 0
core_port_id = 0
speed = 10000
asic_id = intf_name.split('/')[1]
asic_name = 'ASIC{}'.format(asic_id)
if intf_sonic_name.startswith('Ethernet-IB'):
core_id = voq_intf_attributes.get('inb', {}).get('core_id', None)
core_port_id = voq_intf_attributes.get(
'inb', {}).get('core_port_index', None)
intf_speed = voq_intf_attributes.get('inb', {}).get('speed', None)
asic_id = intf_name.split('/')[1]
asic_name = 'ASIC{}'.format(asic_id)
if intf_sonic_name.startswith('Ethernet-Rec'):
# continue
core_id = voq_intf_attributes.get('rec', {}).get('core_id', None)
core_port_id = voq_intf_attributes.get(
'rec', {}).get('core_port_index', None)
intf_speed = voq_intf_attributes.get('rec', {}).get('speed', None)
asic_id = intf_name.split('/')[1]
asic_name = 'ASIC{}'.format(asic_id)
switch_id = get_asic_switch_id(slot_index, asic_name)
linecard_name = chassis_linecards_info.get(
slot_index, {}).get('hostname', None)
if linecard_name is None:
continue
if chassis_type == CHASSIS_CARD_VOQ:
key = intf_sonic_name
if asic_name is not None:
key = "%s|%s" % (asic_name, key)
if linecard_name is not None:
key = "%s|%s" % (linecard_name, key)
system_ports[key] = {
"system_port_id": 0,
"switch_id": switch_id,
"core_index": core_id,
"core_port_index": core_port_id,
"speed": intf_speed,
"num_voq": num_voq
}
chassis_port_alias.setdefault(slot_index, {}).update(
{(intf_sonic_name, intf_speed): intf_name})
# For Some Vendor we can have multiple speed define for same port with different alias.
# Example Port serving 400G alias will be FoutHundredGig0/0/0/0 and same port as 100G will be HundredGig0/0/0/0
# So to get port default speed get the max speed possible.
try:
if int(intf_speed) > int(port_default_speed[slot_index][intf_sonic_name]):
port_default_speed[slot_index][intf_sonic_name] = intf_speed
except:
port_default_speed.setdefault(slot_index, {}).update(
{intf_sonic_name: intf_speed})
# The above loop with findall("DeviceInterfaceMetadata") was not giving interfaces from minigraph
# in document order. So doing an explict sort so that system_port_ids remain same across LCs
sorted_system_ports = { key:system_ports[key] for key in sorted(system_ports.keys()) }
for k,v in sorted_system_ports.items():
v["system_port_id"] = system_port_id
system_port_id += 1
return sorted_system_ports, chassis_port_alias, port_default_speed
def parse_chassis_deviceinfo_voq_int_intfs(device_info):
backend_intf_map = {}
backend_interfaces = device_info.find(str(QName(ns, "BackendFabricInterfaces"))).findall(
str(QName(ns1, "BackendFabricInterface")))
voq_internal_intf_attr = {}
for backend_interface in backend_interfaces:
intf_name = backend_interface.find(str(QName(ns, "InterfaceName"))).text
if any(voq_intf in intf_name.lower() for voq_intf in voq_internal_intfs) == True:
sonic_name = backend_interface.find(str(QName(ns, "SonicName"))).text
speed = backend_interface.find(str(QName(ns, "Speed"))).text
backend_intf_map[intf_name] = {'sonic_name': sonic_name, 'speed': speed}
return backend_intf_map
def parse_chassis_deviceinfo_intfs(device_info):
interface_map = {}
interfaces = device_info.find(str(QName(ns, "EthernetInterfaces"))).findall(
str(QName(ns1, "EthernetInterface")))
for interface in interfaces:
# the interface name is at the chassis level, so the interface name will have
# the slot information. It will be of format
# Ethernet<slot_index>/port
intf_name = interface.find(str(QName(ns, "InterfaceName"))).text
sonic_name = interface.find(str(QName(ns, "SonicName"))).text
speed = interface.find(str(QName(ns, "Speed"))).text
interface_map[intf_name] = {'sonic_name': sonic_name, 'speed': speed}
return interface_map
def parse_chassis_deviceinfo(deviceinfos, chassis_linecards_info, chassis_hwsku, num_voq, chassis_type, voq_intf_attributes):
system_ports = {}
chassis_port_alias = {}
chassis_name = None
port_default_speed = {}
for device_info in deviceinfos.findall(str(QName(ns, "DeviceInfo"))):
dev_sku = device_info.find(str(QName(ns, "HwSku"))).text
if dev_sku == chassis_hwsku:
# The chassis device_info for sonic chassiss will 3 sections
# level information
# 1. EthernetInterfaces, which contains all the front panel ports present in the chassis
# 2. BackendFabricInterfaces, which contains all the internal/fabric ports present in the chassis
# this includes, cpu, Inband and recirc ports for all linecards
# 3. InterfaceMetadata which contains Metadata for the ports.
# In case of Voq chassis, the system port properties are presnent in this section
chassis_intf_map = parse_chassis_deviceinfo_intfs(device_info)
if chassis_type == CHASSIS_CARD_VOQ:
chassis_internal_intf_map = parse_chassis_deviceinfo_voq_int_intfs(
device_info)
chassis_intf_map.update(chassis_internal_intf_map)
system_ports, chassis_port_alias, port_default_speed = parse_chassis_deviceinfo_intf_metadata(
device_info, chassis_linecards_info, chassis_hwsku, num_voq, chassis_type, chassis_intf_map, voq_intf_attributes)
return system_ports, chassis_port_alias, port_default_speed
class minigraph_encoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, (
ipaddress.IPv4Network, ipaddress.IPv6Network,
ipaddress.IPv4Address, ipaddress.IPv6Address
)):
return str(obj)
return json.JSONEncoder.default(self, obj)
def exec_cmd(cmd):
p = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE)
outs, errs = p.communicate()
def get_peer_switch_info(link_metadata, devices):
peer_switch_table = {}
peer_switch_ip = None
mux_tunnel_name = None
for port, data in link_metadata.items():
if "PeerSwitch" in data:
peer_hostname = data["PeerSwitch"]
peer_lo_addr_str = devices[peer_hostname]["lo_addr"]
peer_lo_addr = ipaddress.ip_network(UNICODE_TYPE(peer_lo_addr_str)) if peer_lo_addr_str else None
peer_switch_table[peer_hostname] = {
'address_ipv4': str(peer_lo_addr.network_address) if peer_lo_addr else peer_lo_addr_str
}
mux_tunnel_name = port
peer_switch_ip = peer_switch_table[peer_hostname]['address_ipv4']
return peer_switch_table, mux_tunnel_name, peer_switch_ip
def parse_device(device):
lo_prefix = None
lo_prefix_v6 = None
mgmt_prefix = None
mgmt_prefix_v6 = None
d_type = None # don't shadow type()
hwsku = None
name = None
deployment_id = None
cluster = None
d_subtype = None
slice_type = None
for node in device:
if node.tag == str(QName(ns, "Address")):
lo_prefix = node.find(str(QName(ns2, "IPPrefix"))).text
elif node.tag == str(QName(ns, "AddressV6")):
lo_prefix_v6 = node.find(str(QName(ns2, "IPPrefix"))).text
elif node.tag == str(QName(ns, "ManagementAddress")):
mgmt_prefix = node.find(str(QName(ns2, "IPPrefix"))).text
elif node.tag == str(QName(ns, "ManagementAddressV6")):
mgmt_prefix_v6 = node.find(str(QName(ns2, "IPPrefix"))).text
elif node.tag == str(QName(ns, "Hostname")):
name = node.text
elif node.tag == str(QName(ns, "HwSku")):
hwsku = node.text
elif node.tag == str(QName(ns, "DeploymentId")):
deployment_id = node.text
elif node.tag == str(QName(ns, "ElementType")):
d_type = node.text
elif node.tag == str(QName(ns, "ClusterName")):
cluster = node.text
elif node.tag == str(QName(ns, "SubType")):
d_subtype = node.text
elif node.tag == str(QName(ns, "AssociatedSliceStr")) and node.text and "AZNG_Production" in node.text:
slice_type = "AZNG_Production"
if d_type is None and str(QName(ns3, "type")) in device.attrib:
d_type = device.attrib[str(QName(ns3, "type"))]
return (lo_prefix, lo_prefix_v6, mgmt_prefix, mgmt_prefix_v6, name, hwsku, d_type, deployment_id, cluster, d_subtype, slice_type)
def calculate_lcm_for_ecmp (nhdevices_bank_map, nhip_bank_map):
banks_enumerated = {}
lcm_array = []
for value in nhdevices_bank_map.values():
for key in nhip_bank_map.keys():
if nhip_bank_map[key] == value:
if value not in banks_enumerated:
banks_enumerated[value] = 1
else:
banks_enumerated[value] = banks_enumerated[value] + 1
for bank_enumeration in banks_enumerated.values():
lcm_list = range(1, bank_enumeration+1)
lcm_comp = lcm_list[0]
for i in lcm_list[1:]:
lcm_comp = lcm_comp * i / calculate_gcd(lcm_comp, i)
lcm_array.append(lcm_comp)
LCM = sum(lcm_array)
return int(LCM)
def calculate_gcd(x, y):
while y != 0:
(x, y) = (y, x % y)
return int(x)
def formulate_fine_grained_ecmp(version, dpg_ecmp_content, port_device_map, port_alias_map):
family = ""
tag = ""
neigh_key = []
if version == "ipv4":
family = "IPV4"
tag = "fgnhg_v4"
elif version == "ipv6":
family = "IPV6"
tag = "fgnhg_v6"
port_nhip_map = dpg_ecmp_content['port_nhip_map']
nhg_int = dpg_ecmp_content['nhg_int']
nhip_device_map = {port_nhip_map[x]: port_device_map[x] for x in port_device_map
if x in port_nhip_map}
nhip_devices = sorted(list(set(nhip_device_map.values())))
nhdevices_ip_bank_map = {device: bank for bank, device in enumerate(nhip_devices)}
nhip_bank_map = {ip: nhdevices_ip_bank_map[device] for ip, device in nhip_device_map.items()}
LCM = calculate_lcm_for_ecmp(nhdevices_ip_bank_map, nhip_bank_map)
FG_NHG_MEMBER = {ip: {"FG_NHG": tag, "bank": bank} for ip, bank in nhip_bank_map.items()}
nhip_port_map = dict(zip(port_nhip_map.values(), port_nhip_map.keys()))
for nhip, memberinfo in FG_NHG_MEMBER.items():
if nhip in nhip_port_map:
memberinfo["link"] = port_alias_map[nhip_port_map[nhip]]
FG_NHG_MEMBER[nhip] = memberinfo
FG_NHG = {tag: {"bucket_size": LCM, "match_mode": "nexthop-based"}}
for ip in nhip_bank_map:
neigh_key.append(str(nhg_int + "|" + ip))
NEIGH = {neigh_key: {"family": family} for neigh_key in neigh_key}
fine_grained_content = {"FG_NHG_MEMBER": FG_NHG_MEMBER, "FG_NHG": FG_NHG, "NEIGH": NEIGH}
return fine_grained_content
def parse_png(png, hname, dpg_ecmp_content = None):
neighbors = {}
devices = {}
console_dev = ''
console_port = ''
mgmt_dev = ''
mgmt_port = ''
port_speeds = {}
console_ports = {}
mux_cable_ports = {}
port_device_map = {}
png_ecmp_content = {}
FG_NHG_MEMBER = {}
FG_NHG = {}
NEIGH = {}
for child in png:
if child.tag == str(QName(ns, "DeviceInterfaceLinks")):
for link in child.findall(str(QName(ns, "DeviceLinkBase"))):
linktype = link.find(str(QName(ns, "ElementType"))).text
if linktype == "DeviceSerialLink":
enddevice = link.find(str(QName(ns, "EndDevice"))).text
endport = link.find(str(QName(ns, "EndPort"))).text
startdevice = link.find(str(QName(ns, "StartDevice"))).text
startport = link.find(str(QName(ns, "StartPort"))).text
baudrate = link.find(str(QName(ns, "Bandwidth"))).text
flowcontrol = 1 if link.find(str(QName(ns, "FlowControl"))) is not None and link.find(str(QName(ns, "FlowControl"))).text == 'true' else 0
if enddevice.lower() == hname.lower() and endport.isdigit():
console_ports[endport] = {
'remote_device': startdevice,
'baud_rate': baudrate,
'flow_control': flowcontrol
}
elif startport.isdigit():
console_ports[startport] = {
'remote_device': enddevice,
'baud_rate': baudrate,
'flow_control': flowcontrol
}
continue
if linktype == "DeviceInterfaceLink":
endport = link.find(str(QName(ns, "EndPort"))).text
startdevice = link.find(str(QName(ns, "StartDevice"))).text
port_device_map[endport] = startdevice
if linktype != "DeviceInterfaceLink" and linktype != "UnderlayInterfaceLink" and linktype != "DeviceMgmtLink":
continue
enddevice = link.find(str(QName(ns, "EndDevice"))).text
endport = link.find(str(QName(ns, "EndPort"))).text
startdevice = link.find(str(QName(ns, "StartDevice"))).text
startport = link.find(str(QName(ns, "StartPort"))).text
bandwidth_node = link.find(str(QName(ns, "Bandwidth")))
bandwidth = bandwidth_node.text if bandwidth_node is not None else None
if enddevice.lower() == hname.lower():
if endport in port_alias_map:
endport = port_alias_map[endport]
if linktype != "DeviceMgmtLink":
neighbors[endport] = {'name': startdevice, 'port': startport}
if bandwidth:
port_speeds[endport] = bandwidth
elif startdevice.lower() == hname.lower():
if startport in port_alias_map:
startport = port_alias_map[startport]
if linktype != "DeviceMgmtLink":
neighbors[startport] = {'name': enddevice, 'port': endport}
if bandwidth:
port_speeds[startport] = bandwidth
if child.tag == str(QName(ns, "Devices")):
for device in child.findall(str(QName(ns, "Device"))):
(lo_prefix, lo_prefix_v6, mgmt_prefix, mgmt_prefix_v6, name, hwsku, d_type, deployment_id, cluster, d_subtype, slice_type) = \
parse_device(device)
device_data = {}
if hwsku != None:
device_data['hwsku'] = hwsku
if cluster != None:
device_data['cluster'] = cluster
if deployment_id != None:
device_data['deployment_id'] = deployment_id
if lo_prefix != None:
device_data['lo_addr'] = lo_prefix
if lo_prefix_v6 != None:
device_data['lo_addr_v6'] = lo_prefix_v6
if mgmt_prefix != None:
device_data['mgmt_addr'] = mgmt_prefix
if mgmt_prefix_v6 != None:
device_data['mgmt_addr_v6'] = mgmt_prefix_v6
if d_type != None:
device_data['type'] = d_type
if d_subtype != None:
device_data['subtype'] = d_subtype
if slice_type != None:
device_data['slice_type'] = slice_type
devices[name] = device_data
if child.tag == str(QName(ns, "DeviceInterfaceLinks")):
for if_link in child.findall(str(QName(ns, 'DeviceLinkBase'))):
if str(QName(ns3, "type")) in if_link.attrib:
link_type = if_link.attrib[str(QName(ns3, "type"))]
if link_type == 'DeviceSerialLink':
for node in if_link:
if node.tag == str(QName(ns, "EndPort")):
console_port = node.text.split()[-1]
elif node.tag == str(QName(ns, "EndDevice")):
console_dev = node.text
elif link_type == 'DeviceMgmtLink':
for node in if_link:
if node.tag == str(QName(ns, "EndPort")):
mgmt_port = node.text.split()[-1]
elif node.tag == str(QName(ns, "EndDevice")):
mgmt_dev = node.text
if child.tag == str(QName(ns, "DeviceInterfaceLinks")):
for link in child.findall(str(QName(ns, 'DeviceLinkBase'))):
if link.find(str(QName(ns, "ElementType"))).text == "LogicalLink":
intf_name = link.find(str(QName(ns, "EndPort"))).text
start_device = link.find(str(QName(ns, "StartDevice"))).text
if intf_name in port_alias_map:
intf_name = port_alias_map[intf_name]
mux_cable_ports[intf_name] = start_device
if dpg_ecmp_content and (len(dpg_ecmp_content)):
for version, content in dpg_ecmp_content.items(): # version is ipv4 or ipv6
fine_grained_content = formulate_fine_grained_ecmp(version, content, port_device_map, port_alias_map) # port_alias_map
FG_NHG_MEMBER.update(fine_grained_content['FG_NHG_MEMBER'])
FG_NHG.update(fine_grained_content['FG_NHG'])
NEIGH.update(fine_grained_content['NEIGH'])
png_ecmp_content = {"FG_NHG_MEMBER": FG_NHG_MEMBER, "FG_NHG": FG_NHG, "NEIGH": NEIGH}
return (neighbors, devices, console_dev, console_port, mgmt_dev, mgmt_port, port_speeds, console_ports, mux_cable_ports, png_ecmp_content)
def parse_asic_external_link(link, asic_name, hostname):
neighbors = {}
port_speeds = {}
enddevice = link.find(str(QName(ns, "EndDevice"))).text
endport = link.find(str(QName(ns, "EndPort"))).text
startdevice = link.find(str(QName(ns, "StartDevice"))).text
startport = link.find(str(QName(ns, "StartPort"))).text
bandwidth_node = link.find(str(QName(ns, "Bandwidth")))
bandwidth = bandwidth_node.text if bandwidth_node is not None else None
# if chassis internal is false, the interface name will be
# interface alias which should be converted to asic port name
if (enddevice.lower() == hostname.lower()):
if endport in port_alias_asic_map:
endport = port_alias_asic_map[endport]
neighbors[port_alias_map[endport]] = {'name': startdevice, 'port': startport}
if bandwidth:
port_speeds[port_alias_map[endport]] = bandwidth
elif (startdevice.lower() == hostname.lower()):
if startport in port_alias_asic_map:
startport = port_alias_asic_map[startport]
neighbors[port_alias_map[startport]] = {'name': enddevice, 'port': endport}
if bandwidth:
port_speeds[port_alias_map[startport]] = bandwidth
return neighbors, port_speeds
def parse_asic_internal_link(link, asic_name, hostname):
neighbors = {}
port_speeds = {}
enddevice = link.find(str(QName(ns, "EndDevice"))).text
endport = link.find(str(QName(ns, "EndPort"))).text
startdevice = link.find(str(QName(ns, "StartDevice"))).text
startport = link.find(str(QName(ns, "StartPort"))).text
bandwidth_node = link.find(str(QName(ns, "Bandwidth")))
bandwidth = bandwidth_node.text if bandwidth_node is not None else None
if ((enddevice.lower() == asic_name.lower()) and
(startdevice.lower() != hostname.lower())):
if endport in port_alias_map:
endport = port_alias_map[endport]
neighbors[endport] = {'name': startdevice, 'port': startport}
if bandwidth:
port_speeds[endport] = bandwidth
elif ((startdevice.lower() == asic_name.lower()) and
(enddevice.lower() != hostname.lower())):
if startport in port_alias_map:
startport = port_alias_map[startport]
neighbors[startport] = {'name': enddevice, 'port': endport}
if bandwidth:
port_speeds[startport] = bandwidth
return neighbors, port_speeds
def parse_asic_png(png, asic_name, hostname):
neighbors = {}
devices = {}
port_speeds = {}
for child in png:
if child.tag == str(QName(ns, "DeviceInterfaceLinks")):
for link in child.findall(str(QName(ns, "DeviceLinkBase"))):
# Chassis internal node is used in multi-asic device or chassis minigraph
# where the minigraph will contain the internal asic connectivity and
# external neighbor information. The ChassisInternal node will be used to
# determine if the link is internal to the device or chassis.
chassis_internal_node = link.find(str(QName(ns, "ChassisInternal")))
chassis_internal = chassis_internal_node.text if chassis_internal_node is not None else "false"
# If the link is an external link include the external neighbor
# information in ASIC ports table
if chassis_internal.lower() == "false":
ext_neighbors, ext_port_speeds = parse_asic_external_link(link, asic_name, hostname)
neighbors.update(ext_neighbors)
port_speeds.update(ext_port_speeds)
else:
int_neighbors, int_port_speeds = parse_asic_internal_link(link, asic_name, hostname)
neighbors.update(int_neighbors)
port_speeds.update(int_port_speeds)
if child.tag == str(QName(ns, "Devices")):
for device in child.findall(str(QName(ns, "Device"))):
(lo_prefix, lo_prefix_v6, mgmt_prefix, mgmt_prefix_v6, name, hwsku, d_type, deployment_id, cluster, _, slice_type) = parse_device(device)
device_data = {}
if hwsku != None:
device_data['hwsku'] = hwsku
if cluster != None:
device_data['cluster'] = cluster
if deployment_id != None:
device_data['deployment_id'] = deployment_id
if lo_prefix != None:
device_data['lo_addr'] = lo_prefix
if lo_prefix_v6 != None:
device_data['lo_addr_v6'] = lo_prefix_v6
if mgmt_prefix != None:
device_data['mgmt_addr'] = mgmt_prefix
if mgmt_prefix_v6 != None:
device_data['mgmt_addr_v6'] = mgmt_prefix_v6
if d_type != None:
device_data['type'] = d_type
if slice_type != None:
device_data['slice_type'] = slice_type
devices[name] = device_data
return (neighbors, devices, port_speeds)
def parse_loopback_intf(child):
lointfs = child.find(str(QName(ns, "LoopbackIPInterfaces")))
lo_intfs = {}
for lointf in lointfs.findall(str(QName(ns1, "LoopbackIPInterface"))):
intfname = lointf.find(str(QName(ns, "AttachTo"))).text
ipprefix = lointf.find(str(QName(ns1, "PrefixStr"))).text
lo_intfs[(intfname, ipprefix)] = {}
return lo_intfs
def parse_dpg(dpg, hname):
aclintfs = {}
mgmtintfs = {}
subintfs = None
intfs= {}
lo_intfs= {}
mvrf= {}
mgmt_intf= {}
voq_inband_intfs= {}
vlans= {}
vlan_members= {}
dhcp_relay_table= {}
pcs= {}
pc_members= {}
acls= {}
acl_table_types = {}
vni= {}
dpg_ecmp_content= {}
static_routes= {}
tunnelintfs = defaultdict(dict)
tunnelintfs_qos_remap_config = defaultdict(dict)
for child in dpg:
"""
In Multi-NPU platforms the acl intfs are defined only for the host not for individual asic.
There is just one aclintf node in the minigraph
Get the aclintfs node first.
"""
if not aclintfs and child.find(str(QName(ns, "AclInterfaces"))) is not None and child.find(str(QName(ns, "AclInterfaces"))).findall(str(QName(ns, "AclInterface"))):
aclintfs = child.find(str(QName(ns, "AclInterfaces"))).findall(str(QName(ns, "AclInterface")))
"""
In Multi-NPU platforms the mgmt intfs are defined only for the host not for individual asic
There is just one mgmtintf node in the minigraph
Get the mgmtintfs node first. We need mgmt intf to get mgmt ip in per asic dockers.
"""
if not mgmtintfs and child.find(str(QName(ns, "ManagementIPInterfaces"))) is not None and child.find(str(QName(ns, "ManagementIPInterfaces"))).findall(str(QName(ns1, "ManagementIPInterface"))):
mgmtintfs = child.find(str(QName(ns, "ManagementIPInterfaces"))).findall(str(QName(ns1, "ManagementIPInterface")))
hostname = child.find(str(QName(ns, "Hostname")))
if hostname.text.lower() != hname.lower():
continue
vni = vni_default
vni_element = child.find(str(QName(ns, "VNI")))
if vni_element != None:
if vni_element.text.isdigit():
vni = int(vni_element.text)
else:
print("VNI must be an integer (use default VNI %d instead)" % vni_default, file=sys.stderr)
ipintfs = child.find(str(QName(ns, "IPInterfaces")))
intfs = {}
ip_intfs_map = {}
for ipintf in ipintfs.findall(str(QName(ns, "IPInterface"))):
ipprefix = ipintf.find(str(QName(ns, "Prefix"))).text
ipintf_name = ipintf.find(str(QName(ns, "Name"))).text
intfalias = ipintf.find(str(QName(ns, "AttachTo"))).text
"""
VoqInband interfaces are special ip interfaces needed on inter linecard
control plane communications on Voq Chassis
"""
if ipintf_name in ["v6VoqInband", "VoqInband"]:
if intfalias.startswith("Ethernet"):
voq_intf_type = "Port"
# Vlan interface is not used, adding to be future proof
elif intfalias.startswith("Vlan"):
voq_intf_type = "Vlan"
if intfalias not in voq_inband_intfs:
voq_inband_intfs[intfalias] = {'inband_type': voq_intf_type}
voq_inband_intfs["%s|%s" % (intfalias, ipprefix)] = {}
continue
intfname = port_alias_map.get(intfalias, intfalias)
intfs[(intfname, ipprefix)] = {}
ip_intfs_map[ipprefix] = intfalias
lo_intfs = parse_loopback_intf(child)
subintfs = child.find(str(QName(ns, "SubInterfaces")))
if subintfs is not None:
for subintf in subintfs.findall(str(QName(ns, "SubInterface"))):
intfalias = subintf.find(str(QName(ns, "AttachTo"))).text
intfname = port_alias_map.get(intfalias, intfalias)
ipprefix = subintf.find(str(QName(ns, "Prefix"))).text
subintfvlan = subintf.find(str(QName(ns, "Vlan"))).text
subintfname = intfname + VLAN_SUB_INTERFACE_SEPARATOR + subintfvlan
intfs[(subintfname, ipprefix)] = {}
mvrfConfigs = child.find(str(QName(ns, "MgmtVrfConfigs")))
mvrf = {}
if mvrfConfigs != None:
mv = mvrfConfigs.find(str(QName(ns1, "MgmtVrfGlobal")))
if mv != None:
mvrf_en_flag = mv.find(str(QName(ns, "mgmtVrfEnabled"))).text
mvrf["vrf_global"] = {"mgmtVrfEnabled": mvrf_en_flag}
mgmt_intf = {}
for mgmtintf in mgmtintfs:
intfname = mgmtintf.find(str(QName(ns, "AttachTo"))).text
ipprefix = mgmtintf.find(str(QName(ns1, "PrefixStr"))).text
mgmtipn = ipaddress.ip_network(UNICODE_TYPE(ipprefix), False)
gwaddr = ipaddress.ip_address(next(mgmtipn.hosts()))
mgmt_intf[(intfname, ipprefix)] = {'gwaddr': gwaddr}
voqinbandintfs = child.find(str(QName(ns, "VoqInbandInterfaces")))
if voqinbandintfs:
for voqintf in voqinbandintfs.findall(str(QName(ns1, "VoqInbandInterface"))):
intfname = voqintf.find(str(QName(ns, "Name"))).text
intftype = voqintf.find(str(QName(ns, "Type"))).text
ipprefix = voqintf.find(str(QName(ns1, "PrefixStr"))).text
if intfname not in voq_inband_intfs:
voq_inband_intfs[intfname] = {'inband_type': intftype}
voq_inband_intfs["%s|%s" % (intfname, ipprefix)] = {}
pcintfs = child.find(str(QName(ns, "PortChannelInterfaces")))
pc_intfs = []
pcs = {}
pc_members = {}
intfs_inpc = [] # List to hold all the LAG member interfaces
for pcintf in pcintfs.findall(str(QName(ns, "PortChannel"))):
pcintfname = pcintf.find(str(QName(ns, "Name"))).text
pcintfmbr = pcintf.find(str(QName(ns, "AttachTo"))).text
pcmbr_list = pcintfmbr.split(';')
pc_intfs.append(pcintfname)
for i, member in enumerate(pcmbr_list):
pcmbr_list[i] = port_alias_map.get(member, member)
intfs_inpc.append(pcmbr_list[i])
pc_members[(pcintfname, pcmbr_list[i])] = {}
if pcintf.find(str(QName(ns, "Fallback"))) != None:
pcs[pcintfname] = {'fallback': pcintf.find(str(QName(ns, "Fallback"))).text, 'min_links': str(int(math.ceil(len() * 0.75))), 'lacp_key': 'auto'}
else:
pcs[pcintfname] = {'min_links': str(int(math.ceil(len(pcmbr_list) * 0.75))), 'lacp_key': 'auto' }
port_nhipv4_map = {}
port_nhipv6_map = {}
nhg_int = ""
nhportlist = []
dpg_ecmp_content = {}
static_routes = {}
ipnhs = child.find(str(QName(ns, "IPNextHops")))
if ipnhs is not None:
for ipnh in ipnhs.findall(str(QName(ns, "IPNextHop"))):
if ipnh.find(str(QName(ns, "Type"))).text == 'FineGrainedECMPGroupMember':
ipnhfmbr = ipnh.find(str(QName(ns, "AttachTo"))).text
ipnhaddr = ipnh.find(str(QName(ns, "Address"))).text
nhportlist.append(ipnhfmbr)
if "." in ipnhaddr:
port_nhipv4_map[ipnhfmbr] = ipnhaddr
elif ":" in ipnhaddr:
port_nhipv6_map[ipnhfmbr] = ipnhaddr
elif ipnh.find(str(QName(ns, "Type"))).text == 'StaticRoute':
prefix = ipnh.find(str(QName(ns, "Address"))).text
ifname = []
nexthop = []
for nexthop_tuple in ipnh.find(str(QName(ns, "AttachTo"))).text.split(";"):
ifname.append(nexthop_tuple.split(",")[0])
nexthop.append(nexthop_tuple.split(",")[1])
if ipnh.find(str(QName(ns, "Advertise"))):
advertise = ipnh.find(str(QName(ns, "Advertise"))).text
else:
advertise = "false"
if '/' not in prefix: