sonic-buildimage/device/common/pddf/plugins/sfputil.py
Joe LeVeque 7f4ab8fbd8
[sonic-utilities] Update submodule; Build and install as a Python 3 wheel (#5926)
Submodule updates include the following commits:

* src/sonic-utilities 9dc58ea...f9eb739 (18):
  > Remove unnecessary calls to str.encode() now that the package is Python 3; Fix deprecation warning (#1260)
  > [generate_dump] Ignoring file/directory not found Errors (#1201)
  > Fixed porstat rate and util issues (#1140)
  > fix error: interface counters is mismatch after warm-reboot (#1099)
  > Remove unnecessary calls to str.decode() now that the package is Python 3 (#1255)
  > [acl-loader] Make list sorting compliant with Python 3 (#1257)
  > Replace hard-coded fast-reboot with variable. And some typo corrections (#1254)
  > [configlet][portconfig] Remove calls to dict.has_key() which is not available in Python 3 (#1247)
  > Remove unnecessary conversions to list() and calls to dict.keys() (#1243)
  > Clean up LGTM alerts (#1239)
  > Add 'requests' as install dependency in setup.py (#1240)
  > Convert to Python 3 (#1128)
  > Fix mock SonicV2Connector in python3: use decode_responses mode so caller code will be the same as python2 (#1238)
  > [tests] Do not trim from PATH if we did not append to it; Clean up/fix shebangs in scripts (#1233)
  > Updates to bgp config and show commands with BGP_INTERNAL_NEIGHBOR table (#1224)
  > [cli]: NAT show commands newline issue after migrated to Python3 (#1204)
  > [doc]: Update Command-Reference.md (#1231)
  > Added 'import sys' in feature.py file (#1232)

* src/sonic-py-swsssdk 9d9f0c6...1664be9 (2):
  > Fix: no need to decode() after redis client scan, so it will work for both python2 and python3 (#96)
  > FieldValueMap `contains`(`in`)  will also work when migrated to libswsscommon(C++ with SWIG wrapper) (#94)

- Also fix Python 3-related issues:
    - Use integer (floor) division in config_samples.py (sonic-config-engine)
    - Replace print statement with print function in eeprom.py plugin for x86_64-kvm_x86_64-r0 platform
    - Update all platform plugins to be compatible with both Python 2 and Python 3
    - Remove shebangs from plugins files which are not intended to be executable
    - Replace tabs with spaces in Python plugin files and fix alignment, because Python 3 is more strict
    - Remove trailing whitespace from plugins files
2020-11-25 10:28:36 -08:00

237 lines
7.7 KiB
Python
Executable File

import os.path
import sys
sys.path.append('/usr/share/sonic/platform/plugins')
import pddfparse
import json
try:
import time
from ctypes import create_string_buffer
from sonic_sfp.sfputilbase import SfpUtilBase
except ImportError as e:
raise ImportError(str(e) + "- required module not found")
class SfpUtil(SfpUtilBase):
"""Platform generic PDDF SfpUtil class"""
_port_to_eeprom_mapping = {}
_port_start = 0
_port_end = 0
_port_to_type_mapping = {}
_qsfp_ports = []
_sfp_ports = []
def __init__(self):
SfpUtilBase.__init__(self)
global pddf_obj
global plugin_data
with open(os.path.join(os.path.dirname(os.path.realpath(__file__)) + '/../pddf/pd-plugin.json')) as pd:
plugin_data = json.load(pd)
pddf_obj = pddfparse.PddfParse()
self.platform = pddf_obj.get_platform()
self._port_start = 0
self._port_end = self.get_num_ports()
for port_num in range(self._port_start, self._port_end):
device = "PORT" + "%d" % (port_num+1)
port_eeprom_path = pddf_obj.get_path(device, "eeprom")
self._port_to_eeprom_mapping[port_num] = port_eeprom_path
port_type = pddf_obj.get_device_type(device)
self._port_to_type_mapping[port_num] = port_type
self.populate_port_type(port_num)
def get_num_ports(self):
return int(self.platform['num_ports'])
def is_valid_port(self, port_num):
if port_num < self._port_start or port_num > self._port_end:
return False
else:
return True
def get_presence(self, port_num):
if port_num < self._port_start or port_num > self._port_end:
return False
device = "PORT" + "%d" % (port_num+1)
output = pddf_obj.get_attr_name_output(device, 'xcvr_present')
if not output:
return False
#mode = output['mode']
modpres = output['status'].rstrip()
if 'XCVR' in plugin_data:
if 'xcvr_present' in plugin_data['XCVR']:
ptype = self._port_to_type_mapping[port_num]
vtype = 'valmap-'+ptype
if vtype in plugin_data['XCVR']['xcvr_present']:
vmap = plugin_data['XCVR']['xcvr_present'][vtype]
if modpres in vmap:
return vmap[modpres]
else:
return False
# if plugin_data doesn't specify anything regarding Transceivers
if modpres == '1':
return True
return False
def populate_port_type(self, port):
if self._port_to_type_mapping[port] == 'QSFP' or self._port_to_type_mapping[port] == 'QSFP28':
self._qsfp_ports.append(port)
elif self._port_to_type_mapping[port] == 'SFP' or self._port_to_type_mapping[port] == 'SFP28':
self._sfp_ports.append(port)
@property
def port_start(self):
return self._port_start
@property
def port_end(self):
return (self._port_end - 1)
@property
def port_to_eeprom_mapping(self):
return self._port_to_eeprom_mapping
@property
def qsfp_ports(self):
return self._qsfp_ports
def reset(self, port_num):
if port_num < self._port_start or port_num > self._port_end:
return False
device = "PORT" + "%d" % (port_num+1)
port_ps = pddf_obj.get_path(device, "xcvr_reset")
if port_ps is None:
return False
try:
reg_file = open(port_ps, 'w')
except IOError as e:
print("Error: unable to open file: %s" % str(e))
return False
try:
reg_file.seek(0)
reg_file.write('1')
time.sleep(1)
reg_file.seek(0)
reg_file.write('0')
reg_file.close()
return True
except IOError as e:
return False
def get_low_power_mode(self, port_num):
# Check for invalid port_num
if port_num < self._port_start or port_num > self._port_end:
return False
if not self.get_presence(port_num):
return False
device = "PORT" + "%d" % (port_num+1)
output = pddf_obj.get_attr_name_output(device, 'xcvr_lpmode')
if not output:
if port_num not in self.qsfp_ports:
return False # Read from eeprom only for QSFP ports
try:
eeprom = None
eeprom = open(self.port_to_eeprom_mapping[port_num], "rb")
# check for valid connector type
eeprom.seek(2)
ctype = eeprom.read(1)
if ctype in ['21', '23']:
return False
eeprom.seek(93)
lpmode = ord(eeprom.read(1))
if ((lpmode & 0x3) == 0x3):
return True # Low Power Mode if "Power override" bit is 1 and "Power set" bit is 1
else:
# High Power Mode if one of the following conditions is matched:
# 1. "Power override" bit is 0
# 2. "Power override" bit is 1 and "Power set" bit is 0
return False
except IOError as e:
print("Error: unable to open file: %s" % str(e))
return False
finally:
if eeprom is not None:
eeprom.close()
time.sleep(0.01)
else:
#mode = output['mode']
status = int(output['status'].rstrip())
if status == 1:
return True
else:
return False
def set_low_power_mode(self, port_num, lpmode):
# Check for invalid port_num
if port_num < self._port_start or port_num > self._port_end:
return False
if not self.get_presence(port_num):
return False # Port is not present, unable to set the eeprom
device = "PORT" + "%d" % (port_num+1)
port_ps = pddf_obj.get_path(device, "xcvr_lpmode")
if port_ps is None:
if port_num not in self.qsfp_ports:
return False # Write to eeprom only for QSFP ports
try:
eeprom = None
eeprom = open(self.port_to_eeprom_mapping[port_num], "r+b")
# check for valid connector type
eeprom.seek(2)
ctype = eeprom.read(1)
if ctype in ['21', '23']:
return False
# Fill in write buffer
regval = 0x3 if lpmode else 0x1 # 0x3:Low Power Mode, 0x1:High Power Mode
buffer = create_string_buffer(1)
buffer[0] = chr(regval)
# Write to eeprom
eeprom.seek(93)
eeprom.write(buffer[0])
return True
except IOError as e:
print("Error: unable to open file: %s" % str(e))
return False
finally:
if eeprom is not None:
eeprom.close()
time.sleep(0.01)
else:
try:
f = open(port_ps, 'w')
if lpmode:
f.write('1')
else:
f.write('0')
f.close()
return True
except IOError as e:
return False
def get_transceiver_change_event(self):
"""
TODO: This function need to be implemented
when decide to support monitoring SFP(Xcvrd)
on this platform.
"""
raise NotImplementedError
def dump_sysfs(self):
return pddf_obj.cli_dump_dsysfs('xcvr')