-
Notifications
You must be signed in to change notification settings - Fork 539
/
conftest.py
2026 lines (1655 loc) · 74.8 KB
/
conftest.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
import os
import re
import time
import json
import redis
import docker
import pytest
import random
import string
import subprocess
import sys
import tarfile
import io
import traceback
from typing import Dict, Tuple
from datetime import datetime
from swsscommon import swsscommon
from dvslib.dvs_database import DVSDatabase
from dvslib.dvs_common import PollingConfig, wait_for_result
from dvslib.dvs_acl import DVSAcl
from dvslib.dvs_pbh import DVSPbh
from dvslib.dvs_route import DVSRoute
from dvslib import dvs_vlan
from dvslib import dvs_port
from dvslib import dvs_lag
from dvslib import dvs_mirror
from dvslib import dvs_policer
from dvslib import dvs_hash
from dvslib import dvs_switch
from dvslib import dvs_twamp
from buffer_model import enable_dynamic_buffer
# FIXME: For the sake of stabilizing the PR pipeline we currently assume there are 32 front-panel
# ports in the system (much like the rest of the test suite). This should be adjusted to accomodate
# a dynamic number of ports. GitHub Issue: Azure/sonic-swss#1384.
NUM_PORTS = 32
# Voq asics will have 16 fabric ports created (defined in Azure/sonic-buildimage#7629).
FABRIC_NUM_PORTS = 16
def ensure_system(cmd):
rc, output = subprocess.getstatusoutput(cmd)
if rc:
raise RuntimeError(f"Failed to run command: {cmd}. rc={rc}. output: {output}")
def pytest_addoption(parser):
parser.addoption("--dvsname",
action="store",
default=None,
help="Name of a persistent DVS container to run the tests with. Mutually exclusive with --force-recreate-dvs")
parser.addoption("--forcedvs",
action="store_true",
default=False,
help="Force tests to run in persistent DVS containers with <32 ports")
parser.addoption("--force-recreate-dvs",
action="store_true",
default=False,
help="Force the DVS container to be recreated between each test module. Mutually exclusive with --dvsname")
parser.addoption("--keeptb",
action="store_true",
default=False,
help="Keep testbed running after tests for debugging purposes")
parser.addoption("--imgname",
action="store",
default="docker-sonic-vs:latest",
help="Name of an image to use for the DVS container")
parser.addoption("--max_cpu",
action="store",
default=2,
type=int,
help="Max number of CPU cores to use, if available. (default = 2)")
parser.addoption("--vctns",
action="store",
default=None,
help="Namespace for the Virtual Chassis Topology")
parser.addoption("--topo",
action="store",
default=None,
help="Topology file for the Virtual Chassis Topology")
parser.addoption("--buffer_model",
action="store",
default="traditional",
help="Buffer model")
parser.addoption("--graceful-stop",
action="store_true",
default=False,
help="Stop swss and syncd before stopping a conatainer")
parser.addoption("--num-ports",
action="store",
default=NUM_PORTS,
type=int,
help="number of ports")
parser.addoption("--enable-coverage",
action="store_true",
default=False,
help="Collect the test coverage information")
def random_string(size=4, chars=string.ascii_uppercase + string.digits):
return "".join(random.choice(chars) for x in range(size))
class AsicDbValidator(DVSDatabase):
def __init__(self, db_id: int, connector: str, switch_type: str):
DVSDatabase.__init__(self, db_id, connector)
if switch_type not in ['fabric']:
self._wait_for_asic_db_to_initialize()
self._populate_default_asic_db_values()
self._generate_oid_to_interface_mapping()
def _wait_for_asic_db_to_initialize(self) -> None:
"""Wait up to 30 seconds for the default fields to appear in ASIC DB."""
def _verify_db_contents():
# We expect only the default VLAN
if len(self.get_keys("ASIC_STATE:SAI_OBJECT_TYPE_VLAN")) != 1:
return (False, None)
if len(self.get_keys("ASIC_STATE:SAI_OBJECT_TYPE_HOSTIF")) < NUM_PORTS:
return (False, None)
if len(self.get_keys("ASIC_STATE:SAI_OBJECT_TYPE_ACL_ENTRY")) != 0:
return (False, None)
return (True, None)
# Verify that ASIC DB has been fully initialized
init_polling_config = PollingConfig(2, 30, strict=True)
wait_for_result(_verify_db_contents, init_polling_config)
def _generate_oid_to_interface_mapping(self) -> None:
"""Generate the OID->Name mappings for ports and host interfaces."""
self.portoidmap = {}
self.portnamemap = {}
self.hostifoidmap = {}
self.hostifnamemap = {}
host_intfs = self.get_keys("ASIC_STATE:SAI_OBJECT_TYPE_HOSTIF")
for intf in host_intfs:
fvs = self.get_entry("ASIC_STATE:SAI_OBJECT_TYPE_HOSTIF", intf)
port_oid = fvs.get("SAI_HOSTIF_ATTR_OBJ_ID")
port_name = fvs.get("SAI_HOSTIF_ATTR_NAME")
self.portoidmap[port_oid] = port_name
self.portnamemap[port_name] = port_oid
self.hostifoidmap[intf] = port_name
self.hostifnamemap[port_name] = intf
def _populate_default_asic_db_values(self) -> None:
# Get default .1Q Vlan ID
self.default_vlan_id = self.get_keys("ASIC_STATE:SAI_OBJECT_TYPE_VLAN")[0]
self.default_acl_tables = self.get_keys("ASIC_STATE:SAI_OBJECT_TYPE_ACL_TABLE")
self.default_acl_entries = self.get_keys("ASIC_STATE:SAI_OBJECT_TYPE_ACL_ENTRY")
self.default_hash_keys = self.get_keys("ASIC_STATE:SAI_OBJECT_TYPE_HASH")
self.default_switch_keys = self.get_keys("ASIC_STATE:SAI_OBJECT_TYPE_SWITCH")
self.default_copp_policers = self.get_keys("ASIC_STATE:SAI_OBJECT_TYPE_POLICER")
class ApplDbValidator(DVSDatabase):
NEIGH_TABLE = "NEIGH_TABLE"
def __init__(self, db_id: int, connector: str):
DVSDatabase.__init__(self, db_id, connector)
def __del__(self):
# Make sure no neighbors on physical interfaces
neighbors = self.get_keys(self.NEIGH_TABLE)
for neighbor in neighbors:
m = re.match(r"eth(\d+)", neighbor)
if not m:
continue
assert int(m.group(1)) > 0
class VirtualServer:
def __init__(self, ctn_name: str, pid: int, i: int):
self.nsname = f"{ctn_name}-srv{i}"
self.pifname = f"eth{i + 1}"
self.cleanup = True
# create netns
if os.path.exists(os.path.join("/var/run/netns/", self.nsname)):
self.kill_all_processes()
self.cleanup = False
else:
ensure_system(f"ip netns add {self.nsname}")
# create vpeer link
ensure_system(
f"ip netns exec {self.nsname} ip link add {self.nsname[0:12]}"
f" type veth peer name {self.pifname}"
)
# ensure self.pifname is not already an interface in the DVS net namespace
rc, _ = subprocess.getstatusoutput(f"nsenter -t {pid} -n ip link show | grep '{self.pifname}@'")
if not rc:
try:
ensure_system(f"nsenter -t {pid} -n ip link delete {self.pifname}")
except RuntimeError as e:
# Occasionally self.pifname will get deleted between us checking for its existence
# and us deleting it ourselves. In this case we can continue normally
if "cannot find device" in str(e).lower():
pass
else:
raise e
ensure_system(f"ip netns exec {self.nsname} ip link set {self.pifname} netns {pid}")
# bring up link in the virtual server
ensure_system(f"ip netns exec {self.nsname} ip link set dev {self.nsname[0:12]} name eth0")
ensure_system(f"ip netns exec {self.nsname} ip link set dev eth0 up")
ensure_system(f"ip netns exec {self.nsname} ethtool -K eth0 tx off")
# bring up link in the virtual switch
ensure_system(f"nsenter -t {pid} -n ip link set dev {self.pifname} up")
# disable arp, so no neigh on physical interfaces
ensure_system(f"nsenter -t {pid} -n ip link set arp off dev {self.pifname}")
ensure_system(f"nsenter -t {pid} -n sysctl -w net.ipv6.conf.{self.pifname}.disable_ipv6=1")
def __repr__(self):
return f'<VirtualServer> {self.nsname}'
def kill_all_processes(self) -> None:
pids = subprocess.check_output(f"ip netns pids {self.nsname}", shell=True).decode("utf-8")
if pids:
for pid in pids.split('\n'):
if len(pid) > 0:
os.system(f"kill {pid}")
def destroy(self) -> None:
if self.cleanup:
self.kill_all_processes()
ensure_system(f"ip netns delete {self.nsname}")
def runcmd(self, cmd: str) -> int:
try:
subprocess.check_output(f"ip netns exec {self.nsname} {cmd}", stderr=subprocess.STDOUT, shell=True)
except subprocess.CalledProcessError as e:
print(f"------rc={e.returncode} for cmd: {e.cmd}------")
print(e.output.rstrip())
print("------")
return e.returncode
return 0
# used in buildimage tests, do not delete
def runcmd_async(self, cmd: str) -> subprocess.Popen:
return subprocess.Popen(f"ip netns exec {self.nsname} {cmd}", shell=True)
def runcmd_output(self, cmd: str) -> str:
return subprocess.check_output(f"ip netns exec {self.nsname} {cmd}", shell=True).decode("utf-8")
class DockerVirtualSwitch:
APPL_DB_ID = 0
ASIC_DB_ID = 1
COUNTERS_DB_ID = 2
CONFIG_DB_ID = 4
FLEX_COUNTER_DB_ID = 5
STATE_DB_ID = 6
# FIXME: Should be broken up into helper methods in a later PR.
def __init__(
self,
name: str = None,
imgname: str = None,
keeptb: bool = False,
env: list = [],
log_path: str = None,
max_cpu: int = 2,
forcedvs: bool = None,
vct: str = None,
newctnname: str = None,
ctnmounts: Dict[str, str] = None,
buffer_model: str = None,
enable_coverage: bool = False
):
self.basicd = ["redis-server", "rsyslogd"]
self.swssd = [
"orchagent",
"intfmgrd",
"neighsyncd",
"portsyncd",
"vlanmgrd",
"vrfmgrd",
"portmgrd"
]
self.syncd = ["syncd"]
self.rtd = ["fpmsyncd", "zebra", "staticd", "mgmtd"]
self.teamd = ["teamsyncd", "teammgrd"]
self.natd = ["natsyncd", "natmgrd"]
self.alld = self.basicd + self.swssd + self.syncd + self.rtd + self.teamd + self.natd
self.log_path = log_path
self.dvsname = name
self.vct = vct
self.ctn = None
self.enable_coverage = enable_coverage
self.cleanup = not keeptb
ctn_sw_id = -1
ctn_sw_name = None
self.persistent = False
self.client = docker.from_env()
# Use the provided persistent DVS testbed
if name:
# get virtual switch container
for ctn in self.client.containers.list():
if ctn.name == name:
self.ctn = ctn
_, output = subprocess.getstatusoutput(f"docker inspect --format '{{{{.HostConfig.NetworkMode}}}}' {name}")
ctn_sw_id = output.split(':')[1]
# Persistent DVS is available.
self.cleanup = False
self.persistent = True
if not self.ctn:
raise NameError(f"cannot find container {name}")
num_net_interfaces = self.net_interface_count()
if num_net_interfaces > NUM_PORTS:
raise ValueError(f"persistent dvs is not valid for testbed with ports > {NUM_PORTS}")
if num_net_interfaces < NUM_PORTS and not forcedvs:
raise ValueError(f"persistent dvs does not have {NUM_PORTS} ports needed by testbed")
# get base container
for ctn in self.client.containers.list():
if ctn.id == ctn_sw_id or ctn.name == ctn_sw_id:
ctn_sw_name = ctn.name
if ctn_sw_name:
_, output = subprocess.getstatusoutput(f"docker inspect --format '{{{{.State.Pid}}}}' {ctn_sw_name}")
self.ctn_sw_pid = int(output)
# create virtual servers
self.servers = []
for i in range(NUM_PORTS):
server = VirtualServer(ctn_sw_name, self.ctn_sw_pid, i)
self.servers.append(server)
self.mount = f"/var/run/redis-vs/{ctn_sw_name}"
else:
self.mount = "/var/run/redis-vs/{}".format(name)
self.net_cleanup()
# As part of https://github.com/Azure/sonic-buildimage/pull/4499
# VS support dynamically create Front-panel ports so save the orginal
# config db for persistent DVS
self.runcmd("mv /etc/sonic/config_db.json /etc/sonic/config_db.json.orig")
self.ctn_restart()
# Dynamically create a DVS container and servers
else:
self.ctn_sw = self.client.containers.run("debian:jessie",
privileged=True,
detach=True,
command="bash",
stdin_open=True)
_, output = subprocess.getstatusoutput(f"docker inspect --format '{{{{.State.Pid}}}}' {self.ctn_sw.name}")
self.ctn_sw_pid = int(output)
# create virtual server
self.servers = []
self.create_servers()
if self.vct:
self.vct_connect(newctnname)
# mount redis to base to unique directory
self.mount = f"/var/run/redis-vs/{self.ctn_sw.name}"
ensure_system(f"mkdir -p {self.mount}")
kwargs = {}
if newctnname:
kwargs["name"] = newctnname
self.dvsname = newctnname
vols = {self.mount: {"bind": "/var/run/redis", "mode": "rw"}}
if ctnmounts:
for k, v in ctnmounts.items():
vols[k] = v
kwargs["volumes"] = vols
# create virtual switch container
self.ctn = self.client.containers.run(imgname,
privileged=True,
detach=True,
environment=env,
network_mode=f"container:{self.ctn_sw.name}",
cpu_count=max_cpu,
**kwargs)
_, output = subprocess.getstatusoutput(f"docker inspect --format '{{{{.State.Pid}}}}' {self.ctn.name}")
self.pid = int(output)
self.redis_sock = os.path.join(self.mount, "redis.sock")
self.redis_chassis_sock = os.path.join(self.mount, "redis_chassis.sock")
self.reset_dbs()
# Make sure everything is up and running before turning over control to the caller
self.check_ready_status_and_init_db()
# Switch buffer model to dynamic if necessary
if buffer_model == 'dynamic':
enable_dynamic_buffer(self.get_config_db(), self.runcmd)
def create_servers(self):
for i in range(NUM_PORTS):
server = VirtualServer(self.ctn_sw.name, self.ctn_sw_pid, i)
self.servers.append(server)
def reset_dbs(self):
# DB wrappers are declared here, lazy-loaded in the tests
self.app_db = None
self.asic_db = None
self.counters_db = None
self.config_db = None
self.flex_db = None
self.state_db = None
def del_appl_db(self):
# APPL DB may not always exist, so use this helper method to check before deleting
if getattr(self, 'appldb', False):
del self.appldb
def collect_coverage(self):
if not self.enable_coverage:
return
try:
# Generate the gcda files
self.runcmd('killall5 -15')
time.sleep(1)
# Stop the services to reduce the CPU comsuption
if self.cleanup:
self.runcmd('supervisorctl stop all')
# Generate the converage info by lcov and copy to the host
cmd = f"docker exec {self.ctn.short_id} sh -c 'cd $BUILD_DIR; rm -rf **/.libs ./lib/libSaiRedis*; lcov -c --directory . --no-external --exclude tests --ignore-errors gcov,unused --output-file /tmp/coverage.info; sed -i \"s#SF:$BUILD_DIR/#SF:#\" /tmp/coverage.info; lcov_cobertura /tmp/coverage.info -o /tmp/coverage.xml'"
subprocess.getstatusoutput(cmd)
cmd = f"docker exec {self.ctn.short_id} sh -c 'cd $BUILD_DIR; find . -name *.gcda -type f -exec tar -rf /tmp/gcda.tar {{}} \\;'"
subprocess.getstatusoutput(cmd)
cmd = f"docker cp {self.ctn.short_id}:/tmp/gcda.tar {self.ctn.short_id}.gcda.tar"
subprocess.getstatusoutput(cmd)
cmd = f"docker cp {self.ctn.short_id}:/tmp/coverage.info {self.ctn.short_id}.coverage.info"
subprocess.getstatusoutput(cmd)
cmd = f"docker cp {self.ctn.short_id}:/tmp/coverage.xml {self.ctn.short_id}.coverage.xml"
subprocess.getstatusoutput(cmd)
except:
traceback.print_exc()
def destroy(self) -> None:
self.del_appl_db()
self.collect_coverage()
# In case persistent dvs was used removed all the extra server link
# that were created
if self.persistent:
self.destroy_servers()
# persistent and clean-up flag are mutually exclusive
elif self.cleanup:
try:
self.ctn.remove(force=True)
self.ctn_sw.remove(force=True)
os.system(f"rm -rf {self.mount}")
self.destroy_servers()
except docker.errors.NotFound:
print("Skipped the container not found error, the container has already removed.")
def destroy_servers(self):
for s in self.servers:
s.destroy()
self.servers = []
def check_ready_status_and_init_db(self) -> None:
try:
# temp fix: remove them once they are moved to vs start.sh
self.ctn.exec_run("sysctl -w net.ipv6.conf.default.disable_ipv6=0")
for i in range(0, 128, 4):
self.ctn.exec_run(f"sysctl -w net.ipv6.conf.eth{i + 1}.disable_ipv6=1")
# Verify that all of the device services have started.
self.check_services_ready()
# Initialize the databases.
self.init_asic_db_validator()
self.init_appl_db_validator()
self.reset_dbs()
# Verify that SWSS has finished initializing.
self.check_swss_ready()
except Exception:
self.get_logs()
self.destroy()
raise
def check_services_ready(self, timeout=60) -> None:
"""Check if all processes in the DVS are ready."""
service_polling_config = PollingConfig(1, timeout, strict=True)
def _polling_function():
res = self.ctn.exec_run("supervisorctl status")
out = res.output.decode("utf-8")
process_status = {}
for line in out.splitlines():
tokens = line.split()
if len(tokens) < 2:
continue
process_status[tokens[0]] = tokens[1]
for pname in self.alld:
if process_status.get(pname, None) != "RUNNING":
return (False, process_status)
return (process_status.get("start.sh", None) == "EXITED", process_status)
wait_for_result(_polling_function, service_polling_config)
def init_asic_db_validator(self) -> None:
self.get_config_db()
metadata = self.config_db.get_entry('DEVICE_METADATA|localhost', '')
self.asicdb = AsicDbValidator(self.ASIC_DB_ID, self.redis_sock, metadata.get("switch_type"))
def init_appl_db_validator(self) -> None:
self.appldb = ApplDbValidator(self.APPL_DB_ID, self.redis_sock)
def check_swss_ready(self, timeout: int = 300) -> None:
"""Verify that SWSS is ready to receive inputs.
Almost every part of orchagent depends on ports being created and initialized
before they can proceed with their processing. If we start the tests after orchagent
has started running but before it has had time to initialize all the ports, then the
first several tests will fail.
"""
num_ports = NUM_PORTS
# Voq and fabric asics have fabric ports enabled
self.get_config_db()
metadata = self.config_db.get_entry('DEVICE_METADATA|localhost', '')
if metadata.get('switch_type', 'npu') in ['voq', 'fabric']:
num_ports = NUM_PORTS + FABRIC_NUM_PORTS
# Verify that all ports have been initialized and configured
app_db = self.get_app_db()
startup_polling_config = PollingConfig(5, timeout, strict=True)
def _polling_function():
port_table_keys = app_db.get_keys("PORT_TABLE")
return ("PortInitDone" in port_table_keys and "PortConfigDone" in port_table_keys, None)
if metadata.get('switch_type') not in ['fabric']:
wait_for_result(_polling_function, startup_polling_config)
# Verify that all ports have been created
if metadata.get('switch_type') not in ['fabric']:
asic_db = self.get_asic_db()
asic_db.wait_for_n_keys("ASIC_STATE:SAI_OBJECT_TYPE_PORT", num_ports + 1) # +1 CPU Port
# Verify that fabric ports are monitored in STATE_DB
if metadata.get('switch_type', 'npu') in ['voq', 'fabric']:
self.get_state_db()
self.state_db.wait_for_n_keys("FABRIC_PORT_TABLE", FABRIC_NUM_PORTS)
def net_cleanup(self) -> None:
"""Clean up network, remove extra links."""
re_space = re.compile(r'\s+')
res = self.ctn.exec_run("ip link show")
out = res.output.decode("utf-8")
for line in out.splitlines():
m = re.compile(r'^\d+').match(line)
if not m:
continue
fds = re_space.split(line)
if len(fds) > 1:
pname = fds[1].rstrip(":")
m = re.compile("(eth|lo|Bridge|Ethernet|vlan|inband)").match(pname)
if not m:
self.ctn.exec_run(f"ip link del {pname}")
print(f"remove extra link {pname}")
def net_interface_count(self) -> int:
"""Get the interface count in persistent DVS Container.
Returns:
The interface count, or 0 if the value is not found or some error occurs.
"""
res = self.ctn.exec_run(["sh", "-c", "ip link show | grep -oE eth[0-9]+ | grep -vc eth0"])
if not res.exit_code:
out = res.output.decode("utf-8")
return int(out.rstrip('\n'))
else:
return 0
def vct_connect(self, ctnname: str) -> None:
data = self.vct.get_inband(ctnname)
if "inband_address" in data:
ifpair = data["inband_intf_pair"]
ifname = data["inband_intf"]
iaddr = data["inband_address"]
self.vct.connect(ifname, ifpair, str(self.ctn_sw_pid))
self.ctn_sw.exec_run(f"ip link set dev {ifpair} up")
self.ctn_sw.exec_run(f"ip link add link {ifpair} name vlan4094 type vlan id 4094")
self.ctn_sw.exec_run(f"ip addr add {iaddr} dev vlan4094")
self.ctn_sw.exec_run("ip link set dev vlan4094 up")
def ctn_restart(self) -> None:
self.ctn.restart()
def restart(self) -> None:
self.del_appl_db()
self.ctn_restart()
self.check_ready_status_and_init_db()
def runcmd(self, cmd: str, include_stderr=True) -> Tuple[int, str]:
res = self.ctn.exec_run(cmd, stdout=True, stderr=include_stderr)
exitcode = res.exit_code
out = res.output.decode("utf-8")
if exitcode != 0:
print(f"-----rc={exitcode} for cmd {cmd}-----")
print(out.rstrip())
print("-----")
return (exitcode, out)
# used in buildimage tests, do not delete
def copy_file(self, path: str, filename: str) -> None:
tarstr = io.BytesIO()
tar = tarfile.open(fileobj=tarstr, mode="w")
tar.add(filename, os.path.basename(filename))
tar.close()
self.ctn.exec_run(f"mkdir -p {path}")
self.ctn.put_archive(path, tarstr.getvalue())
tarstr.close()
def get_logs(self) -> None:
log_dir = os.path.join("log", self.log_path) if self.log_path else "log"
ensure_system(f"rm -rf {log_dir}")
ensure_system(f"mkdir -p {log_dir}")
p = subprocess.Popen(["tar", "--no-same-owner", "--exclude", "README", "-C", os.path.join("./", log_dir), "-x"], stdin=subprocess.PIPE)
stream, _ = self.ctn.get_archive("/var/log/")
for x in stream:
p.stdin.write(x)
p.stdin.close()
p.wait()
if p.returncode:
raise RuntimeError("Failed to unpack the log archive.")
ensure_system("chmod a+r -R log")
def add_log_marker(self, file_name=None) -> str:
marker = f"=== start marker {datetime.now().isoformat()} ==="
if file_name:
self.runcmd(["sh", "-c", f"echo \"{marker}\" >> {file_name}"])
else:
self.ctn.exec_run(f"logger {marker}")
return marker
# start processes in SWSS
# deps: acl, fdb, port_an, port_config, warm_reboot
def start_swss(self):
cmd = ""
for pname in self.swssd:
cmd += "supervisorctl start {}; ".format(pname)
self.runcmd(['sh', '-c', cmd])
time.sleep(5)
# stop processes in SWSS
# deps: acl, fdb, port_an, port_config, warm_reboot
def stop_swss(self):
cmd = ""
for pname in self.swssd:
cmd += "supervisorctl stop {}; ".format(pname)
self.runcmd(['sh', '-c', cmd])
time.sleep(5)
def stop_syncd(self):
self.runcmd(['sh', '-c', 'supervisorctl stop syncd'])
time.sleep(5)
# deps: warm_reboot
def start_zebra(self):
self.runcmd(['sh', '-c', 'supervisorctl start zebra'])
# Let's give zebra a chance to connect to FPM.
time.sleep(5)
# deps: warm_reboot
def stop_zebra(self):
self.runcmd(['sh', '-c', 'pkill -9 zebra'])
time.sleep(5)
# deps: warm_reboot
def start_fpmsyncd(self):
self.runcmd(['sh', '-c', 'supervisorctl start fpmsyncd'])
# Let's give fpmsyncd a chance to connect to Zebra.
time.sleep(5)
# deps: warm_reboot
def stop_fpmsyncd(self):
self.runcmd(['sh', '-c', 'pkill -x fpmsyncd'])
time.sleep(1)
# deps: warm_reboot
def SubscribeAppDbObject(self, objpfx):
r = redis.Redis(unix_socket_path=self.redis_sock, db=swsscommon.APPL_DB,
encoding="utf-8", decode_responses=True)
pubsub = r.pubsub()
pubsub.psubscribe("__keyspace@0__:%s*" % objpfx)
return pubsub
# deps: warm_reboot
def SubscribeAsicDbObject(self, objpfx):
r = redis.Redis(unix_socket_path=self.redis_sock, db=swsscommon.ASIC_DB,
encoding="utf-8", decode_responses=True)
pubsub = r.pubsub()
pubsub.psubscribe("__keyspace@1__:ASIC_STATE:%s*" % objpfx)
return pubsub
# deps: warm_reboot
def CountSubscribedObjects(self, pubsub, ignore=None, timeout=10):
nadd = 0
ndel = 0
idle = 0
while True and idle < timeout:
message = pubsub.get_message()
if message:
print(message)
if ignore:
fds = message['channel'].split(':')
if fds[2] in ignore:
continue
if message['data'] == 'hset':
nadd += 1
elif message['data'] == 'del':
ndel += 1
idle = 0
else:
time.sleep(1)
idle += 1
return (nadd, ndel)
# deps: warm_reboot
def GetSubscribedAppDbObjects(self, pubsub, ignore=None, timeout=10):
r = redis.Redis(unix_socket_path=self.redis_sock, db=swsscommon.APPL_DB,
encoding="utf-8", decode_responses=True)
addobjs = []
delobjs = []
idle = 0
prev_key = None
while True and idle < timeout:
message = pubsub.get_message()
if message:
print(message)
key = message['channel'].split(':', 1)[1]
# In producer/consumer_state_table scenarios, every entry will
# show up twice for every push/pop operation, so skip the second
# one to avoid double counting.
if key != None and key == prev_key:
continue
# Skip instructions with meaningless keys. To be extended in the
# future to other undesired keys.
if key == "ROUTE_TABLE_KEY_SET" or key == "ROUTE_TABLE_DEL_SET":
continue
if ignore:
fds = message['channel'].split(':')
if fds[2] in ignore:
continue
if message['data'] == 'hset':
(_, k) = key.split(':', 1)
value=r.hgetall(key)
addobjs.append({'key':json.dumps(k), 'vals':json.dumps(value)})
prev_key = key
elif message['data'] == 'del':
(_, k) = key.split(':', 1)
delobjs.append({'key':json.dumps(k)})
idle = 0
else:
time.sleep(1)
idle += 1
return (addobjs, delobjs)
# deps: warm_reboot
def GetSubscribedAsicDbObjects(self, pubsub, ignore=None, timeout=10):
r = redis.Redis(unix_socket_path=self.redis_sock, db=swsscommon.ASIC_DB,
encoding="utf-8", decode_responses=True)
addobjs = []
delobjs = []
idle = 0
while True and idle < timeout:
message = pubsub.get_message()
if message:
print(message)
key = message['channel'].split(':', 1)[1]
if ignore:
fds = message['channel'].split(':')
if fds[2] in ignore:
continue
if message['data'] == 'hset':
value=r.hgetall(key)
(_, t, k) = key.split(':', 2)
addobjs.append({'type':t, 'key':k, 'vals':value})
elif message['data'] == 'del':
(_, t, k) = key.split(':', 2)
delobjs.append({'key':k})
idle = 0
else:
time.sleep(1)
idle += 1
return (addobjs, delobjs)
# deps: warm_reboot
def SubscribeDbObjects(self, dbobjs):
# assuming all the db object pairs are in the same db instance
r = redis.Redis(unix_socket_path=self.redis_sock, encoding="utf-8",
decode_responses=True)
pubsub = r.pubsub()
substr = ""
for db, obj in dbobjs:
pubsub.psubscribe("__keyspace@{}__:{}".format(db, obj))
return pubsub
# deps: warm_reboot
def GetSubscribedMessages(self, pubsub, timeout=10):
messages = []
delobjs = []
idle = 0
prev_key = None
while True and idle < timeout:
message = pubsub.get_message()
if message:
messages.append(message)
idle = 0
else:
time.sleep(1)
idle += 1
return (messages)
# deps: fdb_update, fdb
def get_map_iface_bridge_port_id(self, asic_db):
port_id_2_iface = self.asicdb.portoidmap
tbl = swsscommon.Table(asic_db, "ASIC_STATE:SAI_OBJECT_TYPE_BRIDGE_PORT")
iface_2_bridge_port_id = {}
for key in tbl.getKeys():
status, data = tbl.get(key)
assert status
values = dict(data)
if "SAI_BRIDGE_PORT_ATTR_PORT_ID" in values:
iface_id = values["SAI_BRIDGE_PORT_ATTR_PORT_ID"]
iface_name = port_id_2_iface[iface_id]
iface_2_bridge_port_id[iface_name] = key
return iface_2_bridge_port_id
# deps: fdb_update, fdb
def get_vlan_oid(self, asic_db, vlan_id):
tbl = swsscommon.Table(asic_db, "ASIC_STATE:SAI_OBJECT_TYPE_VLAN")
keys = tbl.getKeys()
for key in keys:
status, fvs = tbl.get(key)
assert status, "Error reading from table %s" % "ASIC_STATE:SAI_OBJECT_TYPE_VLAN"
for k, v in fvs:
if k == "SAI_VLAN_ATTR_VLAN_ID" and v == vlan_id:
return True, key
return False, "Not found vlan id %s" % vlan_id
# deps: fdb
def is_table_entry_exists(self, db, table, keyregex, attributes):
tbl = swsscommon.Table(db, table)
keys = tbl.getKeys()
extra_info = []
for key in keys:
if re.match(keyregex, key) is None:
continue
status, fvs = tbl.get(key)
assert status, "Error reading from table %s" % table
d_attributes = dict(attributes)
for k, v in fvs:
if k in d_attributes and d_attributes[k] == v:
del d_attributes[k]
if len(d_attributes) != 0:
extra_info.append("Desired attributes %s was not found for key %s" % (str(d_attributes), key))
else:
return True, extra_info
else:
if not extra_info:
extra_info.append("Desired key regex %s was not found" % str(keyregex))
return False, extra_info
# deps: fdb
def all_table_entry_has(self, db, table, keyregex, attributes):
tbl = swsscommon.Table(db, table)
keys = tbl.getKeys()
extra_info = []
if len(keys) == 0:
extra_info.append("keyregex %s not found" % keyregex)
return False, extra_info
for key in keys:
if re.match(keyregex, key) is None:
continue
status, fvs = tbl.get(key)
assert status, "Error reading from table %s" % table
d_attributes = dict(attributes)
for k, v in fvs:
if k in d_attributes and d_attributes[k] == v:
del d_attributes[k]
if len(d_attributes) != 0:
extra_info.append("Desired attributes %s were not found for key %s" % (str(d_attributes), key))
return False, extra_info
return True, extra_info
# deps: fdb
def all_table_entry_has_no(self, db, table, keyregex, attributes_list):
tbl = swsscommon.Table(db, table)
keys = tbl.getKeys()
extra_info = []
if len(keys) == 0:
extra_info.append("keyregex %s not found" % keyregex)
return False, extra_info
for key in keys:
if re.match(keyregex, key) is None:
continue
status, fvs = tbl.get(key)
assert status, "Error reading from table %s" % table
for k, v in fvs:
if k in attributes_list: