-
Notifications
You must be signed in to change notification settings - Fork 160
/
xcvrd.py
2319 lines (1957 loc) · 109 KB
/
xcvrd.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
xcvrd
Transceiver information update daemon for SONiC
"""
try:
import ast
import copy
import json
import os
import signal
import sys
import threading
import time
import datetime
import subprocess
import argparse
import re
import traceback
import ctypes
from natsort import natsorted
from sonic_py_common import daemon_base, syslogger
from sonic_py_common import multi_asic
from swsscommon import swsscommon
from .xcvrd_utilities import sfp_status_helper
from .sff_mgr import SffManagerTask
from .dom_mgr import DomInfoUpdateTask
from .xcvrd_utilities.xcvr_table_helper import *
from .xcvrd_utilities import port_event_helper
from .xcvrd_utilities.port_event_helper import PortChangeObserver
from .xcvrd_utilities import media_settings_parser
from .xcvrd_utilities import optics_si_parser
from sonic_platform_base.sonic_xcvr.api.public.c_cmis import CmisApi
except ImportError as e:
raise ImportError(str(e) + " - required module not found")
#
# Constants ====================================================================
#
SYSLOG_IDENTIFIER = "xcvrd"
PLATFORM_SPECIFIC_MODULE_NAME = "sfputil"
PLATFORM_SPECIFIC_CLASS_NAME = "SfpUtil"
TRANSCEIVER_STATUS_TABLE_SW_FIELDS = ["status", "error", "cmis_state"]
CMIS_STATE_UNKNOWN = 'UNKNOWN'
CMIS_STATE_INSERTED = 'INSERTED'
CMIS_STATE_DP_DEINIT = 'DP_DEINIT'
CMIS_STATE_AP_CONF = 'AP_CONFIGURED'
CMIS_STATE_DP_ACTIVATE = 'DP_ACTIVATION'
CMIS_STATE_DP_INIT = 'DP_INIT'
CMIS_STATE_DP_TXON = 'DP_TXON'
CMIS_STATE_READY = 'READY'
CMIS_STATE_REMOVED = 'REMOVED'
CMIS_STATE_FAILED = 'FAILED'
CMIS_TERMINAL_STATES = {
CMIS_STATE_FAILED,
CMIS_STATE_READY,
CMIS_STATE_REMOVED
}
# Mgminit time required as per CMIS spec
MGMT_INIT_TIME_DELAY_SECS = 2
# SFP insert event poll duration
SFP_INSERT_EVENT_POLL_PERIOD_MSECS = 1000
STATE_MACHINE_UPDATE_PERIOD_MSECS = 60000
TIME_FOR_SFP_READY_SECS = 1
EVENT_ON_ALL_SFP = '-1'
# events definition
SYSTEM_NOT_READY = 'system_not_ready'
SYSTEM_BECOME_READY = 'system_become_ready'
SYSTEM_FAIL = 'system_fail'
NORMAL_EVENT = 'normal'
# states definition
STATE_INIT = 0
STATE_NORMAL = 1
STATE_EXIT = 2
PHYSICAL_PORT_NOT_EXIST = -1
SFP_EEPROM_NOT_READY = -2
SFPUTIL_LOAD_ERROR = 1
PORT_CONFIG_LOAD_ERROR = 2
NOT_IMPLEMENTED_ERROR = 3
SFP_SYSTEM_ERROR = 4
RETRY_TIMES_FOR_SYSTEM_READY = 24
RETRY_PERIOD_FOR_SYSTEM_READY_MSECS = 5000
RETRY_TIMES_FOR_SYSTEM_FAIL = 24
RETRY_PERIOD_FOR_SYSTEM_FAIL_MSECS = 5000
TEMP_UNIT = 'C'
VOLT_UNIT = 'Volts'
POWER_UNIT = 'dBm'
BIAS_UNIT = 'mA'
g_dict = {}
# Global platform specific sfputil class instance
platform_sfputil = None
# Global chassis object based on new platform api
platform_chassis = None
# Global logger instance for helper functions and classes
# TODO: Refactor so that we only need the logger inherited
# by DaemonXcvrd
helper_logger = syslogger.SysLogger(SYSLOG_IDENTIFIER, enable_runtime_config=True)
#
# Helper functions =============================================================
#
def log_exception_traceback():
exc_type, exc_value, exc_traceback = sys.exc_info()
msg = traceback.format_exception(exc_type, exc_value, exc_traceback)
for tb_line in msg:
for tb_line_split in tb_line.splitlines():
helper_logger.log_error(tb_line_split)
def is_cmis_api(api):
return isinstance(api, CmisApi)
def get_cmis_application_desired(api, host_lane_count, speed):
"""
Get the CMIS application code that matches the specified host side configurations
Args:
api:
XcvrApi object
host_lane_count:
Number of lanes on the host side
speed:
Integer, the port speed of the host interface
Returns:
Integer, the transceiver-specific application code
"""
if speed == 0 or host_lane_count == 0:
return None
if not is_cmis_api(api):
return None
appl_dict = api.get_application_advertisement()
for index, app_info in appl_dict.items():
if (app_info.get('host_lane_count') == host_lane_count and
get_interface_speed(app_info.get('host_electrical_interface_id')) == speed):
return (index & 0xf)
helper_logger.log_notice(f'No application found from {appl_dict} with host_lane_count={host_lane_count} speed={speed}')
return None
def get_interface_speed(ifname):
"""
Get the port speed from the host interface name
Args:
ifname: String, interface name
Returns:
Integer, the port speed if success otherwise 0
"""
# see HOST_ELECTRICAL_INTERFACE of sff8024.py
speed = 0
if '800G' in ifname:
speed = 800000
elif '400G' in ifname:
speed = 400000
elif '200G' in ifname:
speed = 200000
elif '100G' in ifname or 'CAUI-4' in ifname:
speed = 100000
elif '50G' in ifname or 'LAUI-2' in ifname:
speed = 50000
elif '40G' in ifname or 'XLAUI' in ifname or 'XLPPI' in ifname:
speed = 40000
elif '25G' in ifname:
speed = 25000
elif '10G' in ifname or 'SFI' in ifname or 'XFI' in ifname:
speed = 10000
elif '1000BASE' in ifname:
speed = 1000
return speed
# Get physical port name
def get_physical_port_name(logical_port, physical_port, ganged):
if ganged:
return logical_port + ":{} (ganged)".format(physical_port)
else:
return logical_port
# Get physical port name dict (port_idx to port_name)
def get_physical_port_name_dict(logical_port_name, port_mapping):
ganged_port = False
ganged_member_num = 1
physical_port_list = port_mapping.logical_port_name_to_physical_port_list(logical_port_name)
if physical_port_list is None:
helper_logger.log_error("No physical ports found for logical port '{}'".format(logical_port_name))
return {}
if len(physical_port_list) > 1:
ganged_port = True
port_name_dict = {}
for physical_port in physical_port_list:
port_name = get_physical_port_name(logical_port_name, ganged_member_num, ganged_port)
ganged_member_num += 1
port_name_dict[physical_port] = port_name
return port_name_dict
# Strip units and beautify
def strip_unit_and_beautify(value, unit):
# Strip unit from raw data
if type(value) is str:
width = len(unit)
if value[-width:] == unit:
value = value[:-width]
return value
else:
return str(value)
def _wrapper_get_presence(physical_port):
if platform_chassis is not None:
try:
return platform_chassis.get_sfp(physical_port).get_presence()
except NotImplementedError:
pass
return platform_sfputil.get_presence(physical_port)
def _wrapper_is_replaceable(physical_port):
if platform_chassis is not None:
try:
return platform_chassis.get_sfp(physical_port).is_replaceable()
except NotImplementedError:
pass
return False
def _wrapper_get_transceiver_info(physical_port):
if platform_chassis is not None:
try:
return platform_chassis.get_sfp(physical_port).get_transceiver_info()
except NotImplementedError:
pass
return platform_sfputil.get_transceiver_info_dict(physical_port)
def _wrapper_get_transceiver_firmware_info(physical_port):
if platform_chassis is not None:
try:
return platform_chassis.get_sfp(physical_port).get_transceiver_info_firmware_versions()
except NotImplementedError:
pass
return {}
def _wrapper_get_transceiver_dom_info(physical_port):
if platform_chassis is not None:
try:
return platform_chassis.get_sfp(physical_port).get_transceiver_bulk_status()
except NotImplementedError:
pass
return platform_sfputil.get_transceiver_dom_info_dict(physical_port)
def _wrapper_get_transceiver_dom_threshold_info(physical_port):
if platform_chassis is not None:
try:
return platform_chassis.get_sfp(physical_port).get_transceiver_threshold_info()
except NotImplementedError:
pass
return platform_sfputil.get_transceiver_dom_threshold_info_dict(physical_port)
def _wrapper_get_transceiver_status(physical_port):
if platform_chassis is not None:
try:
return platform_chassis.get_sfp(physical_port).get_transceiver_status()
except NotImplementedError:
pass
return {}
def _wrapper_get_transceiver_pm(physical_port):
if platform_chassis is not None:
try:
return platform_chassis.get_sfp(physical_port).get_transceiver_pm()
except NotImplementedError:
pass
return {}
def _wrapper_is_flat_memory(physical_port):
if platform_chassis is not None:
try:
sfp = platform_chassis.get_sfp(physical_port)
api = sfp.get_xcvr_api()
if not api:
return True
return api.is_flat_memory()
except NotImplementedError:
pass
return None
# Soak SFP insert event until management init completes
def _wrapper_soak_sfp_insert_event(sfp_insert_events, port_dict):
for key, value in list(port_dict.items()):
if value == sfp_status_helper.SFP_STATUS_INSERTED:
sfp_insert_events[key] = time.time()
del port_dict[key]
elif value == sfp_status_helper.SFP_STATUS_REMOVED:
if key in sfp_insert_events:
del sfp_insert_events[key]
for key, itime in list(sfp_insert_events.items()):
if time.time() - itime >= MGMT_INIT_TIME_DELAY_SECS:
port_dict[key] = sfp_status_helper.SFP_STATUS_INSERTED
del sfp_insert_events[key]
def _wrapper_get_transceiver_change_event(timeout):
if platform_chassis is not None:
try:
status, events = platform_chassis.get_change_event(timeout)
sfp_events = events.get('sfp')
sfp_errors = events.get('sfp_error')
return status, sfp_events, sfp_errors
except NotImplementedError:
pass
status, events = platform_sfputil.get_transceiver_change_event(timeout)
return status, events, None
def _wrapper_get_sfp_type(physical_port):
if platform_chassis:
try:
sfp = platform_chassis.get_sfp(physical_port)
except (NotImplementedError, AttributeError):
return None
try:
return sfp.sfp_type
except (NotImplementedError, AttributeError):
pass
return None
def _wrapper_get_sfp_error_description(physical_port):
if platform_chassis:
try:
return platform_chassis.get_sfp(physical_port).get_error_description()
except NotImplementedError:
pass
return None
def beautify_dom_threshold_info_dict(dom_info_dict):
for k, v in dom_info_dict.items():
if re.search('temp', k) is not None:
dom_info_dict[k] = strip_unit_and_beautify(v, TEMP_UNIT)
elif re.search('vcc', k) is not None:
dom_info_dict[k] = strip_unit_and_beautify(v, VOLT_UNIT)
elif re.search('power', k) is not None:
dom_info_dict[k] = strip_unit_and_beautify(v, POWER_UNIT)
elif re.search('txbias', k) is not None:
dom_info_dict[k] = strip_unit_and_beautify(v, BIAS_UNIT)
elif type(v) is not str:
# For all the other keys:
dom_info_dict[k] = str(v)
# Update port sfp info in db
def post_port_sfp_info_to_db(logical_port_name, port_mapping, table, transceiver_dict,
stop_event=threading.Event()):
ganged_port = False
ganged_member_num = 1
physical_port_list = port_mapping.logical_port_name_to_physical_port_list(logical_port_name)
if physical_port_list is None:
helper_logger.log_error("No physical ports found for logical port '{}'".format(logical_port_name))
return PHYSICAL_PORT_NOT_EXIST
if len(physical_port_list) > 1:
ganged_port = True
for physical_port in physical_port_list:
if stop_event.is_set():
break
if not _wrapper_get_presence(physical_port):
helper_logger.log_notice("Transceiver not present in port {}".format(logical_port_name))
continue
port_name = get_physical_port_name(logical_port_name, ganged_member_num, ganged_port)
ganged_member_num += 1
try:
port_info_dict = _wrapper_get_transceiver_info(physical_port)
if port_info_dict is not None:
is_replaceable = _wrapper_is_replaceable(physical_port)
transceiver_dict[physical_port] = port_info_dict
# if cmis is supported by the module
if 'cmis_rev' in port_info_dict:
fvs = swsscommon.FieldValuePairs(
[('type', port_info_dict['type']),
('vendor_rev', port_info_dict['vendor_rev']),
('serial', port_info_dict['serial']),
('manufacturer', port_info_dict['manufacturer']),
('model', port_info_dict['model']),
('vendor_oui', port_info_dict['vendor_oui']),
('vendor_date', port_info_dict['vendor_date']),
('connector', port_info_dict['connector']),
('encoding', port_info_dict['encoding']),
('ext_identifier', port_info_dict['ext_identifier']),
('ext_rateselect_compliance', port_info_dict['ext_rateselect_compliance']),
('cable_type', port_info_dict['cable_type']),
('cable_length', str(port_info_dict['cable_length'])),
('specification_compliance', port_info_dict['specification_compliance']),
('nominal_bit_rate', str(port_info_dict['nominal_bit_rate'])),
('application_advertisement', port_info_dict['application_advertisement']
if 'application_advertisement' in port_info_dict else 'N/A'),
('is_replaceable', str(is_replaceable)),
('dom_capability', port_info_dict['dom_capability']
if 'dom_capability' in port_info_dict else 'N/A'),
('cmis_rev', port_info_dict['cmis_rev'] if 'cmis_rev' in port_info_dict else 'N/A'),
('hardware_rev', port_info_dict['hardware_rev']
if 'hardware_rev' in port_info_dict else 'N/A'),
('media_interface_code', port_info_dict['media_interface_code']
if 'media_interface_code' in port_info_dict else 'N/A'),
('host_electrical_interface', port_info_dict['host_electrical_interface']
if 'host_electrical_interface' in port_info_dict else 'N/A'),
('host_lane_count', 'N/A'),
('media_lane_count', 'N/A'),
('host_lane_assignment_option', str(port_info_dict['host_lane_assignment_option'])
if 'host_lane_assignment_option' in port_info_dict else 'N/A'),
('media_lane_assignment_option', str(port_info_dict['media_lane_assignment_option'])
if 'media_lane_assignment_option' in port_info_dict else 'N/A'),
('active_apsel_hostlane1', 'N/A'),
('active_apsel_hostlane2', 'N/A'),
('active_apsel_hostlane3', 'N/A'),
('active_apsel_hostlane4', 'N/A'),
('active_apsel_hostlane5', 'N/A'),
('active_apsel_hostlane6', 'N/A'),
('active_apsel_hostlane7', 'N/A'),
('active_apsel_hostlane8', 'N/A'),
('media_interface_technology', port_info_dict['media_interface_technology']
if 'media_interface_technology' in port_info_dict else 'N/A'),
('supported_max_tx_power', str(port_info_dict['supported_max_tx_power'])
if 'supported_max_tx_power' in port_info_dict else 'N/A'),
('supported_min_tx_power', str(port_info_dict['supported_min_tx_power'])
if 'supported_min_tx_power' in port_info_dict else 'N/A'),
('supported_max_laser_freq', str(port_info_dict['supported_max_laser_freq'])
if 'supported_max_laser_freq' in port_info_dict else 'N/A'),
('supported_min_laser_freq', str(port_info_dict['supported_min_laser_freq'])
if 'supported_min_laser_freq' in port_info_dict else 'N/A')
])
# else cmis is not supported by the module
else:
fvs = swsscommon.FieldValuePairs([
('type', port_info_dict['type']),
('vendor_rev', port_info_dict['vendor_rev']),
('serial', port_info_dict['serial']),
('manufacturer', port_info_dict['manufacturer']),
('model', port_info_dict['model']),
('vendor_oui', port_info_dict['vendor_oui']),
('vendor_date', port_info_dict['vendor_date']),
('connector', port_info_dict['connector']),
('encoding', port_info_dict['encoding']),
('ext_identifier', port_info_dict['ext_identifier']),
('ext_rateselect_compliance', port_info_dict['ext_rateselect_compliance']),
('cable_type', port_info_dict['cable_type']),
('cable_length', str(port_info_dict['cable_length'])),
('specification_compliance', port_info_dict['specification_compliance']),
('nominal_bit_rate', str(port_info_dict['nominal_bit_rate'])),
('application_advertisement', port_info_dict['application_advertisement']
if 'application_advertisement' in port_info_dict else 'N/A'),
('is_replaceable', str(is_replaceable)),
('dom_capability', port_info_dict['dom_capability']
if 'dom_capability' in port_info_dict else 'N/A')
])
table.set(port_name, fvs)
else:
return SFP_EEPROM_NOT_READY
except NotImplementedError:
helper_logger.log_error("This functionality is currently not implemented for this platform")
sys.exit(NOT_IMPLEMENTED_ERROR)
# Update port dom threshold info in db
def post_port_dom_threshold_info_to_db(logical_port_name, port_mapping, table,
stop=threading.Event(), dom_th_info_cache=None):
ganged_port = False
ganged_member_num = 1
physical_port_list = port_mapping.logical_port_name_to_physical_port_list(logical_port_name)
if physical_port_list is None:
helper_logger.log_error("No physical ports found for logical port '{}'".format(logical_port_name))
return PHYSICAL_PORT_NOT_EXIST
if len(physical_port_list) > 1:
ganged_port = True
for physical_port in physical_port_list:
if stop.is_set():
break
if not _wrapper_get_presence(physical_port):
continue
if _wrapper_is_flat_memory(physical_port) == True:
continue
port_name = get_physical_port_name(logical_port_name,
ganged_member_num, ganged_port)
ganged_member_num += 1
try:
if dom_th_info_cache is not None and physical_port in dom_th_info_cache:
# If cache is enabled and there is a cache, no need read from EEPROM, just read from cache
dom_info_dict = dom_th_info_cache[physical_port]
else:
dom_info_dict = _wrapper_get_transceiver_dom_threshold_info(physical_port)
if dom_th_info_cache is not None:
# If cache is enabled, put dom threshold infomation to cache
dom_th_info_cache[physical_port] = dom_info_dict
if dom_info_dict is not None:
beautify_dom_threshold_info_dict(dom_info_dict)
fvs = swsscommon.FieldValuePairs([(k, v) for k, v in dom_info_dict.items()])
table.set(port_name, fvs)
else:
return SFP_EEPROM_NOT_READY
except NotImplementedError:
helper_logger.log_error("This functionality is currently not implemented for this platform")
sys.exit(NOT_IMPLEMENTED_ERROR)
# Delete port dom/sfp info from db
def del_port_sfp_dom_info_from_db(logical_port_name, port_mapping, int_tbl, dom_tbl, dom_threshold_tbl, pm_tbl, firmware_info_tbl):
for physical_port_name in get_physical_port_name_dict(logical_port_name, port_mapping).values():
try:
if int_tbl:
int_tbl._del(physical_port_name)
if dom_tbl:
dom_tbl._del(physical_port_name)
if dom_threshold_tbl:
dom_threshold_tbl._del(physical_port_name)
if pm_tbl:
pm_tbl._del(physical_port_name)
if firmware_info_tbl:
firmware_info_tbl._del(physical_port_name)
except NotImplementedError:
helper_logger.log_error("This functionality is currently not implemented for this platform")
sys.exit(NOT_IMPLEMENTED_ERROR)
def check_port_in_range(range_str, physical_port):
RANGE_SEPARATOR = '-'
range_list = range_str.split(RANGE_SEPARATOR)
start_num = int(range_list[0].strip())
end_num = int(range_list[1].strip())
if start_num <= physical_port <= end_num:
return True
return False
def waiting_time_compensation_with_sleep(time_start, time_to_wait):
time_now = time.time()
time_diff = time_now - time_start
if time_diff < time_to_wait:
time.sleep(time_to_wait - time_diff)
# Update port SFP status table for SW fields on receiving SFP change event
def update_port_transceiver_status_table_sw(logical_port_name, status_tbl, status, error_descriptions='N/A'):
fvs = swsscommon.FieldValuePairs([('status', status), ('error', error_descriptions)])
status_tbl.set(logical_port_name, fvs)
def get_cmis_state_from_state_db(lport, status_tbl):
found, transceiver_status_dict = status_tbl.get(lport)
if found and 'cmis_state' in dict(transceiver_status_dict):
return dict(transceiver_status_dict)['cmis_state']
else:
return CMIS_STATE_UNKNOWN
# Delete port from SFP status table
def delete_port_from_status_table_sw(logical_port_name, status_tbl):
for f in TRANSCEIVER_STATUS_TABLE_SW_FIELDS:
status_tbl.hdel(logical_port_name, f)
# Delete port from SFP status table for HW fields which are fetched from EEPROM
def delete_port_from_status_table_hw(logical_port_name, port_mapping, status_tbl):
for physical_port_name in get_physical_port_name_dict(logical_port_name, port_mapping).values():
found, fvs = status_tbl.get(physical_port_name)
if not found:
return
status_dict = dict(fvs)
for f in status_dict.keys():
if f in TRANSCEIVER_STATUS_TABLE_SW_FIELDS:
continue
status_tbl.hdel(physical_port_name, f)
def is_fast_reboot_enabled():
fastboot_enabled = subprocess.check_output('sonic-db-cli STATE_DB hget "FAST_RESTART_ENABLE_TABLE|system" enable', shell=True, universal_newlines=True)
return "true" in fastboot_enabled
def is_warm_reboot_enabled():
warmstart = swsscommon.WarmStart()
warmstart.initialize("xcvrd", "pmon")
warmstart.checkWarmStart("xcvrd", "pmon", False)
is_warm_start = warmstart.isWarmStart()
return is_warm_start
#
# Helper classes ===============================================================
#
# Thread wrapper class for CMIS transceiver management
class CmisManagerTask(threading.Thread):
CMIS_MAX_RETRIES = 3
CMIS_DEF_EXPIRED = 60 # seconds, default expiration time
CMIS_MODULE_TYPES = ['QSFP-DD', 'QSFP_DD', 'OSFP', 'OSFP-8X', 'QSFP+C']
CMIS_MAX_HOST_LANES = 8
def __init__(self, namespaces, port_mapping, main_thread_stop_event, skip_cmis_mgr=False):
threading.Thread.__init__(self)
self.name = "CmisManagerTask"
self.exc = None
self.task_stopping_event = threading.Event()
self.main_thread_stop_event = main_thread_stop_event
self.port_dict = {}
self.port_mapping = copy.deepcopy(port_mapping)
self.isPortInitDone = False
self.isPortConfigDone = False
self.skip_cmis_mgr = skip_cmis_mgr
self.namespaces = namespaces
def log_debug(self, message):
helper_logger.log_debug("CMIS: {}".format(message))
def log_notice(self, message):
helper_logger.log_notice("CMIS: {}".format(message))
def log_error(self, message):
helper_logger.log_error("CMIS: {}".format(message))
def update_port_transceiver_status_table_sw_cmis_state(self, lport, cmis_state_to_set):
asic_index = self.port_mapping.get_asic_id_for_logical_port(lport)
status_table = self.xcvr_table_helper.get_status_tbl(asic_index)
if status_table is None:
helper_logger.log_error("status_table is None while updating "
"sw CMIS state for lport {}".format(lport))
return
fvs = swsscommon.FieldValuePairs([('cmis_state', cmis_state_to_set)])
status_table.set(lport, fvs)
def on_port_update_event(self, port_change_event):
if port_change_event.event_type not in [port_change_event.PORT_SET, port_change_event.PORT_DEL]:
return
lport = port_change_event.port_name
pport = port_change_event.port_index
if lport in ['PortInitDone']:
self.isPortInitDone = True
return
if lport in ['PortConfigDone']:
self.isPortConfigDone = True
return
# Skip if it's not a physical port
if not lport.startswith('Ethernet'):
return
# Skip if the physical index is not available
if pport is None:
return
# Skip if the port/cage type is not a CMIS
# 'index' can be -1 if STATE_DB|PORT_TABLE
if lport not in self.port_dict:
self.port_dict[lport] = {}
if port_change_event.port_dict is None:
return
if port_change_event.event_type == port_change_event.PORT_SET:
if pport >= 0:
self.port_dict[lport]['index'] = pport
if 'speed' in port_change_event.port_dict and port_change_event.port_dict['speed'] != 'N/A':
self.port_dict[lport]['speed'] = port_change_event.port_dict['speed']
if 'lanes' in port_change_event.port_dict:
self.port_dict[lport]['lanes'] = port_change_event.port_dict['lanes']
if 'host_tx_ready' in port_change_event.port_dict:
self.port_dict[lport]['host_tx_ready'] = port_change_event.port_dict['host_tx_ready']
if 'admin_status' in port_change_event.port_dict:
self.port_dict[lport]['admin_status'] = port_change_event.port_dict['admin_status']
if 'laser_freq' in port_change_event.port_dict:
self.port_dict[lport]['laser_freq'] = int(port_change_event.port_dict['laser_freq'])
if 'tx_power' in port_change_event.port_dict:
self.port_dict[lport]['tx_power'] = float(port_change_event.port_dict['tx_power'])
if 'subport' in port_change_event.port_dict:
self.port_dict[lport]['subport'] = int(port_change_event.port_dict['subport'])
self.force_cmis_reinit(lport, 0)
else:
self.update_port_transceiver_status_table_sw_cmis_state(lport, CMIS_STATE_REMOVED)
def get_cmis_dp_init_duration_secs(self, api):
return api.get_datapath_init_duration()/1000
def get_cmis_dp_deinit_duration_secs(self, api):
return api.get_datapath_deinit_duration()/1000
def get_cmis_module_power_up_duration_secs(self, api):
return api.get_module_pwr_up_duration()/1000
def get_cmis_module_power_down_duration_secs(self, api):
return api.get_module_pwr_down_duration()/1000
def get_cmis_host_lanes_mask(self, api, appl, host_lane_count, subport):
"""
Retrieves mask of active host lanes based on appl, host lane count and subport
Args:
api:
XcvrApi object
appl:
Integer, the transceiver-specific application code
host_lane_count:
Integer, number of lanes on the host side
subport:
Integer, 1-based logical port number of the physical port after breakout
0 means port is a non-breakout port
Returns:
Integer, a mask of the active lanes on the host side
e.g. 0x3 for lane 0 and lane 1.
"""
host_lanes_mask = 0
if appl is None or host_lane_count <= 0 or subport < 0:
self.log_error("Invalid input to get host lane mask - appl {} host_lane_count {} "
"subport {}!".format(appl, host_lane_count, subport))
return host_lanes_mask
host_lane_assignment_option = api.get_host_lane_assignment_option(appl)
host_lane_start_bit = (host_lane_count * (0 if subport == 0 else subport - 1))
if host_lane_assignment_option & (1 << host_lane_start_bit):
host_lanes_mask = ((1 << host_lane_count) - 1) << host_lane_start_bit
else:
self.log_error("Unable to find starting host lane - host_lane_assignment_option {}"
" host_lane_start_bit {} host_lane_count {} subport {} appl {}!".format(
host_lane_assignment_option, host_lane_start_bit, host_lane_count,
subport, appl))
return host_lanes_mask
def get_cmis_media_lanes_mask(self, api, appl, lport, subport):
"""
Retrieves mask of active media lanes based on appl, lport and subport
Args:
api:
XcvrApi object
appl:
Integer, the transceiver-specific application code
lport:
String, logical port name
subport:
Integer, 1-based logical port number of the physical port after breakout
0 means port is a non-breakout port
Returns:
Integer, a mask of the active lanes on the media side
e.g. 0xf for lane 0, lane 1, lane 2 and lane 3.
"""
media_lanes_mask = 0
media_lane_count = self.port_dict[lport]['media_lane_count']
media_lane_assignment_option = self.port_dict[lport]['media_lane_assignment_options']
if appl < 1 or media_lane_count <= 0 or subport < 0:
self.log_error("Invalid input to get media lane mask - appl {} media_lane_count {} "
"lport {} subport {}!".format(appl, media_lane_count, lport, subport))
return media_lanes_mask
media_lane_start_bit = (media_lane_count * (0 if subport == 0 else subport - 1))
if media_lane_assignment_option & (1 << media_lane_start_bit):
media_lanes_mask = ((1 << media_lane_count) - 1) << media_lane_start_bit
else:
self.log_error("Unable to find starting media lane - media_lane_assignment_option {}"
" media_lane_start_bit {} media_lane_count {} lport {} subport {} appl {}!".format(
media_lane_assignment_option, media_lane_start_bit, media_lane_count,
lport, subport, appl))
return media_lanes_mask
def is_appl_reconfigure_required(self, api, app_new):
"""
Reset app code if non default app code needs to configured
"""
for lane in range(self.CMIS_MAX_HOST_LANES):
app_cur = api.get_application(lane)
if app_cur != 0 and app_cur != app_new:
return True
return False
def is_cmis_application_update_required(self, api, app_new, host_lanes_mask):
"""
Check if the CMIS application update is required
Args:
api:
XcvrApi object
app_new:
Integer, the transceiver-specific application code for the new application
host_lanes_mask:
Integer, a bitmask of the lanes on the host side
e.g. 0x5 for lane 0 and lane 2.
Returns:
Boolean, true if application update is required otherwise false
"""
if api.is_flat_memory() or app_new <= 0 or host_lanes_mask <= 0:
self.log_error("Invalid input while checking CMIS update required - is_flat_memory {}"
"app_new {} host_lanes_mask {}!".format(
api.is_flat_memory(), app_new, host_lanes_mask))
return False
app_old = 0
for lane in range(self.CMIS_MAX_HOST_LANES):
if ((1 << lane) & host_lanes_mask) == 0:
continue
if app_old == 0:
app_old = api.get_application(lane)
elif app_old != api.get_application(lane):
self.log_notice("Not all the lanes are in the same application mode "
"app_old {} current app {} lane {} host_lanes_mask {}".format(
app_old, api.get_application(lane), lane, host_lanes_mask))
self.log_notice("Forcing application update...")
return True
if app_old == app_new:
skip = True
dp_state = api.get_datapath_state()
conf_state = api.get_config_datapath_hostlane_status()
for lane in range(self.CMIS_MAX_HOST_LANES):
if ((1 << lane) & host_lanes_mask) == 0:
continue
name = "DP{}State".format(lane + 1)
if dp_state[name] != 'DataPathActivated':
skip = False
break
name = "ConfigStatusLane{}".format(lane + 1)
if conf_state[name] != 'ConfigSuccess':
skip = False
break
return (not skip)
return True
def force_cmis_reinit(self, lport, retries=0):
"""
Try to force the restart of CMIS state machine
"""
self.update_port_transceiver_status_table_sw_cmis_state(lport, CMIS_STATE_INSERTED)
self.port_dict[lport]['cmis_retries'] = retries
self.port_dict[lport]['cmis_expired'] = None # No expiration
def check_module_state(self, api, states):
"""
Check if the CMIS module is in the specified state
Args:
api:
XcvrApi object
states:
List, a string list of states
Returns:
Boolean, true if it's in the specified state, otherwise false
"""
return api.get_module_state() in states
def check_config_error(self, api, host_lanes_mask, states):
"""
Check if the CMIS configuration states are in the specified state
Args:
api:
XcvrApi object
host_lanes_mask:
Integer, a bitmask of the lanes on the host side
e.g. 0x5 for lane 0 and lane 2.
states:
List, a string list of states
Returns:
Boolean, true if all lanes are in the specified state, otherwise false
"""
done = True
cerr = api.get_config_datapath_hostlane_status()
for lane in range(self.CMIS_MAX_HOST_LANES):
if ((1 << lane) & host_lanes_mask) == 0:
continue
key = "ConfigStatusLane{}".format(lane + 1)
if cerr[key] not in states:
done = False
break
return done
def check_datapath_init_pending(self, api, host_lanes_mask):
"""
Check if the CMIS datapath init is pending
Args:
api:
XcvrApi object
host_lanes_mask:
Integer, a bitmask of the lanes on the host side
e.g. 0x5 for lane 0 and lane 2.
Returns:
Boolean, true if all lanes are pending datapath init, otherwise false
"""
pending = True
dpinit_pending_dict = api.get_dpinit_pending()
for lane in range(self.CMIS_MAX_HOST_LANES):
if ((1 << lane) & host_lanes_mask) == 0:
continue
key = "DPInitPending{}".format(lane + 1)
if not dpinit_pending_dict[key]:
pending = False
break
return pending
def check_datapath_state(self, api, host_lanes_mask, states):
"""
Check if the CMIS datapath states are in the specified state
Args:
api:
XcvrApi object
host_lanes_mask:
Integer, a bitmask of the lanes on the host side
e.g. 0x5 for lane 0 and lane 2.
states:
List, a string list of states
Returns:
Boolean, true if all lanes are in the specified state, otherwise false
"""
done = True
dpstate = api.get_datapath_state()
for lane in range(self.CMIS_MAX_HOST_LANES):
if ((1 << lane) & host_lanes_mask) == 0:
continue
key = "DP{}State".format(lane + 1)
if dpstate[key] not in states:
done = False
break
return done