-
Notifications
You must be signed in to change notification settings - Fork 664
/
main.py
9074 lines (7595 loc) · 357 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 threading
import click
import concurrent.futures
import datetime
import ipaddress
import json
import jsonpatch
import netaddr
import netifaces
import os
import re
import subprocess
import sys
import time
import itertools
import copy
import tempfile
import sonic_yang
from jsonpatch import JsonPatchConflict
from jsonpointer import JsonPointerException
from collections import OrderedDict
from generic_config_updater.generic_updater import GenericUpdater, ConfigFormat, extract_scope
from generic_config_updater.gu_common import HOST_NAMESPACE, GenericConfigUpdaterError
from minigraph import parse_device_desc_xml, minigraph_encoder
from natsort import natsorted
from portconfig import get_child_ports
from socket import AF_INET, AF_INET6
from sonic_py_common import device_info, multi_asic
from sonic_py_common.general import getstatusoutput_noshell
from sonic_py_common.interface import get_interface_table_name, get_port_table_name, get_intf_longname
from sonic_yang_cfg_generator import SonicYangCfgDbGenerator
from utilities_common import util_base
from swsscommon import swsscommon
from swsscommon.swsscommon import SonicV2Connector, ConfigDBConnector, ConfigDBPipeConnector, \
isInterfaceNameValid, IFACE_NAME_MAX_LEN
from utilities_common.db import Db
from utilities_common.intf_filter import parse_interface_in_filter
from utilities_common import bgp_util
import utilities_common.cli as clicommon
from utilities_common.helper import get_port_pbh_binding, get_port_acl_binding, update_config
from utilities_common.general import load_db_config, load_module_from_source
from .validated_config_db_connector import ValidatedConfigDBConnector
import utilities_common.multi_asic as multi_asic_util
from utilities_common.flock import try_lock
from .utils import log
from . import aaa
from . import chassis_modules
from . import console
from . import feature
from . import fabric
from . import flow_counters
from . import kdump
from . import kube
from . import muxcable
from . import nat
from . import vlan
from . import vxlan
from . import plugins
from .config_mgmt import ConfigMgmtDPB, ConfigMgmt, YANG_DIR
from . import mclag
from . import syslog
from . import switchport
from . import dns
from . import bgp_cli
from . import stp
# mock masic APIs for unit test
try:
if os.environ["UTILITIES_UNIT_TESTING"] == "1" or os.environ["UTILITIES_UNIT_TESTING"] == "2":
modules_path = os.path.join(os.path.dirname(__file__), "..")
tests_path = os.path.join(modules_path, "tests")
sys.path.insert(0, modules_path)
sys.path.insert(0, tests_path)
import mock_tables.dbconnector
if os.environ["UTILITIES_UNIT_TESTING_TOPOLOGY"] == "multi_asic":
import mock_tables.mock_multi_asic
mock_tables.dbconnector.load_namespace_config()
except KeyError:
pass
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'
VLAN_SUB_INTERFACE_SEPARATOR = '.'
ASIC_CONF_FILENAME = 'asic.conf'
DEFAULT_CONFIG_DB_FILE = '/etc/sonic/config_db.json'
DEFAULT_CONFIG_YANG_FILE = '/etc/sonic/config_yang.json'
NAMESPACE_PREFIX = 'asic'
INTF_KEY = "interfaces"
DEFAULT_GOLDEN_CONFIG_DB_FILE = '/etc/sonic/golden_config_db.json'
INIT_CFG_FILE = '/etc/sonic/init_cfg.json'
DEFAULT_NAMESPACE = ''
CFG_LOOPBACK_PREFIX = "Loopback"
CFG_LOOPBACK_PREFIX_LEN = len(CFG_LOOPBACK_PREFIX)
CFG_LOOPBACK_NAME_TOTAL_LEN_MAX = 11
CFG_LOOPBACK_ID_MAX_VAL = 999
CFG_LOOPBACK_NO="<0-999>"
CFG_PORTCHANNEL_PREFIX = "PortChannel"
CFG_PORTCHANNEL_PREFIX_LEN = 11
CFG_PORTCHANNEL_MAX_VAL = 9999
CFG_PORTCHANNEL_NO="<0-9999>"
PORT_MTU = "mtu"
PORT_SPEED = "speed"
PORT_TPID = "tpid"
DEFAULT_TPID = "0x8100"
PORT_MODE = "switchport_mode"
DOM_CONFIG_SUPPORTED_SUBPORTS = ['0', '1']
asic_type = None
DSCP_RANGE = click.IntRange(min=0, max=63)
TTL_RANGE = click.IntRange(min=0, max=255)
QUEUE_RANGE = click.IntRange(min=0, max=255)
GRE_TYPE_RANGE = click.IntRange(min=0, max=65535)
ADHOC_VALIDATION = True
if os.environ.get("UTILITIES_UNIT_TESTING", "0") in ("1", "2"):
temp_system_reload_lockfile = tempfile.NamedTemporaryFile()
SYSTEM_RELOAD_LOCK = temp_system_reload_lockfile.name
else:
SYSTEM_RELOAD_LOCK = "/etc/sonic/reload.lock"
# Load sonic-cfggen from source since /usr/local/bin/sonic-cfggen does not have .py extension.
sonic_cfggen = load_module_from_source('sonic_cfggen', '/usr/local/bin/sonic-cfggen')
#
# Helper functions
#
# Sort nested dict
def sort_dict(data):
""" Sort of 1st level and 2nd level dict of data naturally by its key
data: data to be sorted
"""
if type(data) is not dict:
return data
for table in data:
if type(data[table]) is dict:
data[table] = OrderedDict(natsorted(data[table].items()))
return OrderedDict(natsorted(data.items()))
# Read given JSON file
def read_json_file(fileName):
try:
with open(fileName) as f:
result = json.load(f)
except Exception as e:
raise Exception(str(e))
return result
# write given JSON file
def write_json_file(json_input, fileName):
try:
with open(fileName, 'w') as f:
json.dump(json_input, f, indent=4)
except Exception as e:
raise Exception(str(e))
def _get_breakout_options(ctx, args, incomplete):
""" Provides dynamic mode option as per user argument i.e. interface name """
all_mode_options = []
interface_name = args[-1]
breakout_cfg_file = device_info.get_path_to_port_config_file()
if not os.path.isfile(breakout_cfg_file) or not breakout_cfg_file.endswith('.json'):
return []
else:
breakout_file_input = read_json_file(breakout_cfg_file)
if interface_name in breakout_file_input[INTF_KEY]:
breakout_mode_options = [mode for i, v in breakout_file_input[INTF_KEY].items() if i == interface_name \
for mode in v["breakout_modes"].keys()]
all_mode_options = [str(c) for c in breakout_mode_options if incomplete in c]
return all_mode_options
def _validate_interface_mode(ctx, breakout_cfg_file, interface_name, target_brkout_mode, cur_brkout_mode):
""" Validate Parent interface and user selected mode before starting deletion or addition process """
breakout_file_input = read_json_file(breakout_cfg_file)["interfaces"]
if interface_name not in breakout_file_input:
click.secho("[ERROR] {} is not a Parent port. So, Breakout Mode is not available on this port".format(interface_name), fg='red')
return False
# Check whether target breakout mode is available for the user-selected interface or not
if target_brkout_mode not in breakout_file_input[interface_name]["breakout_modes"].keys():
click.secho('[ERROR] Target mode {} is not available for the port {}'. format(target_brkout_mode, interface_name), fg='red')
return False
# Get config db context
config_db = ctx.obj['config_db']
port_dict = config_db.get_table('PORT')
# Check whether there is any port in config db.
if not port_dict:
click.echo("port_dict is None!")
return False
# Check whether the user-selected interface is part of 'port' table in config db.
if interface_name not in port_dict:
click.secho("[ERROR] {} is not in port_dict".format(interface_name))
return False
click.echo("\nRunning Breakout Mode : {} \nTarget Breakout Mode : {}".format(cur_brkout_mode, target_brkout_mode))
if (cur_brkout_mode == target_brkout_mode):
click.secho("[WARNING] No action will be taken as current and desired Breakout Mode are same.", fg='magenta')
sys.exit(0)
return True
def load_ConfigMgmt(verbose):
""" Load config for the commands which are capable of change in config DB. """
try:
cm = ConfigMgmtDPB(debug=verbose)
return cm
except Exception as e:
raise Exception("Failed to load the config. Error: {}".format(str(e)))
def breakout_warnUser_extraTables(cm, final_delPorts, confirm=True):
"""
Function to warn user about extra tables while Dynamic Port Breakout(DPB).
confirm: re-confirm from user to proceed.
Config Tables Without Yang model considered extra tables.
cm = instance of config MGMT class.
"""
try:
# check if any extra tables exist
eTables = cm.tablesWithOutYang()
if len(eTables):
# find relavent tables in extra tables, i.e. one which can have deleted
# ports
tables = cm.configWithKeys(configIn=eTables, keys=final_delPorts)
click.secho("Below Config can not be verified, It may cause harm "\
"to the system\n {}".format(json.dumps(tables, indent=2)))
click.confirm('Do you wish to Continue?', abort=True)
except Exception as e:
raise Exception("Failed in breakout_warnUser_extraTables. Error: {}".format(str(e)))
return
def breakout_Ports(cm, delPorts=list(), portJson=dict(), force=False, \
loadDefConfig=False, verbose=False):
deps, ret = cm.breakOutPort(delPorts=delPorts, portJson=portJson, \
force=force, loadDefConfig=loadDefConfig)
# check if DPB failed
if ret == False:
if not force and deps:
click.echo("Dependencies Exist. No further action will be taken")
click.echo("*** Printing dependencies ***")
for dep in deps:
click.echo(dep)
sys.exit(1)
else:
click.echo("[ERROR] Port breakout Failed!!! Opting Out")
raise click.Abort()
return
#
# Helper functions
#
def _get_device_type():
"""
Get device type
TODO: move to sonic-py-common
"""
command = [SONIC_CFGGEN_PATH, "-m", "-v", "DEVICE_METADATA.localhost.type"]
proc = subprocess.Popen(command, text=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()
return device_type
def interface_alias_to_name(config_db, interface_alias):
"""Return default interface name if alias name 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 name so the subsequent logic still applies
interface_alias = interface_alias[:sub_intf_sep_idx]
# If the input parameter config_db is None, derive it from interface.
# In single ASIC platform, get_port_namespace() returns DEFAULT_NAMESPACE.
if config_db is None:
namespace = get_port_namespace(interface_alias)
if namespace is None:
return None
config_db = ConfigDBConnector(use_unix_socket_path=True, namespace=namespace)
config_db.connect()
port_dict = config_db.get_table('PORT')
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:
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(config_db, interface_name):
"""Check if the interface name is valid
"""
# If the input parameter config_db is None, derive it from interface.
# In single ASIC platform, get_port_namespace() returns DEFAULT_NAMESPACE.
if config_db is None:
namespace = get_port_namespace(interface_name)
if namespace is None:
return False
config_db = ConfigDBConnector(use_unix_socket_path=True, namespace=namespace)
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')
loopback_dict = config_db.get_table('LOOPBACK_INTERFACE')
if clicommon.get_interface_naming_mode() == "alias":
interface_name = interface_alias_to_name(config_db, 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:
if interface_name == port_name:
return True
if port_channel_dict:
for port_channel_name in port_channel_dict:
if interface_name == port_channel_name:
return True
if sub_port_intf_dict:
for sub_port_intf_name in sub_port_intf_dict:
if interface_name == sub_port_intf_name:
return True
if loopback_dict:
for loopback_name in loopback_dict:
if interface_name == loopback_name:
return True
return False
def interface_name_to_alias(config_db, interface_name):
"""Return alias interface name if default name is given as argument
"""
# If the input parameter config_db is None, derive it from interface.
# In single ASIC platform, get_port_namespace() returns DEFAULT_NAMESPACE.
if config_db is None:
namespace = get_port_namespace(interface_name)
if namespace is None:
return None
config_db = ConfigDBConnector(use_unix_socket_path=True, namespace=namespace)
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:
if interface_name == port_name:
return port_dict[port_name]['alias']
return None
def get_interface_ipaddresses(config_db, interface_name):
"""Get IP addresses attached to interface
"""
ipaddresses = set()
table_name = get_interface_table_name(interface_name)
if not table_name:
return ipaddresses
keys = config_db.get_keys(table_name)
for key in keys:
if isinstance(key, tuple) and len(key) == 2:
iface, interface_ip = key
if iface == interface_name:
ipaddresses.add(ipaddress.ip_interface(interface_ip))
return ipaddresses
def is_vrf_exists(config_db, vrf_name):
"""Check if VRF exists
"""
keys = config_db.get_keys("VRF")
if vrf_name in keys:
return True
elif vrf_name == "mgmt" or vrf_name == "management":
entry = config_db.get_entry("MGMT_VRF_CONFIG", "vrf_global")
if entry and entry.get("mgmtVrfEnabled") == "true":
return True
return False
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 is_portchannel_name_valid(portchannel_name):
"""Port channel name validation
"""
# Return True if Portchannel name is PortChannelXXXX (XXXX can be 0-9999)
if portchannel_name[:CFG_PORTCHANNEL_PREFIX_LEN] != CFG_PORTCHANNEL_PREFIX:
return False
if (portchannel_name[CFG_PORTCHANNEL_PREFIX_LEN:].isdigit() is False or
int(portchannel_name[CFG_PORTCHANNEL_PREFIX_LEN:]) > CFG_PORTCHANNEL_MAX_VAL) :
return False
if not isInterfaceNameValid(portchannel_name):
return False
return True
def is_portchannel_present_in_db(db, portchannel_name):
"""Check if Portchannel is present in Config DB
"""
# Return True if Portchannel name exists in the CONFIG_DB
portchannel_list = db.get_table(CFG_PORTCHANNEL_PREFIX)
if portchannel_list is None:
return False
if portchannel_name in portchannel_list:
return True
return False
def is_port_member_of_this_portchannel(db, port_name, portchannel_name):
"""Check if a port is member of given portchannel
"""
portchannel_list = db.get_table(CFG_PORTCHANNEL_PREFIX)
if portchannel_list is None:
return False
for k, v in db.get_table('PORTCHANNEL_MEMBER'):
if (k == portchannel_name) and (v == port_name):
return True
return False
# Return the namespace where an interface belongs
# The port name input could be in default mode or in alias mode.
def get_port_namespace(port):
# If it is a non multi-asic platform, or if the interface is management interface
# return DEFAULT_NAMESPACE
if not multi_asic.is_multi_asic() or port == 'eth0':
return DEFAULT_NAMESPACE
# Get the table to check for interface presence
table_name = get_port_table_name(port)
if table_name == "":
return None
ns_list = multi_asic.get_all_namespaces()
namespaces = ns_list['front_ns'] + ns_list['back_ns']
for namespace in namespaces:
config_db = ConfigDBConnector(use_unix_socket_path=True, namespace=namespace)
config_db.connect()
# If the interface naming mode is alias, search the tables for alias_name.
if clicommon.get_interface_naming_mode() == "alias":
port_dict = config_db.get_table(table_name)
if port_dict:
for port_name in port_dict:
if port == port_dict[port_name]['alias']:
return namespace
else:
entry = config_db.get_entry(table_name, port)
if entry:
return namespace
return None
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:
if 'vrf_name' in interface_dict[interface_name] and vrf_name == interface_dict[interface_name]['vrf_name']:
interface_ipaddresses = get_interface_ipaddresses(config_db, interface_name)
for ipaddress in interface_ipaddresses:
remove_router_interface_ip_address(config_db, interface_name, ipaddress)
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)
# In case of multi-asic, we can check for the alias mode support in any of
# the namespaces as this setting of alias mode should be identical everywhere.
# Here by default we set the namespaces to be a list just having '' which
# represents the linux host. In case of multi-asic, we take the first namespace
# created for the front facing ASIC.
namespaces = [DEFAULT_NAMESPACE]
if multi_asic.is_multi_asic():
namespaces = multi_asic.get_all_namespaces()['front_ns']
# Ensure all interfaces have an 'alias' key in PORT dict
config_db = ConfigDBConnector(use_unix_socket_path=True, namespace=namespaces[0])
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:
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_intf_ipv6_link_local_mode(ctx, interface_name, table_name):
config_db = ctx.obj["config_db"]
intf = config_db.get_table(table_name)
if interface_name in intf:
if 'ipv6_use_link_local_only' in intf[interface_name]:
return intf[interface_name]['ipv6_use_link_local_only']
else:
return "disable"
else:
return ""
def _is_neighbor_ipaddress(config_db, ipaddress):
"""Returns True if a neighbor has the IP address <ipaddress>, False if not
"""
entry = config_db.get_entry('BGP_NEIGHBOR', ipaddress)
return True if entry else False
def _get_all_neighbor_ipaddresses(config_db):
"""Returns list of strings containing IP addresses of all BGP neighbors
"""
addrs = []
bgp_sessions = config_db.get_table('BGP_NEIGHBOR')
for addr, session in bgp_sessions.items():
addrs.append(addr)
return addrs
def _get_neighbor_ipaddress_list_by_hostname(config_db, hostname):
"""Returns list of strings, each containing an IP address of neighbor with
hostname <hostname>. Returns empty list if <hostname> not a neighbor
"""
addrs = []
bgp_sessions = config_db.get_table('BGP_NEIGHBOR')
for addr, session in bgp_sessions.items():
if 'name' in session and session['name'] == hostname:
addrs.append(addr)
return addrs
def _change_bgp_session_status_by_addr(config_db, 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.mod_entry('bgp_neighbor', ipaddress, {'admin_status': status})
def _change_bgp_session_status(config_db, 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(config_db, 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(config_db, ipaddr_or_hostname)
if not ip_addrs:
return False
for ip_addr in ip_addrs:
_change_bgp_session_status_by_addr(config_db, ip_addr, status, verbose)
return True
def _validate_bgp_neighbor(config_db, neighbor_ip_or_hostname):
"""validates whether the given ip or host name is a BGP neighbor
"""
ip_addrs = []
if _is_neighbor_ipaddress(config_db, neighbor_ip_or_hostname.lower()):
ip_addrs.append(neighbor_ip_or_hostname.lower())
else:
ip_addrs = _get_neighbor_ipaddress_list_by_hostname(config_db, neighbor_ip_or_hostname.upper())
return ip_addrs
def _remove_bgp_neighbor_config(config_db, neighbor_ip_or_hostname):
"""Removes BGP configuration of the given neighbor
"""
ip_addrs = _validate_bgp_neighbor(config_db, neighbor_ip_or_hostname)
if not ip_addrs:
return False
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))
return True
def _change_hostname(hostname):
current_hostname = os.uname()[1]
if current_hostname != hostname:
with open('/etc/hostname', 'w') as f:
f.write(str(hostname) + '\n')
clicommon.run_command(['hostname', '-F', '/etc/hostname'], display_cmd=True)
clicommon.run_command(['sed', '-i', r"/\s{}$/d".format(current_hostname), '/etc/hosts'], display_cmd=True)
with open('/etc/hosts', 'a') as f:
f.write("127.0.0.1 " + str(hostname) + '\n')
def _clear_cbf():
CBF_TABLE_NAMES = [
'DSCP_TO_FC_MAP',
'EXP_TO_FC_MAP']
namespace_list = [DEFAULT_NAMESPACE]
if multi_asic.get_num_asics() > 1:
namespace_list = multi_asic.get_namespaces_from_linux()
for ns in namespace_list:
if ns is DEFAULT_NAMESPACE:
config_db = ConfigDBConnector()
else:
config_db = ConfigDBConnector(
use_unix_socket_path=True, namespace=ns
)
config_db.connect()
for cbf_table in CBF_TABLE_NAMES:
config_db.delete_table(cbf_table)
#API to validate the interface passed for storm-control configuration
def storm_control_interface_validate(port_name):
if clicommon.get_interface_naming_mode() == "alias":
port_name = interface_alias_to_name(None, port_name)
if port_name is None:
click.echo("'port_name' is None!")
return False
if (port_name.startswith("Ethernet")):
if interface_name_is_valid(None, port_name) is False:
click.echo("Interface name %s is invalid. Please enter a valid interface name" %(port_name))
return False
else:
click.echo("Storm-control is supported only on Ethernet interfaces. Not supported on %s" %(port_name))
return False
return True
def is_storm_control_supported(storm_type, namespace):
asic_id = multi_asic.get_asic_index_from_namespace(namespace)
#state_db[asic_id] = swsscommon.DBConnector("STATE_DB", REDIS_TIMEOUT_MSECS, True, namespace)
#supported = state_db[asic_id].get_entry('BUM_STORM_CAPABILITY', storm_type)
state_db = SonicV2Connector(host='127.0.0.1')
state_db.connect(state_db.STATE_DB, False)
entry_name="BUM_STORM_CAPABILITY|"+storm_type
supported = state_db.get(state_db.STATE_DB, entry_name,"supported")
return supported
#API to configure the PORT_STORM_CONTROL table
def storm_control_set_entry(port_name, kbps, storm_type, namespace):
if storm_control_interface_validate(port_name) is False:
return False
if is_storm_control_supported(storm_type, namespace) == 0:
click.echo("Storm-control is not supported on this namespace {}".format(namespace))
return False
#Validate kbps value
config_db = ValidatedConfigDBConnector(ConfigDBConnector())
config_db.connect()
key = port_name + '|' + storm_type
entry = config_db.get_entry('PORT_STORM_CONTROL', key)
if len(entry) == 0:
try:
config_db.set_entry('PORT_STORM_CONTROL', key, {'kbps':kbps})
except ValueError as e:
ctx = click.get_current_context()
ctx.fail("Invalid ConfigDB. Error: {}".format(e))
else:
kbps_value = int(entry.get('kbps',0))
if kbps_value != kbps:
try:
config_db.mod_entry('PORT_STORM_CONTROL', key, {'kbps':kbps})
except ValueError as e:
ctx = click.get_current_context()
ctx.fail("Invalid ConfigDB. Error: {}".format(e))
return True
#API to remove an entry from PORT_STORM_CONTROL table
def storm_control_delete_entry(port_name, storm_type):
if storm_control_interface_validate(port_name) is False:
return False
config_db = ValidatedConfigDBConnector(ConfigDBConnector())
config_db.connect()
key = port_name + '|' + storm_type
entry = config_db.get_entry('PORT_STORM_CONTROL', key)
if len(entry) == 0:
click.echo("%s storm-control not enabled on interface %s" %(storm_type, port_name))
return False
else:
try:
config_db.set_entry('PORT_STORM_CONTROL', key, None)
except JsonPatchConflict as e:
ctx = click.get_current_context()
ctx.fail("Invalid ConfigDB. Error: {}".format(e))
return True
def _wait_until_clear(tables, interval=0.5, timeout=30, verbose=False):
start = time.time()
empty = False
app_db = SonicV2Connector(host='127.0.0.1')
app_db.connect(app_db.APPL_DB)
while not empty and time.time() - start < timeout:
non_empty_table_count = 0
for table in tables:
keys = app_db.keys(app_db.APPL_DB, table)
if keys:
non_empty_table_count += 1
if verbose:
click.echo("Some entries matching {} still exist: {}".format(table, keys[0]))
time.sleep(interval)
empty = (non_empty_table_count == 0)
if not empty:
click.echo("Operation not completed successfully, please save and reload configuration.")
return empty
def _clear_qos(delay=False, verbose=False):
QOS_TABLE_NAMES = [
'PORT_QOS_MAP',
'QUEUE',
'TC_TO_PRIORITY_GROUP_MAP',
'MAP_PFC_PRIORITY_TO_QUEUE',
'TC_TO_QUEUE_MAP',
'DSCP_TO_TC_MAP',
'MPLS_TC_TO_TC_MAP',
'SCHEDULER',
'PFC_PRIORITY_TO_PRIORITY_GROUP_MAP',
'WRED_PROFILE',
'CABLE_LENGTH',
'BUFFER_PG',
'BUFFER_QUEUE',
'BUFFER_PORT_INGRESS_PROFILE_LIST',
'BUFFER_PORT_EGRESS_PROFILE_LIST',
'BUFFER_PROFILE',
'BUFFER_POOL',
'DEFAULT_LOSSLESS_BUFFER_PARAMETER',
'LOSSLESS_TRAFFIC_PATTERN']
namespace_list = [DEFAULT_NAMESPACE]
if multi_asic.get_num_asics() > 1:
namespace_list = multi_asic.get_namespaces_from_linux()
for ns in namespace_list:
if ns is DEFAULT_NAMESPACE:
config_db = ConfigDBConnector()
else:
config_db = ConfigDBConnector(
use_unix_socket_path=True, namespace=ns
)
config_db.connect()
for qos_table in QOS_TABLE_NAMES:
config_db.delete_table(qos_table)
if delay:
device_metadata = config_db.get_entry('DEVICE_METADATA', 'localhost')
# Traditional buffer manager do not remove buffer tables in any case, no need to wait.
timeout = 120 if device_metadata and device_metadata.get('buffer_model') == 'dynamic' else 0
_wait_until_clear(["BUFFER_*_TABLE:*", "BUFFER_*_SET"], interval=0.5, timeout=timeout, verbose=verbose)
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 _get_disabled_services_list(config_db):
disabled_services_list = []
feature_table = config_db.get_table('FEATURE')
if feature_table is not None:
for feature_name in feature_table:
if not feature_name:
log.log_warning("Feature is None")
continue
state = feature_table[feature_name]['state']
if not state:
log.log_warning("Enable state of feature '{}' is None".format(feature_name))
continue
if state == "disabled":
disabled_services_list.append(feature_name)
else:
log.log_warning("Unable to retreive FEATURE table")
return disabled_services_list
def _stop_services():
try:
subprocess.check_call(['sudo', 'monit', 'status'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
click.echo("Disabling container monitoring ...")
clicommon.run_command(['sudo', 'monit', 'unmonitor', 'container_checker'])
except subprocess.CalledProcessError as err:
pass
click.echo("Stopping SONiC target ...")
clicommon.run_command(['sudo', 'systemctl', 'stop', 'sonic.target', '--job-mode', 'replace-irreversibly'])
def _get_sonic_services():
cmd = ['systemctl', 'list-dependencies', '--plain', 'sonic.target']
out, _ = clicommon.run_command(cmd, return_cmd=True)
out = out.strip().split('\n')[1:]
return (unit.strip() for unit in out)
def _reset_failed_services():
for service in _get_sonic_services():
clicommon.run_command(['systemctl', 'reset-failed', str(service)])
def get_service_finish_timestamp(service):
out, _ = clicommon.run_command(['sudo',
'systemctl',
'show',
'--no-pager',
service,
'-p',
'ExecMainExitTimestamp',
'--value'],
return_cmd=True)
return out.strip(' \t\n\r')
def wait_service_restart_finish(service, last_timestamp, timeout=30):
start_time = time.time()
elapsed_time = 0
while elapsed_time < timeout:
current_timestamp = get_service_finish_timestamp(service)
if current_timestamp and (current_timestamp != last_timestamp):
return
time.sleep(1)
elapsed_time = time.time() - start_time
log.log_warning("Service: {} does not restart in {} seconds, stop waiting".format(service, timeout))
def _restart_services():
last_interface_config_timestamp = get_service_finish_timestamp('interfaces-config')
last_networking_timestamp = get_service_finish_timestamp('networking')
click.echo("Restarting SONiC target ...")
clicommon.run_command(['sudo', 'systemctl', 'restart', 'sonic.target'])
# These service will restart eth0 and cause device lost network for 10 seconds
# When enable TACACS, every remote user commands will authorize by TACACS service via network
# If load_minigraph exit before eth0 restart, commands after load_minigraph may failed
wait_service_restart_finish('interfaces-config', last_interface_config_timestamp)
wait_service_restart_finish('networking', last_networking_timestamp)
try:
subprocess.check_call(['sudo', 'monit', 'status'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
click.echo("Enabling container monitoring ...")
clicommon.run_command(['sudo', 'monit', 'monitor', 'container_checker'])
except subprocess.CalledProcessError as err:
pass
# Reload Monit configuration to pick up new hostname in case it changed
click.echo("Reloading Monit configuration ...")
clicommon.run_command(['sudo', 'monit', 'reload'])
def _per_namespace_swss_ready(service_name):
out, _ = clicommon.run_command(['systemctl', 'show', str(service_name), '--property', 'ActiveState', '--value'], return_cmd=True)
if out.strip() != "active":
return False
out, _ = clicommon.run_command(['systemctl', 'show', str(service_name), '--property', 'ActiveEnterTimestampMonotonic', '--value'], return_cmd=True)
swss_up_time = float(out.strip())/1000000
now = time.monotonic()
if (now - swss_up_time > 120):
return True
else:
return False
def _swss_ready():
list_of_swss = []
num_asics = multi_asic.get_num_asics()
if num_asics == 1:
list_of_swss.append("swss.service")
else:
for asic in range(num_asics):
service = "swss@{}.service".format(asic)
list_of_swss.append(service)
for service_name in list_of_swss:
if _per_namespace_swss_ready(service_name) == False:
return False
return True
def _is_system_starting():
out, _ = clicommon.run_command(['sudo', 'systemctl', 'is-system-running'], return_cmd=True)
return out.strip() == "starting"
def interface_is_in_vlan(vlan_member_table, interface_name):
""" Check if an interface is in a vlan """
for _, intf in vlan_member_table:
if intf == interface_name:
return True