forked from sonic-net/sonic-utilities
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
executable file
·3191 lines (2616 loc) · 101 KB
/
Copy pathmain.py
File metadata and controls
executable file
·3191 lines (2616 loc) · 101 KB
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
#! /usr/bin/python -u
import json
import netaddr
import netifaces
import os
import re
import subprocess
import sys
import ipaddress
from pkg_resources import parse_version
import click
from click_default_group import DefaultGroup
from natsort import natsorted
from tabulate import tabulate
import sonic_device_util
from swsssdk import ConfigDBConnector
from swsssdk import SonicV2Connector
import mlnx
SONIC_CFGGEN_PATH = '/usr/local/bin/sonic-cfggen'
VLAN_SUB_INTERFACE_SEPARATOR = '.'
try:
# noinspection PyPep8Naming
import ConfigParser as configparser
except ImportError:
# noinspection PyUnresolvedReferences
import configparser
# This is from the aliases example:
# https://github.com/pallets/click/blob/57c6f09611fc47ca80db0bd010f05998b3c0aa95/examples/aliases/aliases.py
class Config(object):
"""Object to hold CLI config"""
def __init__(self):
self.path = os.getcwd()
self.aliases = {}
def read_config(self, filename):
parser = configparser.RawConfigParser()
parser.read([filename])
try:
self.aliases.update(parser.items('aliases'))
except configparser.NoSectionError:
pass
class InterfaceAliasConverter(object):
"""Class which handles conversion between interface name and alias"""
def __init__(self):
self.alias_max_length = 0
config_db = ConfigDBConnector()
config_db.connect()
self.port_dict = config_db.get_table('PORT')
if not self.port_dict:
click.echo(message="Warning: failed to retrieve PORT table from ConfigDB!", err=True)
self.port_dict = {}
for port_name in self.port_dict.keys():
try:
if self.alias_max_length < len(
self.port_dict[port_name]['alias']):
self.alias_max_length = len(
self.port_dict[port_name]['alias'])
except KeyError:
break
def name_to_alias(self, interface_name):
"""Return vendor interface alias if SONiC
interface name is given as argument
"""
vlan_id = ''
sub_intf_sep_idx = -1
if interface_name is not None:
sub_intf_sep_idx = interface_name.find(VLAN_SUB_INTERFACE_SEPARATOR)
if sub_intf_sep_idx != -1:
vlan_id = interface_name[sub_intf_sep_idx + 1:]
# interface_name holds the parent port name
interface_name = interface_name[:sub_intf_sep_idx]
for port_name in self.port_dict.keys():
if interface_name == port_name:
return self.port_dict[port_name]['alias'] if sub_intf_sep_idx == -1 \
else self.port_dict[port_name]['alias'] + VLAN_SUB_INTERFACE_SEPARATOR + vlan_id
# interface_name not in port_dict. Just return interface_name
return interface_name if sub_intf_sep_idx == -1 else interface_name + VLAN_SUB_INTERFACE_SEPARATOR + vlan_id
def alias_to_name(self, interface_alias):
"""Return SONiC interface name if vendor
port alias is given as argument
"""
vlan_id = ''
sub_intf_sep_idx = -1
if interface_alias is not None:
sub_intf_sep_idx = interface_alias.find(VLAN_SUB_INTERFACE_SEPARATOR)
if sub_intf_sep_idx != -1:
vlan_id = interface_alias[sub_intf_sep_idx + 1:]
# interface_alias holds the parent port alias
interface_alias = interface_alias[:sub_intf_sep_idx]
for port_name in self.port_dict.keys():
if interface_alias == self.port_dict[port_name]['alias']:
return port_name if sub_intf_sep_idx == -1 else port_name + VLAN_SUB_INTERFACE_SEPARATOR + vlan_id
# interface_alias not in port_dict. Just return interface_alias
return interface_alias if sub_intf_sep_idx == -1 else interface_alias + VLAN_SUB_INTERFACE_SEPARATOR + vlan_id
# Global Config object
_config = None
# This aliased group has been modified from click examples to inherit from DefaultGroup instead of click.Group.
# DefaultGroup is a superclass of click.Group which calls a default subcommand instead of showing
# a help message if no subcommand is passed
class AliasedGroup(DefaultGroup):
"""This subclass of a DefaultGroup supports looking up aliases in a config
file and with a bit of magic.
"""
def get_command(self, ctx, cmd_name):
global _config
# If we haven't instantiated our global config, do it now and load current config
if _config is None:
_config = Config()
# Load our config file
cfg_file = os.path.join(os.path.dirname(__file__), 'aliases.ini')
_config.read_config(cfg_file)
# Try to get builtin commands as normal
rv = click.Group.get_command(self, ctx, cmd_name)
if rv is not None:
return rv
# No builtin found. Look up an explicit command alias in the config
if cmd_name in _config.aliases:
actual_cmd = _config.aliases[cmd_name]
return click.Group.get_command(self, ctx, actual_cmd)
# Alternative option: if we did not find an explicit alias we
# allow automatic abbreviation of the command. "status" for
# instance will match "st". We only allow that however if
# there is only one command.
matches = [x for x in self.list_commands(ctx)
if x.lower().startswith(cmd_name.lower())]
if not matches:
# No command name matched. Issue Default command.
ctx.arg0 = cmd_name
cmd_name = self.default_cmd_name
return DefaultGroup.get_command(self, ctx, cmd_name)
elif len(matches) == 1:
return DefaultGroup.get_command(self, ctx, matches[0])
ctx.fail('Too many matches: %s' % ', '.join(sorted(matches)))
# To be enhanced. Routing-stack information should be collected from a global
# location (configdb?), so that we prevent the continous execution of this
# bash oneliner. To be revisited once routing-stack info is tracked somewhere.
def get_routing_stack():
command = "sudo docker ps | grep bgp | awk '{print$2}' | cut -d'-' -f3 | cut -d':' -f1"
try:
proc = subprocess.Popen(command,
stdout=subprocess.PIPE,
shell=True,
stderr=subprocess.STDOUT)
stdout = proc.communicate()[0]
proc.wait()
result = stdout.rstrip('\n')
except OSError as e:
raise OSError("Cannot detect routing-stack")
return (result)
# Global Routing-Stack variable
routing_stack = get_routing_stack()
def run_command(command, display_cmd=False, return_cmd=False):
if display_cmd:
click.echo(click.style("Command: ", fg='cyan') + click.style(command, fg='green'))
# No conversion needed for intfutil commands as it already displays
# both SONiC interface name and alias name for all interfaces.
if get_interface_mode() == "alias" and not command.startswith("intfutil"):
run_command_in_alias_mode(command)
raise sys.exit(0)
proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
while True:
if return_cmd:
output = proc.communicate()[0].decode("utf-8")
return output
output = proc.stdout.readline()
if output == "" and proc.poll() is not None:
break
if output:
click.echo(output.rstrip('\n'))
rc = proc.poll()
if rc != 0:
sys.exit(rc)
def get_interface_mode():
mode = os.getenv('SONIC_CLI_IFACE_MODE')
if mode is None:
mode = "default"
return mode
def is_ip_prefix_in_key(key):
'''
Function to check if IP address is present in the key. If it
is present, then the key would be a tuple or else, it shall be
be string
'''
return (isinstance(key, tuple))
# Global class instance for SONiC interface name to alias conversion
iface_alias_converter = InterfaceAliasConverter()
def print_output_in_alias_mode(output, index):
"""Convert and print all instances of SONiC interface
name to vendor-sepecific interface aliases.
"""
alias_name = ""
interface_name = ""
# Adjust tabulation width to length of alias name
if output.startswith("---"):
word = output.split()
dword = word[index]
underline = dword.rjust(iface_alias_converter.alias_max_length,
'-')
word[index] = underline
output = ' ' .join(word)
# Replace SONiC interface name with vendor alias
word = output.split()
if word:
interface_name = word[index]
interface_name = interface_name.replace(':', '')
for port_name in natsorted(iface_alias_converter.port_dict.keys()):
if interface_name == port_name:
alias_name = iface_alias_converter.port_dict[port_name]['alias']
if alias_name:
if len(alias_name) < iface_alias_converter.alias_max_length:
alias_name = alias_name.rjust(
iface_alias_converter.alias_max_length)
output = output.replace(interface_name, alias_name, 1)
click.echo(output.rstrip('\n'))
def run_command_in_alias_mode(command):
"""Run command and replace all instances of SONiC interface names
in output with vendor-sepecific interface aliases.
"""
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
while True:
output = process.stdout.readline()
if output == '' and process.poll() is not None:
break
if output:
index = 1
raw_output = output
output = output.lstrip()
if command.startswith("portstat"):
"""Show interface counters"""
index = 0
if output.startswith("IFACE"):
output = output.replace("IFACE", "IFACE".rjust(
iface_alias_converter.alias_max_length))
print_output_in_alias_mode(output, index)
elif command.startswith("intfstat"):
"""Show RIF counters"""
index = 0
if output.startswith("IFACE"):
output = output.replace("IFACE", "IFACE".rjust(
iface_alias_converter.alias_max_length))
print_output_in_alias_mode(output, index)
elif command == "pfcstat":
"""Show pfc counters"""
index = 0
if output.startswith("Port Tx"):
output = output.replace("Port Tx", "Port Tx".rjust(
iface_alias_converter.alias_max_length))
elif output.startswith("Port Rx"):
output = output.replace("Port Rx", "Port Rx".rjust(
iface_alias_converter.alias_max_length))
print_output_in_alias_mode(output, index)
elif (command.startswith("sudo sfputil show eeprom")):
"""show interface transceiver eeprom"""
index = 0
print_output_in_alias_mode(raw_output, index)
elif (command.startswith("sudo sfputil show")):
"""show interface transceiver lpmode,
presence
"""
index = 0
if output.startswith("Port"):
output = output.replace("Port", "Port".rjust(
iface_alias_converter.alias_max_length))
print_output_in_alias_mode(output, index)
elif command == "sudo lldpshow":
"""show lldp table"""
index = 0
if output.startswith("LocalPort"):
output = output.replace("LocalPort", "LocalPort".rjust(
iface_alias_converter.alias_max_length))
print_output_in_alias_mode(output, index)
elif command.startswith("queuestat"):
"""show queue counters"""
index = 0
if output.startswith("Port"):
output = output.replace("Port", "Port".rjust(
iface_alias_converter.alias_max_length))
print_output_in_alias_mode(output, index)
elif command == "fdbshow":
"""show mac"""
index = 3
if output.startswith("No."):
output = " " + output
output = re.sub(
'Type', ' Type', output)
elif output[0].isdigit():
output = " " + output
print_output_in_alias_mode(output, index)
elif command.startswith("nbrshow"):
"""show arp"""
index = 2
if "Vlan" in output:
output = output.replace('Vlan', ' Vlan')
print_output_in_alias_mode(output, index)
elif command.startswith("sudo teamshow"):
"""
sudo teamshow
Search for port names either at the start of a line or preceded immediately by
whitespace and followed immediately by either the end of a line or whitespace
OR followed immediately by '(D)', '(S)', '(D*)' or '(S*)'
"""
converted_output = raw_output
for port_name in iface_alias_converter.port_dict.keys():
converted_output = re.sub(r"(^|\s){}(\([DS]\*{{0,1}}\)(?:$|\s))".format(port_name),
r"\1{}\2".format(iface_alias_converter.name_to_alias(port_name)),
converted_output)
click.echo(converted_output.rstrip('\n'))
else:
"""
Default command conversion
Search for port names either at the start of a line or preceded immediately by
whitespace and followed immediately by either the end of a line or whitespace
or a comma followed by whitespace
"""
converted_output = raw_output
for port_name in iface_alias_converter.port_dict.keys():
converted_output = re.sub(r"(^|\s){}($|,{{0,1}}\s)".format(port_name),
r"\1{}\2".format(iface_alias_converter.name_to_alias(port_name)),
converted_output)
click.echo(converted_output.rstrip('\n'))
rc = process.poll()
if rc != 0:
sys.exit(rc)
def get_bgp_summary_extended(command_output):
"""
Adds Neighbor name to the show ip[v6] bgp summary command
:param command: command to get bgp summary
"""
static_neighbors, dynamic_neighbors = get_bgp_neighbors_dict()
modified_output = []
my_list = iter(command_output.splitlines())
for element in my_list:
if element.startswith("Neighbor"):
element = "{}\tNeighborName".format(element)
modified_output.append(element)
elif not element or element.startswith("Total number "):
modified_output.append(element)
elif re.match(r"(\*?([0-9A-Fa-f]{1,4}:|\d+.\d+.\d+.\d+))", element.split()[0]):
first_element = element.split()[0]
ip = first_element[1:] if first_element.startswith("*") else first_element
name = get_bgp_neighbor_ip_to_name(ip, static_neighbors, dynamic_neighbors)
if len(element.split()) == 1:
modified_output.append(element)
element = next(my_list)
element = "{}\t{}".format(element, name)
modified_output.append(element)
else:
modified_output.append(element)
click.echo("\n".join(modified_output))
def connect_config_db():
"""
Connects to config_db
"""
config_db = ConfigDBConnector()
config_db.connect()
return config_db
def get_neighbor_dict_from_table(db,table_name):
"""
returns a dict with bgp neighbor ip as key and neighbor name as value
:param table_name: config db table name
:param db: config_db
"""
neighbor_dict = {}
neighbor_data = db.get_table(table_name)
try:
for entry in neighbor_data.keys():
neighbor_dict[entry] = neighbor_data[entry].get(
'name') if 'name' in neighbor_data[entry].keys() else 'NotAvailable'
return neighbor_dict
except Exception:
return neighbor_dict
def is_ipv4_address(ipaddress):
"""
Checks if given ip is ipv4
:param ipaddress: unicode ipv4
:return: bool
"""
try:
ipaddress.IPv4Address(ipaddress)
return True
except ipaddress.AddressValueError as err:
return False
def is_ipv6_address(ipaddress):
"""
Checks if given ip is ipv6
:param ipaddress: unicode ipv6
:return: bool
"""
try:
ipaddress.IPv6Address(ipaddress)
return True
except ipaddress.AddressValueError as err:
return False
def get_dynamic_neighbor_subnet(db):
"""
Returns dict of description and subnet info from bgp_peer_range table
:param db: config_db
"""
dynamic_neighbor = {}
v4_subnet = {}
v6_subnet = {}
neighbor_data = db.get_table('BGP_PEER_RANGE')
try:
for entry in neighbor_data.keys():
new_key = neighbor_data[entry]['ip_range'][0]
new_value = neighbor_data[entry]['name']
if is_ipv4_address(unicode(neighbor_data[entry]['src_address'])):
v4_subnet[new_key] = new_value
elif is_ipv6_address(unicode(neighbor_data[entry]['src_address'])):
v6_subnet[new_key] = new_value
dynamic_neighbor["v4"] = v4_subnet
dynamic_neighbor["v6"] = v6_subnet
return dynamic_neighbor
except Exception:
return neighbor_data
def get_bgp_neighbors_dict():
"""
Uses config_db to get the bgp neighbors and names in dictionary format
:return:
"""
dynamic_neighbors = {}
config_db = connect_config_db()
static_neighbors = get_neighbor_dict_from_table(config_db, 'BGP_NEIGHBOR')
bgp_monitors = get_neighbor_dict_from_table(config_db, 'BGP_MONITORS')
static_neighbors.update(bgp_monitors)
dynamic_neighbors = get_dynamic_neighbor_subnet(config_db)
return static_neighbors, dynamic_neighbors
def get_bgp_neighbor_ip_to_name(ip, static_neighbors, dynamic_neighbors):
"""
return neighbor name for the ip provided
:param ip: ip address unicode
:param static_neighbors: statically defined bgp neighbors dict
:param dynamic_neighbors: subnet of dynamically defined neighbors dict
:return: name of neighbor
"""
if ip in static_neighbors.keys():
return static_neighbors[ip]
elif is_ipv4_address(unicode(ip)):
for subnet in dynamic_neighbors["v4"].keys():
if ipaddress.IPv4Address(unicode(ip)) in ipaddress.IPv4Network(unicode(subnet)):
return dynamic_neighbors["v4"][subnet]
elif is_ipv6_address(unicode(ip)):
for subnet in dynamic_neighbors["v6"].keys():
if ipaddress.IPv6Address(unicode(ip)) in ipaddress.IPv6Network(unicode(subnet)):
return dynamic_neighbors["v6"][subnet]
else:
return "NotAvailable"
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help', '-?'])
#
# 'cli' group (root group)
#
# This is our entrypoint - the main "show" command
# TODO: Consider changing function name to 'show' for better understandability
@click.group(cls=AliasedGroup, context_settings=CONTEXT_SETTINGS)
def cli():
"""SONiC command line - 'show' command"""
pass
#
# 'vrf' command ("show vrf")
#
def get_interface_bind_to_vrf(config_db, vrf_name):
"""Get interfaces belong to vrf
"""
tables = ['INTERFACE', 'PORTCHANNEL_INTERFACE', 'VLAN_INTERFACE', 'LOOPBACK_INTERFACE']
data = []
for table_name in tables:
interface_dict = config_db.get_table(table_name)
if interface_dict:
for interface in interface_dict.keys():
if interface_dict[interface].has_key('vrf_name') and vrf_name == interface_dict[interface]['vrf_name']:
data.append(interface)
return data
@cli.command()
@click.argument('vrf_name', required=False)
def vrf(vrf_name):
"""Show vrf config"""
config_db = ConfigDBConnector()
config_db.connect()
header = ['VRF', 'Interfaces']
body = []
vrf_dict = config_db.get_table('VRF')
if vrf_dict:
vrfs = []
if vrf_name is None:
vrfs = vrf_dict.keys()
elif vrf_name in vrf_dict.keys():
vrfs = [vrf_name]
for vrf in vrfs:
intfs = get_interface_bind_to_vrf(config_db, vrf)
if len(intfs) == 0:
body.append([vrf, ""])
else:
body.append([vrf, intfs[0]])
for intf in intfs[1:]:
body.append(["", intf])
click.echo(tabulate(body, header))
#
# 'arp' command ("show arp")
#
@cli.command()
@click.argument('ipaddress', required=False)
@click.option('-if', '--iface')
@click.option('--verbose', is_flag=True, help="Enable verbose output")
def arp(ipaddress, iface, verbose):
"""Show IP ARP table"""
cmd = "nbrshow -4"
if ipaddress is not None:
cmd += " -ip {}".format(ipaddress)
if iface is not None:
if get_interface_mode() == "alias":
if not ((iface.startswith("PortChannel")) or
(iface.startswith("eth"))):
iface = iface_alias_converter.alias_to_name(iface)
cmd += " -if {}".format(iface)
run_command(cmd, display_cmd=verbose)
#
# 'ndp' command ("show ndp")
#
@cli.command()
@click.argument('ip6address', required=False)
@click.option('-if', '--iface')
@click.option('--verbose', is_flag=True, help="Enable verbose output")
def ndp(ip6address, iface, verbose):
"""Show IPv6 Neighbour table"""
cmd = "nbrshow -6"
if ip6address is not None:
cmd += " -ip {}".format(ip6address)
if iface is not None:
cmd += " -if {}".format(iface)
run_command(cmd, display_cmd=verbose)
def is_mgmt_vrf_enabled(ctx):
"""Check if management VRF is enabled"""
if ctx.invoked_subcommand is None:
cmd = 'sonic-cfggen -d --var-json "MGMT_VRF_CONFIG"'
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout = p.communicate()[0]
if p.returncode == 0:
mvrf_dict = json.loads(stdout)
# if the mgmtVrfEnabled attribute is configured, check the value
# and return True accordingly.
if 'mgmtVrfEnabled' in mvrf_dict['vrf_global']:
if (mvrf_dict['vrf_global']['mgmtVrfEnabled'] == "true"):
#ManagementVRF is enabled. Return True.
return True
return False
#
# 'mgmt-vrf' group ("show mgmt-vrf ...")
#
@cli.group('mgmt-vrf', invoke_without_command=True)
@click.argument('routes', required=False)
@click.pass_context
def mgmt_vrf(ctx,routes):
"""Show management VRF attributes"""
if is_mgmt_vrf_enabled(ctx) is False:
click.echo("\nManagementVRF : Disabled")
return
else:
if routes is None:
click.echo("\nManagementVRF : Enabled")
click.echo("\nManagement VRF interfaces in Linux:")
cmd = "ip -d link show mgmt"
run_command(cmd)
cmd = "ip link show vrf mgmt"
run_command(cmd)
else:
click.echo("\nRoutes in Management VRF Routing Table:")
cmd = "ip route show table 5000"
run_command(cmd)
#
# 'management_interface' group ("show management_interface ...")
#
@cli.group(name='management_interface', cls=AliasedGroup, default_if_no_args=False)
def management_interface():
"""Show management interface parameters"""
pass
# 'address' subcommand ("show management_interface address")
@management_interface.command()
def address ():
"""Show IP address configured for management interface"""
config_db = ConfigDBConnector()
config_db.connect()
# Fetching data from config_db for MGMT_INTERFACE
mgmt_ip_data = config_db.get_table('MGMT_INTERFACE')
for key in natsorted(mgmt_ip_data.keys()):
click.echo("Management IP address = {0}".format(key[1]))
click.echo("Management Network Default Gateway = {0}".format(mgmt_ip_data[key]['gwaddr']))
#
# 'snmpagentaddress' group ("show snmpagentaddress ...")
#
@cli.group('snmpagentaddress', invoke_without_command=True)
@click.pass_context
def snmpagentaddress (ctx):
"""Show SNMP agent listening IP address configuration"""
config_db = ConfigDBConnector()
config_db.connect()
agenttable = config_db.get_table('SNMP_AGENT_ADDRESS_CONFIG')
header = ['ListenIP', 'ListenPort', 'ListenVrf']
body = []
for agent in agenttable.keys():
body.append([agent[0], agent[1], agent[2]])
click.echo(tabulate(body, header))
#
# 'snmptrap' group ("show snmptrap ...")
#
@cli.group('snmptrap', invoke_without_command=True)
@click.pass_context
def snmptrap (ctx):
"""Show SNMP agent Trap server configuration"""
config_db = ConfigDBConnector()
config_db.connect()
traptable = config_db.get_table('SNMP_TRAP_CONFIG')
header = ['Version', 'TrapReceiverIP', 'Port', 'VRF', 'Community']
body = []
for row in traptable.keys():
if row == "v1TrapDest":
ver=1
elif row == "v2TrapDest":
ver=2
else:
ver=3
body.append([ver, traptable[row]['DestIp'], traptable[row]['DestPort'], traptable[row]['vrf'], traptable[row]['Community']])
click.echo(tabulate(body, header))
#
# 'interfaces' group ("show interfaces ...")
#
@cli.group(cls=AliasedGroup, default_if_no_args=False)
def interfaces():
"""Show details of the network interfaces"""
pass
# 'alias' subcommand ("show interfaces alias")
@interfaces.command()
@click.argument('interfacename', required=False)
def alias(interfacename):
"""Show Interface Name/Alias Mapping"""
cmd = 'sonic-cfggen -d --var-json "PORT"'
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
port_dict = json.loads(p.stdout.read())
header = ['Name', 'Alias']
body = []
if interfacename is not None:
if get_interface_mode() == "alias":
interfacename = iface_alias_converter.alias_to_name(interfacename)
# If we're given an interface name, output name and alias for that interface only
if interfacename in port_dict:
if 'alias' in port_dict[interfacename]:
body.append([interfacename, port_dict[interfacename]['alias']])
else:
body.append([interfacename, interfacename])
else:
click.echo("Invalid interface name, '{0}'".format(interfacename))
return
else:
# Output name and alias for all interfaces
for port_name in natsorted(port_dict.keys()):
if 'alias' in port_dict[port_name]:
body.append([port_name, port_dict[port_name]['alias']])
else:
body.append([port_name, port_name])
click.echo(tabulate(body, header))
#
# 'neighbor' group ###
#
@interfaces.group(cls=AliasedGroup, default_if_no_args=False)
def neighbor():
"""Show neighbor related information"""
pass
# 'expected' subcommand ("show interface neighbor expected")
@neighbor.command()
@click.argument('interfacename', required=False)
def expected(interfacename):
"""Show expected neighbor information by interfaces"""
neighbor_cmd = 'sonic-cfggen -d --var-json "DEVICE_NEIGHBOR"'
p1 = subprocess.Popen(neighbor_cmd, shell=True, stdout=subprocess.PIPE)
try :
neighbor_dict = json.loads(p1.stdout.read())
except ValueError:
print("DEVICE_NEIGHBOR information is not present.")
return
neighbor_metadata_cmd = 'sonic-cfggen -d --var-json "DEVICE_NEIGHBOR_METADATA"'
p2 = subprocess.Popen(neighbor_metadata_cmd, shell=True, stdout=subprocess.PIPE)
try :
neighbor_metadata_dict = json.loads(p2.stdout.read())
except ValueError:
print("DEVICE_NEIGHBOR_METADATA information is not present.")
return
#Swap Key and Value from interface: name to name: interface
device2interface_dict = {}
for port in natsorted(neighbor_dict['DEVICE_NEIGHBOR'].keys()):
temp_port = port
if get_interface_mode() == "alias":
port = iface_alias_converter.name_to_alias(port)
neighbor_dict['DEVICE_NEIGHBOR'][port] = neighbor_dict['DEVICE_NEIGHBOR'].pop(temp_port)
device2interface_dict[neighbor_dict['DEVICE_NEIGHBOR'][port]['name']] = {'localPort': port, 'neighborPort': neighbor_dict['DEVICE_NEIGHBOR'][port]['port']}
header = ['LocalPort', 'Neighbor', 'NeighborPort', 'NeighborLoopback', 'NeighborMgmt', 'NeighborType']
body = []
if interfacename:
for device in natsorted(neighbor_metadata_dict['DEVICE_NEIGHBOR_METADATA'].keys()):
if device2interface_dict[device]['localPort'] == interfacename:
body.append([device2interface_dict[device]['localPort'],
device,
device2interface_dict[device]['neighborPort'],
neighbor_metadata_dict['DEVICE_NEIGHBOR_METADATA'][device]['lo_addr'],
neighbor_metadata_dict['DEVICE_NEIGHBOR_METADATA'][device]['mgmt_addr'],
neighbor_metadata_dict['DEVICE_NEIGHBOR_METADATA'][device]['type']])
else:
for device in natsorted(neighbor_metadata_dict['DEVICE_NEIGHBOR_METADATA'].keys()):
body.append([device2interface_dict[device]['localPort'],
device,
device2interface_dict[device]['neighborPort'],
neighbor_metadata_dict['DEVICE_NEIGHBOR_METADATA'][device]['lo_addr'],
neighbor_metadata_dict['DEVICE_NEIGHBOR_METADATA'][device]['mgmt_addr'],
neighbor_metadata_dict['DEVICE_NEIGHBOR_METADATA'][device]['type']])
click.echo(tabulate(body, header))
@interfaces.group(cls=AliasedGroup, default_if_no_args=False)
def transceiver():
"""Show SFP Transceiver information"""
pass
@transceiver.command()
@click.argument('interfacename', required=False)
@click.option('-d', '--dom', 'dump_dom', is_flag=True, help="Also display Digital Optical Monitoring (DOM) data")
@click.option('--verbose', is_flag=True, help="Enable verbose output")
def eeprom(interfacename, dump_dom, verbose):
"""Show interface transceiver EEPROM information"""
cmd = "sfpshow eeprom"
if dump_dom:
cmd += " --dom"
if interfacename is not None:
if get_interface_mode() == "alias":
interfacename = iface_alias_converter.alias_to_name(interfacename)
cmd += " -p {}".format(interfacename)
run_command(cmd, display_cmd=verbose)
@transceiver.command()
@click.argument('interfacename', required=False)
@click.option('--verbose', is_flag=True, help="Enable verbose output")
def lpmode(interfacename, verbose):
"""Show interface transceiver low-power mode status"""
cmd = "sudo sfputil show lpmode"
if interfacename is not None:
if get_interface_mode() == "alias":
interfacename = iface_alias_converter.alias_to_name(interfacename)
cmd += " -p {}".format(interfacename)
run_command(cmd, display_cmd=verbose)
@transceiver.command()
@click.argument('interfacename', required=False)
@click.option('--verbose', is_flag=True, help="Enable verbose output")
def presence(interfacename, verbose):
"""Show interface transceiver presence"""
cmd = "sfpshow presence"
if interfacename is not None:
if get_interface_mode() == "alias":
interfacename = iface_alias_converter.alias_to_name(interfacename)
cmd += " -p {}".format(interfacename)
run_command(cmd, display_cmd=verbose)
@interfaces.command()
@click.argument('interfacename', required=False)
@click.option('--verbose', is_flag=True, help="Enable verbose output")
def description(interfacename, verbose):
"""Show interface status, protocol and description"""
cmd = "intfutil description"
if interfacename is not None:
if get_interface_mode() == "alias":
interfacename = iface_alias_converter.alias_to_name(interfacename)
cmd += " {}".format(interfacename)
run_command(cmd, display_cmd=verbose)
@interfaces.command()
@click.argument('interfacename', required=False)
@click.option('--verbose', is_flag=True, help="Enable verbose output")
def status(interfacename, verbose):
"""Show Interface status information"""
cmd = "intfutil status"
if interfacename is not None:
if get_interface_mode() == "alias":
interfacename = iface_alias_converter.alias_to_name(interfacename)
cmd += " {}".format(interfacename)
run_command(cmd, display_cmd=verbose)
# 'counters' subcommand ("show interfaces counters")
@interfaces.group(invoke_without_command=True)
@click.option('-a', '--printall', is_flag=True)
@click.option('-p', '--period')
@click.option('--verbose', is_flag=True, help="Enable verbose output")
@click.pass_context
def counters(ctx, verbose, period, printall):
"""Show interface counters"""
if ctx.invoked_subcommand is None:
cmd = "portstat"
if printall:
cmd += " -a"
if period is not None:
cmd += " -p {}".format(period)
run_command(cmd, display_cmd=verbose)
# 'counters' subcommand ("show interfaces counters rif")
@counters.command()
@click.argument('interface', metavar='<interface_name>', required=False, type=str)
@click.option('-p', '--period')
@click.option('--verbose', is_flag=True, help="Enable verbose output")
def rif(interface, period, verbose):
"""Show interface counters"""
cmd = "intfstat"
if period is not None:
cmd += " -p {}".format(period)
if interface is not None:
cmd += " -i {}".format(interface)
run_command(cmd, display_cmd=verbose)
# 'portchannel' subcommand ("show interfaces portchannel")
@interfaces.command()
@click.option('--verbose', is_flag=True, help="Enable verbose output")
def portchannel(verbose):
"""Show PortChannel information"""
cmd = "sudo teamshow"
run_command(cmd, display_cmd=verbose)
#
# 'subinterfaces' group ("show subinterfaces ...")
#
@cli.group(cls=AliasedGroup, default_if_no_args=False)
def subinterfaces():
"""Show details of the sub port interfaces"""
pass