forked from sonic-net/sonic-utilities
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
executable file
·2757 lines (2360 loc) · 94.2 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/sbin/env python
import sys
import os
import click
import json
import subprocess
import netaddr
import re
import syslog
import time
import netifaces
import sonic_device_util
import ipaddress
from swsssdk import ConfigDBConnector
from swsssdk import SonicV2Connector
from minigraph import parse_device_desc_xml
import aaa
import mlnx
import nat
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help', '-?'])
SONIC_GENERATED_SERVICE_PATH = '/etc/sonic/generated_services.conf'
SONIC_CFGGEN_PATH = '/usr/local/bin/sonic-cfggen'
SYSLOG_IDENTIFIER = "config"
VLAN_SUB_INTERFACE_SEPARATOR = '.'
ASIC_CONF_FILENAME = 'asic.conf'
INIT_CFG_FILE = '/etc/sonic/init_cfg.json'
SYSTEMCTL_ACTION_STOP="stop"
SYSTEMCTL_ACTION_RESTART="restart"
SYSTEMCTL_ACTION_RESET_FAILED="reset-failed"
# ========================== Syslog wrappers ==========================
def log_debug(msg):
syslog.openlog(SYSLOG_IDENTIFIER)
syslog.syslog(syslog.LOG_DEBUG, msg)
syslog.closelog()
def log_info(msg):
syslog.openlog(SYSLOG_IDENTIFIER)
syslog.syslog(syslog.LOG_INFO, msg)
syslog.closelog()
def log_warning(msg):
syslog.openlog(SYSLOG_IDENTIFIER)
syslog.syslog(syslog.LOG_WARNING, msg)
syslog.closelog()
def log_error(msg):
syslog.openlog(SYSLOG_IDENTIFIER)
syslog.syslog(syslog.LOG_ERR, msg)
syslog.closelog()
#
# Load asic_type for further use
#
try:
version_info = sonic_device_util.get_sonic_version_info()
asic_type = version_info['asic_type']
except KeyError, TypeError:
raise click.Abort()
#
# Helper functions
#
# Execute action on list of systemd services
def execute_systemctl(list_of_services, action):
num_asic = _get_num_asic()
generated_services_list, generated_multi_instance_services = _get_sonic_generated_services(num_asic)
if ((generated_services_list == []) and
(generated_multi_instance_services == [])):
log_error("Failed to get generated services")
return
for service in list_of_services:
if (service + '.service' in generated_services_list):
try:
click.echo("Executing {} of service {}...".format(action, service))
run_command("systemctl {} {}".format(action, service))
except SystemExit as e:
log_error("Failed to execute {} of service {} with error {}".format(action, service, e))
raise
if (service + '.service' in generated_multi_instance_services):
for inst in range(num_asic):
try:
click.echo("Executing {} of service {}@{}...".format(action, service, inst))
run_command("systemctl {} {}@{}.service".format(action, service, inst))
except SystemExit as e:
log_error("Failed to execute {} of service {}@{} with error {}".format(action, service, e))
raise
def run_command(command, display_cmd=False, ignore_error=False):
"""Run bash command and print output to stdout
"""
if display_cmd == True:
click.echo(click.style("Running command: ", fg='cyan') + click.style(command, fg='green'))
proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
(out, err) = proc.communicate()
if len(out) > 0:
click.echo(out)
if proc.returncode != 0 and not ignore_error:
sys.exit(proc.returncode)
def interface_alias_to_name(interface_alias):
"""Return default interface name if alias name is given as argument
"""
config_db = ConfigDBConnector()
config_db.connect()
port_dict = config_db.get_table('PORT')
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 name so the subsequent logic still applies
interface_alias = interface_alias[:sub_intf_sep_idx]
if interface_alias is not None:
if not port_dict:
click.echo("port_dict is None!")
raise click.Abort()
for port_name in port_dict.keys():
if interface_alias == 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, e.g.,
# portchannel is passed in as argument, which does not have an alias
return interface_alias if sub_intf_sep_idx == -1 else interface_alias + VLAN_SUB_INTERFACE_SEPARATOR + vlan_id
def interface_name_is_valid(interface_name):
"""Check if the interface name is valid
"""
config_db = ConfigDBConnector()
config_db.connect()
port_dict = config_db.get_table('PORT')
port_channel_dict = config_db.get_table('PORTCHANNEL')
sub_port_intf_dict = config_db.get_table('VLAN_SUB_INTERFACE')
if get_interface_naming_mode() == "alias":
interface_name = interface_alias_to_name(interface_name)
if interface_name is not None:
if not port_dict:
click.echo("port_dict is None!")
raise click.Abort()
for port_name in port_dict.keys():
if interface_name == port_name:
return True
if port_channel_dict:
for port_channel_name in port_channel_dict.keys():
if interface_name == port_channel_name:
return True
if sub_port_intf_dict:
for sub_port_intf_name in sub_port_intf_dict.keys():
if interface_name == sub_port_intf_name:
return True
return False
def interface_name_to_alias(interface_name):
"""Return alias interface name if default name is given as argument
"""
config_db = ConfigDBConnector()
config_db.connect()
port_dict = config_db.get_table('PORT')
if interface_name is not None:
if not port_dict:
click.echo("port_dict is None!")
raise click.Abort()
for port_name in port_dict.keys():
if interface_name == port_name:
return port_dict[port_name]['alias']
return None
def get_interface_table_name(interface_name):
"""Get table name by interface_name prefix
"""
if interface_name.startswith("Ethernet"):
if VLAN_SUB_INTERFACE_SEPARATOR in interface_name:
return "VLAN_SUB_INTERFACE"
return "INTERFACE"
elif interface_name.startswith("PortChannel"):
if VLAN_SUB_INTERFACE_SEPARATOR in interface_name:
return "VLAN_SUB_INTERFACE"
return "PORTCHANNEL_INTERFACE"
elif interface_name.startswith("Vlan"):
return "VLAN_INTERFACE"
elif interface_name.startswith("Loopback"):
return "LOOPBACK_INTERFACE"
else:
return ""
def interface_ipaddr_dependent_on_interface(config_db, interface_name):
"""Get table keys including ipaddress
"""
data = []
table_name = get_interface_table_name(interface_name)
if table_name == "":
return data
keys = config_db.get_keys(table_name)
for key in keys:
if interface_name in key and len(key) == 2:
data.append(key)
return data
def is_interface_bind_to_vrf(config_db, interface_name):
"""Get interface if bind to vrf or not
"""
table_name = get_interface_table_name(interface_name)
if table_name == "":
return False
entry = config_db.get_entry(table_name, interface_name)
if entry and entry.get("vrf_name"):
return True
return False
def del_interface_bind_to_vrf(config_db, vrf_name):
"""del interface bind to vrf
"""
tables = ['INTERFACE', 'PORTCHANNEL_INTERFACE', 'VLAN_INTERFACE', 'LOOPBACK_INTERFACE']
for table_name in tables:
interface_dict = config_db.get_table(table_name)
if interface_dict:
for interface_name in interface_dict.keys():
if interface_dict[interface_name].has_key('vrf_name') and vrf_name == interface_dict[interface_name]['vrf_name']:
interface_dependent = interface_ipaddr_dependent_on_interface(config_db, interface_name)
for interface_del in interface_dependent:
config_db.set_entry(table_name, interface_del, None)
config_db.set_entry(table_name, interface_name, None)
def set_interface_naming_mode(mode):
"""Modify SONIC_CLI_IFACE_MODE env variable in user .bashrc
"""
user = os.getenv('SUDO_USER')
bashrc_ifacemode_line = "export SONIC_CLI_IFACE_MODE={}".format(mode)
# Ensure all interfaces have an 'alias' key in PORT dict
config_db = ConfigDBConnector()
config_db.connect()
port_dict = config_db.get_table('PORT')
if not port_dict:
click.echo("port_dict is None!")
raise click.Abort()
for port_name in port_dict.keys():
try:
if port_dict[port_name]['alias']:
pass
except KeyError:
click.echo("Platform does not support alias mapping")
raise click.Abort()
if not user:
user = os.getenv('USER')
if user != "root":
bashrc = "/home/{}/.bashrc".format(user)
else:
click.get_current_context().fail("Cannot set interface naming mode for root user!")
f = open(bashrc, 'r')
filedata = f.read()
f.close()
if "SONIC_CLI_IFACE_MODE" not in filedata:
newdata = filedata + bashrc_ifacemode_line
newdata += "\n"
else:
newdata = re.sub(r"export SONIC_CLI_IFACE_MODE=\w+",
bashrc_ifacemode_line, filedata)
f = open(bashrc, 'w')
f.write(newdata)
f.close()
click.echo("Please logout and log back in for changes take effect.")
def get_interface_naming_mode():
mode = os.getenv('SONIC_CLI_IFACE_MODE')
if mode is None:
mode = "default"
return mode
def _is_neighbor_ipaddress(ipaddress):
"""Returns True if a neighbor has the IP address <ipaddress>, False if not
"""
config_db = ConfigDBConnector()
config_db.connect()
entry = config_db.get_entry('BGP_NEIGHBOR', ipaddress)
return True if entry else False
def _get_all_neighbor_ipaddresses():
"""Returns list of strings containing IP addresses of all BGP neighbors
"""
config_db = ConfigDBConnector()
config_db.connect()
return config_db.get_table('BGP_NEIGHBOR').keys()
def _get_neighbor_ipaddress_list_by_hostname(hostname):
"""Returns list of strings, each containing an IP address of neighbor with
hostname <hostname>. Returns empty list if <hostname> not a neighbor
"""
addrs = []
config_db = ConfigDBConnector()
config_db.connect()
bgp_sessions = config_db.get_table('BGP_NEIGHBOR')
for addr, session in bgp_sessions.iteritems():
if session.has_key('name') and session['name'] == hostname:
addrs.append(addr)
return addrs
def _change_bgp_session_status_by_addr(ipaddress, status, verbose):
"""Start up or shut down BGP session by IP address
"""
verb = 'Starting' if status == 'up' else 'Shutting'
click.echo("{} {} BGP session with neighbor {}...".format(verb, status, ipaddress))
config_db = ConfigDBConnector()
config_db.connect()
config_db.mod_entry('bgp_neighbor', ipaddress, {'admin_status': status})
def _change_bgp_session_status(ipaddr_or_hostname, status, verbose):
"""Start up or shut down BGP session by IP address or hostname
"""
ip_addrs = []
# If we were passed an IP address, convert it to lowercase because IPv6 addresses were
# stored in ConfigDB with all lowercase alphabet characters during minigraph parsing
if _is_neighbor_ipaddress(ipaddr_or_hostname.lower()):
ip_addrs.append(ipaddr_or_hostname.lower())
else:
# If <ipaddr_or_hostname> is not the IP address of a neighbor, check to see if it's a hostname
ip_addrs = _get_neighbor_ipaddress_list_by_hostname(ipaddr_or_hostname)
if not ip_addrs:
click.get_current_context().fail("Could not locate neighbor '{}'".format(ipaddr_or_hostname))
for ip_addr in ip_addrs:
_change_bgp_session_status_by_addr(ip_addr, status, verbose)
def _validate_bgp_neighbor(neighbor_ip_or_hostname):
"""validates whether the given ip or host name is a BGP neighbor
"""
ip_addrs = []
if _is_neighbor_ipaddress(neighbor_ip_or_hostname.lower()):
ip_addrs.append(neighbor_ip_or_hostname.lower())
else:
ip_addrs = _get_neighbor_ipaddress_list_by_hostname(neighbor_ip_or_hostname.upper())
if not ip_addrs:
click.get_current_context().fail("Could not locate neighbor '{}'".format(neighbor_ip_or_hostname))
return ip_addrs
def _remove_bgp_neighbor_config(neighbor_ip_or_hostname):
"""Removes BGP configuration of the given neighbor
"""
ip_addrs = _validate_bgp_neighbor(neighbor_ip_or_hostname)
config_db = ConfigDBConnector()
config_db.connect()
for ip_addr in ip_addrs:
config_db.mod_entry('bgp_neighbor', ip_addr, None)
click.echo("Removed configuration of BGP neighbor {}".format(ip_addr))
def _change_hostname(hostname):
current_hostname = os.uname()[1]
if current_hostname != hostname:
run_command('echo {} > /etc/hostname'.format(hostname), display_cmd=True)
run_command('hostname -F /etc/hostname', display_cmd=True)
run_command('sed -i "/\s{}$/d" /etc/hosts'.format(current_hostname), display_cmd=True)
run_command('echo "127.0.0.1 {}" >> /etc/hosts'.format(hostname), display_cmd=True)
def _clear_qos():
QOS_TABLE_NAMES = [
'TC_TO_PRIORITY_GROUP_MAP',
'MAP_PFC_PRIORITY_TO_QUEUE',
'TC_TO_QUEUE_MAP',
'DSCP_TO_TC_MAP',
'SCHEDULER',
'PFC_PRIORITY_TO_PRIORITY_GROUP_MAP',
'PORT_QOS_MAP',
'WRED_PROFILE',
'QUEUE',
'CABLE_LENGTH',
'BUFFER_POOL',
'BUFFER_PROFILE',
'BUFFER_PG',
'BUFFER_QUEUE']
config_db = ConfigDBConnector()
config_db.connect()
for qos_table in QOS_TABLE_NAMES:
config_db.delete_table(qos_table)
def _get_hwsku():
config_db = ConfigDBConnector()
config_db.connect()
metadata = config_db.get_table('DEVICE_METADATA')
return metadata['localhost']['hwsku']
def _get_platform():
with open('/host/machine.conf') as machine_conf:
for line in machine_conf:
tokens = line.split('=')
if tokens[0].strip() == 'onie_platform' or tokens[0].strip() == 'aboot_platform':
return tokens[1].strip()
return ''
def _get_num_asic():
platform = _get_platform()
num_asic = 1
asic_conf_file = os.path.join('/usr/share/sonic/device/', platform, ASIC_CONF_FILENAME)
if os.path.isfile(asic_conf_file):
with open(asic_conf_file) as conf_file:
for line in conf_file:
line_info = line.split('=')
if line_info[0].lower() == "num_asic":
num_asic = int(line_info[1])
return num_asic
def _get_sonic_generated_services(num_asic):
if not os.path.isfile(SONIC_GENERATED_SERVICE_PATH):
return None
generated_services_list = []
generated_multi_instance_services = []
with open(SONIC_GENERATED_SERVICE_PATH) as generated_service_file:
for line in generated_service_file:
if '@' in line:
line = line.replace('@', '')
if num_asic > 1:
generated_multi_instance_services.append(line.rstrip('\n'))
else:
generated_services_list.append(line.rstrip('\n'))
else:
generated_services_list.append(line.rstrip('\n'))
return generated_services_list, generated_multi_instance_services
# Callback for confirmation prompt. Aborts if user enters "n"
def _abort_if_false(ctx, param, value):
if not value:
ctx.abort()
def _stop_services():
# on Mellanox platform pmon is stopped by syncd
services_to_stop = [
'swss',
'lldp',
'pmon',
'bgp',
'hostcfgd',
'nat'
]
if asic_type == 'mellanox' and 'pmon' in services_to_stop:
services_to_stop.remove('pmon')
execute_systemctl(services_to_stop, SYSTEMCTL_ACTION_STOP)
def _reset_failed_services():
services_to_reset = [
'bgp',
'dhcp_relay',
'hostcfgd',
'hostname-config',
'interfaces-config',
'lldp',
'ntp-config',
'pmon',
'radv',
'rsyslog-config',
'snmp',
'swss',
'syncd',
'teamd',
'nat',
'sflow'
]
execute_systemctl(services_to_reset, SYSTEMCTL_ACTION_RESET_FAILED)
def _restart_services():
# on Mellanox platform pmon is started by syncd
services_to_restart = [
'hostname-config',
'interfaces-config',
'ntp-config',
'rsyslog-config',
'swss',
'bgp',
'pmon',
'lldp',
'hostcfgd',
'nat',
'sflow',
]
if asic_type == 'mellanox' and 'pmon' in services_to_restart:
services_to_restart.remove('pmon')
execute_systemctl(services_to_restart, SYSTEMCTL_ACTION_RESTART)
def is_ipaddress(val):
""" Validate if an entry is a valid IP """
if not val:
return False
try:
netaddr.IPAddress(str(val))
except:
return False
return True
# This is our main entrypoint - the main 'config' command
@click.group(context_settings=CONTEXT_SETTINGS)
def config():
"""SONiC command line - 'config' command"""
if os.geteuid() != 0:
exit("Root privileges are required for this operation")
config.add_command(aaa.aaa)
config.add_command(aaa.tacacs)
# === Add NAT Configuration ==========
config.add_command(nat.nat)
@config.command()
@click.option('-y', '--yes', is_flag=True, callback=_abort_if_false,
expose_value=False, prompt='Existing file will be overwritten, continue?')
@click.argument('filename', default='/etc/sonic/config_db.json', type=click.Path())
def save(filename):
"""Export current config DB to a file on disk."""
command = "{} -d --print-data > {}".format(SONIC_CFGGEN_PATH, filename)
run_command(command, display_cmd=True)
@config.command()
@click.option('-y', '--yes', is_flag=True)
@click.argument('filename', default='/etc/sonic/config_db.json', type=click.Path(exists=True))
def load(filename, yes):
"""Import a previous saved config DB dump file."""
if not yes:
click.confirm('Load config from the file %s?' % filename, abort=True)
command = "{} -j {} --write-to-db".format(SONIC_CFGGEN_PATH, filename)
run_command(command, display_cmd=True)
@config.command()
@click.option('-y', '--yes', is_flag=True)
@click.option('-l', '--load-sysinfo', is_flag=True, help='load system default information (mac, portmap etc) first.')
@click.argument('filename', default='/etc/sonic/config_db.json', type=click.Path(exists=True))
def reload(filename, yes, load_sysinfo):
"""Clear current configuration and import a previous saved config DB dump file."""
if not yes:
click.confirm('Clear current config and reload config from the file %s?' % filename, abort=True)
log_info("'reload' executing...")
if load_sysinfo:
command = "{} -j {} -v DEVICE_METADATA.localhost.hwsku".format(SONIC_CFGGEN_PATH, filename)
proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
cfg_hwsku, err = proc.communicate()
if err:
click.echo("Could not get the HWSKU from config file, exiting")
sys.exit(1)
else:
cfg_hwsku = cfg_hwsku.strip()
#Stop services before config push
log_info("'reload' stopping services...")
_stop_services()
config_db = ConfigDBConnector()
config_db.connect()
client = config_db.get_redis_client(config_db.CONFIG_DB)
client.flushdb()
if load_sysinfo:
command = "{} -H -k {} --write-to-db".format(SONIC_CFGGEN_PATH, cfg_hwsku)
run_command(command, display_cmd=True)
if os.path.isfile(INIT_CFG_FILE):
command = "{} -j {} -j {} --write-to-db".format(SONIC_CFGGEN_PATH, INIT_CFG_FILE, filename)
else:
command = "{} -j {} --write-to-db".format(SONIC_CFGGEN_PATH, filename)
run_command(command, display_cmd=True)
client.set(config_db.INIT_INDICATOR, 1)
# Migrate DB contents to latest version
db_migrator='/usr/bin/db_migrator.py'
if os.path.isfile(db_migrator) and os.access(db_migrator, os.X_OK):
run_command(db_migrator + ' -o migrate')
# We first run "systemctl reset-failed" to remove the "failed"
# status from all services before we attempt to restart them
_reset_failed_services()
log_info("'reload' restarting services...")
_restart_services()
@config.command("load_mgmt_config")
@click.option('-y', '--yes', is_flag=True, callback=_abort_if_false,
expose_value=False, prompt='Reload mgmt config?')
@click.argument('filename', default='/etc/sonic/device_desc.xml', type=click.Path(exists=True))
def load_mgmt_config(filename):
"""Reconfigure hostname and mgmt interface based on device description file."""
command = "{} -M {} --write-to-db".format(SONIC_CFGGEN_PATH, filename)
run_command(command, display_cmd=True)
#FIXME: After config DB daemon for hostname and mgmt interface is implemented, we'll no longer need to do manual configuration here
config_data = parse_device_desc_xml(filename)
hostname = config_data['DEVICE_METADATA']['localhost']['hostname']
_change_hostname(hostname)
mgmt_conf = netaddr.IPNetwork(config_data['MGMT_INTERFACE'].keys()[0][1])
gw_addr = config_data['MGMT_INTERFACE'].values()[0]['gwaddr']
command = "ifconfig eth0 {} netmask {}".format(str(mgmt_conf.ip), str(mgmt_conf.netmask))
run_command(command, display_cmd=True)
command = "ip route add default via {} dev eth0 table default".format(gw_addr)
run_command(command, display_cmd=True, ignore_error=True)
command = "ip rule add from {} table default".format(str(mgmt_conf.ip))
run_command(command, display_cmd=True, ignore_error=True)
command = "[ -f /var/run/dhclient.eth0.pid ] && kill `cat /var/run/dhclient.eth0.pid` && rm -f /var/run/dhclient.eth0.pid"
run_command(command, display_cmd=True, ignore_error=True)
click.echo("Please note loaded setting will be lost after system reboot. To preserve setting, run `config save`.")
@config.command("load_minigraph")
@click.option('-y', '--yes', is_flag=True, callback=_abort_if_false,
expose_value=False, prompt='Reload config from minigraph?')
def load_minigraph():
"""Reconfigure based on minigraph."""
log_info("'load_minigraph' executing...")
# get the device type
command = "{} -m -v DEVICE_METADATA.localhost.type".format(SONIC_CFGGEN_PATH)
proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
device_type, err = proc.communicate()
if err:
click.echo("Could not get the device type from minigraph, setting device type to Unknown")
device_type = 'Unknown'
else:
device_type = device_type.strip()
#Stop services before config push
log_info("'load_minigraph' stopping services...")
_stop_services()
config_db = ConfigDBConnector()
config_db.connect()
client = config_db.get_redis_client(config_db.CONFIG_DB)
client.flushdb()
if os.path.isfile('/etc/sonic/init_cfg.json'):
command = "{} -H -m -j /etc/sonic/init_cfg.json --write-to-db".format(SONIC_CFGGEN_PATH)
else:
command = "{} -H -m --write-to-db".format(SONIC_CFGGEN_PATH)
run_command(command, display_cmd=True)
client.set(config_db.INIT_INDICATOR, 1)
if device_type != 'MgmtToRRouter':
run_command('pfcwd start_default', display_cmd=True)
if os.path.isfile('/etc/sonic/acl.json'):
run_command("acl-loader update full /etc/sonic/acl.json", display_cmd=True)
run_command("config qos reload", display_cmd=True)
# Write latest db version string into db
db_migrator='/usr/bin/db_migrator.py'
if os.path.isfile(db_migrator) and os.access(db_migrator, os.X_OK):
run_command(db_migrator + ' -o set_version')
# We first run "systemctl reset-failed" to remove the "failed"
# status from all services before we attempt to restart them
_reset_failed_services()
#FIXME: After config DB daemon is implemented, we'll no longer need to restart every service.
log_info("'load_minigraph' restarting services...")
_restart_services()
click.echo("Please note setting loaded from minigraph will be lost after system reboot. To preserve setting, run `config save`.")
#
# 'hostname' command
#
@config.command('hostname')
@click.argument('new_hostname', metavar='<new_hostname>', required=True)
def hostname(new_hostname):
"""Change device hostname without impacting the traffic."""
config_db = ConfigDBConnector()
config_db.connect()
config_db.mod_entry('DEVICE_METADATA' , 'localhost', {"hostname" : new_hostname})
try:
command = "service hostname-config restart"
run_command(command, display_cmd=True)
except SystemExit as e:
click.echo("Restarting hostname-config service failed with error {}".format(e))
raise
click.echo("Please note loaded setting will be lost after system reboot. To preserve setting, run `config save`.")
#
# 'portchannel' group ('config portchannel ...')
#
@config.group()
@click.pass_context
def portchannel(ctx):
config_db = ConfigDBConnector()
config_db.connect()
ctx.obj = {'db': config_db}
pass
@portchannel.command('add')
@click.argument('portchannel_name', metavar='<portchannel_name>', required=True)
@click.option('--min-links', default=0, type=int)
@click.option('--fallback', default='false')
@click.pass_context
def add_portchannel(ctx, portchannel_name, min_links, fallback):
"""Add port channel"""
db = ctx.obj['db']
fvs = {'admin_status': 'up',
'mtu': '9100'}
if min_links != 0:
fvs['min_links'] = str(min_links)
if fallback != 'false':
fvs['fallback'] = 'true'
db.set_entry('PORTCHANNEL', portchannel_name, fvs)
@portchannel.command('del')
@click.argument('portchannel_name', metavar='<portchannel_name>', required=True)
@click.pass_context
def remove_portchannel(ctx, portchannel_name):
"""Remove port channel"""
db = ctx.obj['db']
db.set_entry('PORTCHANNEL', portchannel_name, None)
@portchannel.group('member')
@click.pass_context
def portchannel_member(ctx):
pass
@portchannel_member.command('add')
@click.argument('portchannel_name', metavar='<portchannel_name>', required=True)
@click.argument('port_name', metavar='<port_name>', required=True)
@click.pass_context
def add_portchannel_member(ctx, portchannel_name, port_name):
"""Add member to port channel"""
db = ctx.obj['db']
db.set_entry('PORTCHANNEL_MEMBER', (portchannel_name, port_name),
{'NULL': 'NULL'})
@portchannel_member.command('del')
@click.argument('portchannel_name', metavar='<portchannel_name>', required=True)
@click.argument('port_name', metavar='<port_name>', required=True)
@click.pass_context
def del_portchannel_member(ctx, portchannel_name, port_name):
"""Remove member from portchannel"""
db = ctx.obj['db']
db.set_entry('PORTCHANNEL_MEMBER', (portchannel_name, port_name), None)
db.set_entry('PORTCHANNEL_MEMBER', portchannel_name + '|' + port_name, None)
#
# 'mirror_session' group ('config mirror_session ...')
#
@config.group()
def mirror_session():
pass
@mirror_session.command()
@click.argument('session_name', metavar='<session_name>', required=True)
@click.argument('src_ip', metavar='<src_ip>', required=True)
@click.argument('dst_ip', metavar='<dst_ip>', required=True)
@click.argument('dscp', metavar='<dscp>', required=True)
@click.argument('ttl', metavar='<ttl>', required=True)
@click.argument('gre_type', metavar='[gre_type]', required=False)
@click.argument('queue', metavar='[queue]', required=False)
@click.option('--policer')
def add(session_name, src_ip, dst_ip, dscp, ttl, gre_type, queue, policer):
"""
Add mirror session
"""
config_db = ConfigDBConnector()
config_db.connect()
session_info = {
"src_ip": src_ip,
"dst_ip": dst_ip,
"dscp": dscp,
"ttl": ttl
}
if policer is not None:
session_info['policer'] = policer
if gre_type is not None:
session_info['gre_type'] = gre_type
if queue is not None:
session_info['queue'] = queue
config_db.set_entry("MIRROR_SESSION", session_name, session_info)
@mirror_session.command()
@click.argument('session_name', metavar='<session_name>', required=True)
def remove(session_name):
"""
Delete mirror session
"""
config_db = ConfigDBConnector()
config_db.connect()
config_db.set_entry("MIRROR_SESSION", session_name, None)
#
# 'pfcwd' group ('config pfcwd ...')
#
@config.group()
def pfcwd():
"""Configure pfc watchdog """
pass
@pfcwd.command()
@click.option('--action', '-a', type=click.Choice(['drop', 'forward', 'alert']))
@click.option('--restoration-time', '-r', type=click.IntRange(100, 60000))
@click.option('--verbose', is_flag=True, help="Enable verbose output")
@click.argument('ports', nargs=-1)
@click.argument('detection-time', type=click.IntRange(100, 5000))
def start(action, restoration_time, ports, detection_time, verbose):
"""
Start PFC watchdog on port(s). To config all ports, use all as input.
Example:
config pfcwd start --action drop ports all detection-time 400 --restoration-time 400
"""
cmd = "pfcwd start"
if action:
cmd += " --action {}".format(action)
if ports:
ports = set(ports) - set(['ports', 'detection-time'])
cmd += " ports {}".format(' '.join(ports))
if detection_time:
cmd += " detection-time {}".format(detection_time)
if restoration_time:
cmd += " --restoration-time {}".format(restoration_time)
run_command(cmd, display_cmd=verbose)
@pfcwd.command()
@click.option('--verbose', is_flag=True, help="Enable verbose output")
def stop(verbose):
""" Stop PFC watchdog """
cmd = "pfcwd stop"
run_command(cmd, display_cmd=verbose)
@pfcwd.command()
@click.option('--verbose', is_flag=True, help="Enable verbose output")
@click.argument('poll_interval', type=click.IntRange(100, 3000))
def interval(poll_interval, verbose):
""" Set PFC watchdog counter polling interval (ms) """
cmd = "pfcwd interval {}".format(poll_interval)
run_command(cmd, display_cmd=verbose)
@pfcwd.command()
@click.option('--verbose', is_flag=True, help="Enable verbose output")
@click.argument('counter_poll', type=click.Choice(['enable', 'disable']))
def counter_poll(counter_poll, verbose):
""" Enable/disable counter polling """
cmd = "pfcwd counter_poll {}".format(counter_poll)
run_command(cmd, display_cmd=verbose)
@pfcwd.command()
@click.option('--verbose', is_flag=True, help="Enable verbose output")
@click.argument('big_red_switch', type=click.Choice(['enable', 'disable']))
def big_red_switch(big_red_switch, verbose):
""" Enable/disable BIG_RED_SWITCH mode """
cmd = "pfcwd big_red_switch {}".format(big_red_switch)
run_command(cmd, display_cmd=verbose)
@pfcwd.command()
@click.option('--verbose', is_flag=True, help="Enable verbose output")
def start_default(verbose):
""" Start PFC WD by default configurations """
cmd = "pfcwd start_default"
run_command(cmd, display_cmd=verbose)
#
# 'qos' group ('config qos ...')
#
@config.group()
@click.pass_context
def qos(ctx):
pass
@qos.command('clear')
def clear():
_clear_qos()
@qos.command('reload')
def reload():
_clear_qos()
platform = _get_platform()
hwsku = _get_hwsku()
buffer_template_file = os.path.join('/usr/share/sonic/device/', platform, hwsku, 'buffers.json.j2')
if os.path.isfile(buffer_template_file):
command = "{} -d -t {} >/tmp/buffers.json".format(SONIC_CFGGEN_PATH, buffer_template_file)
run_command(command, display_cmd=True)
qos_template_file = os.path.join('/usr/share/sonic/device/', platform, hwsku, 'qos.json.j2')
sonic_version_file = os.path.join('/etc/sonic/', 'sonic_version.yml')
if os.path.isfile(qos_template_file):
command = "{} -d -t {} -y {} >/tmp/qos.json".format(SONIC_CFGGEN_PATH, qos_template_file, sonic_version_file)
run_command(command, display_cmd=True)
# Apply the configurations only when both buffer and qos configuration files are presented
command = "{} -j /tmp/buffers.json --write-to-db".format(SONIC_CFGGEN_PATH)
run_command(command, display_cmd=True)
command = "{} -j /tmp/qos.json --write-to-db".format(SONIC_CFGGEN_PATH)
run_command(command, display_cmd=True)
else:
click.secho('QoS definition template not found at {}'.format(qos_template_file), fg='yellow')
else:
click.secho('Buffer definition template not found at {}'.format(buffer_template_file), fg='yellow')
#
# 'warm_restart' group ('config warm_restart ...')
#
@config.group()
@click.pass_context
@click.option('-s', '--redis-unix-socket-path', help='unix socket path for redis connection')
def warm_restart(ctx, redis_unix_socket_path):
"""warm_restart-related configuration tasks"""
kwargs = {}
if redis_unix_socket_path:
kwargs['unix_socket_path'] = redis_unix_socket_path
config_db = ConfigDBConnector(**kwargs)
config_db.connect(wait_for_init=False)
# warm restart enable/disable config is put in stateDB, not persistent across cold reboot, not saved to config_DB.json file
state_db = SonicV2Connector(host='127.0.0.1')
state_db.connect(state_db.STATE_DB, False)
TABLE_NAME_SEPARATOR = '|'
prefix = 'WARM_RESTART_ENABLE_TABLE' + TABLE_NAME_SEPARATOR
ctx.obj = {'db': config_db, 'state_db': state_db, 'prefix': prefix}
pass
@warm_restart.command('enable')
@click.argument('module', metavar='<module>', default='system', required=False, type=click.Choice(["system", "swss", "bgp", "teamd"]))
@click.pass_context
def warm_restart_enable(ctx, module):
state_db = ctx.obj['state_db']
prefix = ctx.obj['prefix']
_hash = '{}{}'.format(prefix, module)
state_db.set(state_db.STATE_DB, _hash, 'enable', 'true')
state_db.close(state_db.STATE_DB)
@warm_restart.command('disable')
@click.argument('module', metavar='<module>', default='system', required=False, type=click.Choice(["system", "swss", "bgp", "teamd"]))
@click.pass_context
def warm_restart_enable(ctx, module):
state_db = ctx.obj['state_db']
prefix = ctx.obj['prefix']
_hash = '{}{}'.format(prefix, module)
state_db.set(state_db.STATE_DB, _hash, 'enable', 'false')
state_db.close(state_db.STATE_DB)
@warm_restart.command('neighsyncd_timer')
@click.argument('seconds', metavar='<seconds>', required=True, type=int)
@click.pass_context
def warm_restart_neighsyncd_timer(ctx, seconds):
db = ctx.obj['db']
if seconds not in range(1,9999):
ctx.fail("neighsyncd warm restart timer must be in range 1-9999")
db.mod_entry('WARM_RESTART', 'swss', {'neighsyncd_timer': seconds})
@warm_restart.command('bgp_timer')
@click.argument('seconds', metavar='<seconds>', required=True, type=int)
@click.pass_context
def warm_restart_bgp_timer(ctx, seconds):
db = ctx.obj['db']