forked from SW-CSV/csv-SONiC
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
1893 lines (1508 loc) · 58.8 KB
/
main.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
#! /usr/bin/python -u
import errno
import json
import netaddr
import netifaces
import os
import re
import subprocess
import sys
import click
from click_default_group import DefaultGroup
from natsort import natsorted
from tabulate import tabulate
import sonic_platform
from swsssdk import ConfigDBConnector
from swsssdk import SonicV2Connector
import mlnx
SONIC_CFGGEN_PATH = '/usr/local/bin/sonic-cfggen'
from pcieutil import PcieUtil
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("port_dict is None!")
raise click.Abort()
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
"""
if interface_name is not None:
for port_name in self.port_dict.keys():
if interface_name == port_name:
return self.port_dict[port_name]['alias']
click.echo("Invalid interface {}".format(interface_name))
raise click.Abort()
def alias_to_name(self, interface_alias):
"""Return SONiC interface name if vendor
port alias is given as argument
"""
if interface_alias is not None:
for port_name in self.port_dict.keys():
if interface_alias == self.port_dict[port_name]['alias']:
return port_name
click.echo("Invalid interface {}".format(interface_alias))
raise click.Abort()
# 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, 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):
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:
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
# 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)
else:
if index:
for port_name in iface_alias_converter.port_dict.keys():
regex = re.compile(r"\b{}\b".format(port_name))
result = re.findall(regex, raw_output)
if result:
interface_name = ''.join(result)
if not raw_output.startswith(" PortID:"):
raw_output = raw_output.replace(
interface_name,
iface_alias_converter.name_to_alias(
interface_name))
click.echo(raw_output.rstrip('\n'))
rc = process.poll()
if rc != 0:
sys.exit(rc)
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
#
# '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)
#
# 'interfaces' group ("show interfaces ...")
#
@cli.group(cls=AliasedGroup, default_if_no_args=False)
def interfaces():
"""Show details of the network interfaces"""
pass
#
# '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.keys()):
device2interface_dict[neighbor_dict[port]['name']] = {'localPort': port, 'neighborPort': neighbor_dict[port]['port']}
header = ['LocalPort', 'Neighbor', 'NeighborPort', 'NeighborLoopback', 'NeighborMgmt', 'NeighborType']
body = []
if interfacename:
for device in natsorted(neighbor_metadata_dict.keys()):
if device2interface_dict[device]['localPort'] == interfacename:
body.append([device2interface_dict[device]['localPort'],
device,
device2interface_dict[device]['neighborPort'],
neighbor_metadata_dict[device]['lo_addr'],
neighbor_metadata_dict[device]['mgmt_addr'],
neighbor_metadata_dict[device]['type']])
else:
for device in natsorted(neighbor_metadata_dict.keys()):
body.append([device2interface_dict[device]['localPort'],
device,
device2interface_dict[device]['neighborPort'],
neighbor_metadata_dict[device]['lo_addr'],
neighbor_metadata_dict[device]['mgmt_addr'],
neighbor_metadata_dict[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('-c', '--clear', 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, clear, printall):
"""Show interface counters"""
if ctx.invoked_subcommand is None:
cmd = "portstat"
if clear:
cmd += " -c"
else:
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 = "teamshow"
run_command(cmd, display_cmd=verbose)
#
# 'pfc' group ("show pfc ...")
#
@cli.group(cls=AliasedGroup, default_if_no_args=False)
def pfc():
"""Show details of the priority-flow-control (pfc) """
pass
# 'counters' subcommand ("show interfaces pfccounters")
@pfc.command()
@click.option('-c', '--clear', is_flag=True)
@click.option('--verbose', is_flag=True, help="Enable verbose output")
def counters(clear, verbose):
"""Show pfc counters"""
cmd = "pfcstat"
if clear:
cmd += " -c"
run_command(cmd, display_cmd=verbose)
# 'naming_mode' subcommand ("show interfaces naming_mode")
@interfaces.command()
@click.option('--verbose', is_flag=True, help="Enable verbose output")
def naming_mode(verbose):
"""Show interface naming_mode status"""
click.echo(get_interface_mode())
#
# 'watermark' group ("show watermark telemetry interval")
#
@cli.group(cls=AliasedGroup, default_if_no_args=False)
def watermark():
"""Show details of watermark """
pass
@watermark.group()
def telemetry():
"""Show watermark telemetry info"""
pass
@telemetry.command('interval')
def show_tm_interval():
"""Show telemetry interval"""
command = 'watermarkcfg --show-interval'
run_command(command)
#
# 'queue' group ("show queue ...")
#
@cli.group(cls=AliasedGroup, default_if_no_args=False)
def queue():
"""Show details of the queues """
pass
# 'queuecounters' subcommand ("show queue counters")
@queue.command()
@click.argument('interfacename', required=False)
@click.option('-c', '--clear', is_flag=True)
@click.option('--verbose', is_flag=True, help="Enable verbose output")
def counters(interfacename, clear, verbose):
"""Show queue counters"""
cmd = "queuestat"
if interfacename is not None:
if get_interface_mode() == "alias":
interfacename = iface_alias_converter.alias_to_name(interfacename)
if clear:
cmd += " -c"
else:
if interfacename is not None:
cmd += " -p {}".format(interfacename)
run_command(cmd, display_cmd=verbose)
# watermarks subcommands ("show queue watermarks|persistent-watermarks")
@queue.group()
def watermark():
"""Show queue user WM"""
pass
@watermark.command('unicast')
def wm_q_uni():
"""Show user WM for unicast queues"""
command = 'watermarkstat -t q_shared_uni'
run_command(command)
@watermark.command('multicast')
def wm_q_multi():
"""Show user WM for multicast queues"""
command = 'watermarkstat -t q_shared_multi'
run_command(command)
@queue.group(name='persistent-watermark')
def persistent_watermark():
"""Show queue persistent WM"""
pass
@persistent_watermark.command('unicast')
def pwm_q_uni():
"""Show persistent WM for persistent queues"""
command = 'watermarkstat -p -t q_shared_uni'
run_command(command)
@persistent_watermark.command('multicast')
def pwm_q_multi():
"""Show persistent WM for multicast queues"""
command = 'watermarkstat -p -t q_shared_multi'
run_command(command)
#
# 'priority-group' group ("show priority-group ...")
#
@cli.group(name='priority-group', cls=AliasedGroup, default_if_no_args=False)
def priority_group():
"""Show details of the PGs """
@priority_group.group()
def watermark():
"""Show priority_group user WM"""
pass
@watermark.command('headroom')
def wm_pg_headroom():
"""Show user headroom WM for pg"""
command = 'watermarkstat -t pg_headroom'
run_command(command)
@watermark.command('shared')
def wm_pg_shared():
"""Show user shared WM for pg"""
command = 'watermarkstat -t pg_shared'
run_command(command)
@priority_group.group(name='persistent-watermark')
def persistent_watermark():
"""Show queue persistent WM"""
pass
@persistent_watermark.command('headroom')
def pwm_pg_headroom():
"""Show persistent headroom WM for pg"""
command = 'watermarkstat -p -t pg_headroom'
run_command(command)
@persistent_watermark.command('shared')
def pwm_pg_shared():
"""Show persistent shared WM for pg"""
command = 'watermarkstat -p -t pg_shared'
run_command(command)
#
# 'mac' command ("show mac ...")
#
@cli.command()
@click.option('-v', '--vlan')
@click.option('-p', '--port')
@click.option('--verbose', is_flag=True, help="Enable verbose output")
def mac(vlan, port, verbose):
"""Show MAC (FDB) entries"""
cmd = "fdbshow"
if vlan is not None:
cmd += " -v {}".format(vlan)
if port is not None:
cmd += " -p {}".format(port)
run_command(cmd, display_cmd=verbose)
#
# 'show route-map' command ("show route-map")
#
@cli.command('route-map')
@click.argument('route_map_name', required=False)
@click.option('--verbose', is_flag=True, help="Enable verbose output")
def route_map(route_map_name, verbose):
"""show route-map"""
cmd = 'sudo vtysh -c "show route-map'
if route_map_name is not None:
cmd += ' {}'.format(route_map_name)
cmd += '"'
run_command(cmd, display_cmd=verbose)
#
# 'ip' group ("show ip ...")
#
# This group houses IP (i.e., IPv4) commands and subgroups
@cli.group(cls=AliasedGroup, default_if_no_args=False)
def ip():
"""Show IP (IPv4) commands"""
pass
#
# get_if_admin_state
#
# Given an interface name, return its admin state reported by the kernel.
#
def get_if_admin_state(iface):
admin_file = "/sys/class/net/{0}/flags"
try:
state_file = open(admin_file.format(iface), "r")
except IOError as e:
print "Error: unable to open file: %s" % str(e)
return "error"
content = state_file.readline().rstrip()
flags = int(content, 16)
if flags & 0x1:
return "up"
else:
return "down"
#
# get_if_oper_state
#
# Given an interface name, return its oper state reported by the kernel.
#
def get_if_oper_state(iface):
oper_file = "/sys/class/net/{0}/carrier"
try:
state_file = open(oper_file.format(iface), "r")
except IOError as e:
print "Error: unable to open file: %s" % str(e)
return "error"
oper_state = state_file.readline().rstrip()
if oper_state == "1":
return "up"
else:
return "down"
#
# 'show ip interfaces' command
#
# Display all interfaces with an IPv4 address and their admin/oper states.
# Addresses from all scopes are included. Interfaces with no addresses are
# excluded.
#
@ip.command()
def interfaces():
"""Show interfaces IPv4 address"""
header = ['Interface', 'IPv4 address/mask', 'Admin/Oper']
data = []
interfaces = natsorted(netifaces.interfaces())
for iface in interfaces:
ipaddresses = netifaces.ifaddresses(iface)
if netifaces.AF_INET in ipaddresses:
ifaddresses = []
for ipaddr in ipaddresses[netifaces.AF_INET]:
netmask = netaddr.IPAddress(ipaddr['netmask']).netmask_bits()
ifaddresses.append(["", str(ipaddr['addr']) + "/" + str(netmask)])
if len(ifaddresses) > 0:
admin = get_if_admin_state(iface)
if admin == "up":
oper = get_if_oper_state(iface)
else:
oper = "down"
data.append([iface, ifaddresses[0][1], admin + "/" + oper])
for ifaddr in ifaddresses[1:]:
data.append(["", ifaddr[1], ""])
print tabulate(data, header, tablefmt="simple", stralign='left', missingval="")
#
# 'route' subcommand ("show ip route")
#
@ip.command()
@click.argument('ipaddress', required=False)
@click.option('--verbose', is_flag=True, help="Enable verbose output")
def route(ipaddress, verbose):
"""Show IP (IPv4) routing table"""
cmd = 'sudo vtysh -c "show ip route'
if ipaddress is not None:
cmd += ' {}'.format(ipaddress)
cmd += '"'
run_command(cmd, display_cmd=verbose)
#
# 'prefix-list' subcommand ("show ip prefix-list")
#
@ip.command('prefix-list')
@click.argument('prefix_list_name', required=False)
@click.option('--verbose', is_flag=True, help="Enable verbose output")
def prefix_list(prefix_list_name, verbose):
"""show ip prefix-list"""
cmd = 'sudo vtysh -c "show ip prefix-list'
if prefix_list_name is not None:
cmd += ' {}'.format(prefix_list_name)
cmd += '"'
run_command(cmd, display_cmd=verbose)
# 'protocol' command
@ip.command()
@click.option('--verbose', is_flag=True, help="Enable verbose output")
def protocol(verbose):
"""Show IPv4 protocol information"""
cmd = 'sudo vtysh -c "show ip protocol"'
run_command(cmd, display_cmd=verbose)
#
# 'ipv6' group ("show ipv6 ...")
#
# This group houses IPv6-related commands and subgroups
@cli.group(cls=AliasedGroup, default_if_no_args=False)
def ipv6():
"""Show IPv6 commands"""
pass
#
# 'show ipv6 interfaces' command
#
# Display all interfaces with an IPv6 address and their admin/oper states.
# Addresses from all scopes are included. Interfaces with no addresses are
# excluded.
#
@ipv6.command()
def interfaces():
"""Show interfaces IPv6 address"""
header = ['Interface', 'IPv6 address/mask', 'Admin/Oper']
data = []
interfaces = natsorted(netifaces.interfaces())
for iface in interfaces:
ipaddresses = netifaces.ifaddresses(iface)
if netifaces.AF_INET6 in ipaddresses:
ifaddresses = []
for ipaddr in ipaddresses[netifaces.AF_INET6]:
netmask = ipaddr['netmask'].split('/', 1)[-1]
ifaddresses.append(["", str(ipaddr['addr']) + "/" + str(netmask)])
if len(ifaddresses) > 0:
admin = get_if_admin_state(iface)
if admin == "up":
oper = get_if_oper_state(iface)
else:
oper = "down"
data.append([iface, ifaddresses[0][1], admin + "/" + oper])
for ifaddr in ifaddresses[1:]:
data.append(["", ifaddr[1], ""])