sonic-buildimage/device/inventec/x86_64-inventec_d6332-r0/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

355 lines
12 KiB
Python
Executable File

# sfputil.py
#
# Platform-specific SFP transceiver interface for SONiC
#
try:
import time
import os
import re
import socket
from sonic_sfp.sfputilbase import SfpUtilBase
from collections import OrderedDict
from sonic_sfp.sff8472 import sff8472Dom
except ImportError as e:
raise ImportError("%s - required module not found" % str(e))
SFP_TEMPE_OFFSET = 96
SFP_TEMPE_WIDTH = 2
SFP_VLOT_OFFSET = 98
SFP_VOLT_WIDTH = 2
SFP_CHANNL_MON_OFFSET = 100
SFP_CHANNL_MON_WIDTH = 6
NETLINK_KOBJECT_UEVENT = 15
monitor = None
class SWPSEventMonitor(object):
def __init__(self):
self.recieved_events = OrderedDict()
self.socket = socket.socket(socket.AF_NETLINK, socket.SOCK_DGRAM, NETLINK_KOBJECT_UEVENT)
def start(self):
self.socket.bind((os.getpid(), -1))
def stop(self):
self.socket.close()
def __enter__(self):
self.start()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.stop()
def __iter__(self):
global monitor
while True:
for item in monitor.next_events():
yield item
def next_events(self):
data = self.socket.recv(16384)
event = {}
for item in data.split(b'\x00'):
if not item:
# check if we have an event and if we already received it
if event and event['SEQNUM'] not in self.recieved_events:
self.recieved_events[event['SEQNUM']] = None
if (len(self.recieved_events) > 100):
self.recieved_events.popitem(last=False)
yield event
event = {}
else:
try:
k, v = item.split(b'=', 1)
event[k.decode('ascii')] = v.decode('ascii')
except ValueError:
pass
class SfpUtil(SfpUtilBase):
"""Platform-specific SfpUtil class"""
PORT_START = 0
PORT_END = 31
PORTS_IN_BLOCK = 32
_port_to_eeprom_mapping = {}
port_to_i2cbus_mapping = {
0: 12,
1: 13,
2: 14,
3: 15,
4: 16,
5: 17,
6: 18,
7: 19,
8: 20,
9: 21,
10: 22,
11: 23,
12: 24,
13: 25,
14: 26,
15: 27,
16: 28,
17: 29,
18: 30,
19: 31,
20: 32,
21: 33,
22: 34,
23: 35,
24: 36,
25: 37,
26: 38,
27: 39,
28: 40,
29: 41,
30: 42,
31: 43
}
@property
def port_start(self):
return self.PORT_START
@property
def port_end(self):
return self.PORT_END
@property
def qsfp_ports(self):
return list(range(0, self.PORTS_IN_BLOCK + 1))
@property
def port_to_eeprom_mapping(self):
return self._port_to_eeprom_mapping
def __init__(self):
eeprom_path = "/sys/class/i2c-adapter/i2c-{0}/{0}-0050/eeprom"
for x in range(0, self.port_end + 1):
port_eeprom_path = eeprom_path.format(self.port_to_i2cbus_mapping[x])
self.port_to_eeprom_mapping[x] = port_eeprom_path
self.phy_port_dict = {}
SfpUtilBase.__init__(self)
def get_presence(self, port_num):
# Check for invalid port_num
if port_num < self.port_start or port_num > self.port_end:
return False
try:
reg_file = open("/sys/class/swps/port"+str(port_num)+"/present")
except IOError as e:
print("Error: unable to open file: %s" % str(e))
return False
reg_value = int(reg_file.readline().rstrip())
if reg_value == 0:
return True
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
try:
reg_file = open("/sys/class/swps/port"+str(port_num)+"/lpmod")
except IOError as e:
print("Error: unable to open file: %s" % str(e))
reg_value = int(reg_file.readline().rstrip())
if reg_value == 0:
return False
return True
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
try:
reg_file = open("/sys/class/swps/port"+str(port_num)+"/lpmod", "r+")
except IOError as e:
print("Error: unable to open file: %s" % str(e))
return False
lpmode = int(reg_file.readline().rstrip())
# LPMode is active high; set or clear the bit accordingly
if lpmode is True:
reg_value = 1
else:
reg_value = 0
reg_file.write(hex(reg_value))
reg_file.close()
return True
def reset(self, port_num):
QSFP_RESET_REGISTER_DEVICE_FILE = "/sys/class/swps/port"+str(port_num)+"/reset"
# Check for invalid port_num
if port_num < self.port_start or port_num > self.port_end:
return False
try:
reg_file = open(QSFP_RESET_REGISTER_DEVICE_FILE, "r+")
except IOError as e:
print("Error: unable to open file: %s" % str(e))
return False
reg_value = 0
reg_file.write(hex(reg_value))
reg_file.close()
# Sleep 2 second to allow it to settle
time.sleep(2)
# Flip the value back write back to the register to take port out of reset
try:
reg_file = open(QSFP_RESET_REGISTER_DEVICE_FILE, "r+")
except IOError as e:
print("Error: unable to open file: %s" % str(e))
return False
reg_value = 1
reg_file.write(hex(reg_value))
reg_file.close()
return True
def _get_port_eeprom_path(self, port_num, devid):
sysfs_i2c_adapter_base_path = "/sys/class/i2c-adapter"
if devid == self.IDENTITY_EEPROM_ADDR:
return SfpUtilBase._get_port_eeprom_path(self, port_num, devid)
else:
i2c_adapter_id = self._get_port_i2c_adapter_id(port_num)
if i2c_adapter_id is None:
print("Error getting i2c bus num")
return None
# Get i2c virtual bus path for the sfp
sysfs_sfp_i2c_adapter_path = "%s/i2c-%s" % (sysfs_i2c_adapter_base_path,
str(i2c_adapter_id))
# If i2c bus for port does not exist
if not os.path.exists(sysfs_sfp_i2c_adapter_path):
print("Could not find i2c bus %s. Driver not loaded?" % sysfs_sfp_i2c_adapter_path)
return None
sysfs_sfp_i2c_client_path = "%s/%s-00%s" % (sysfs_sfp_i2c_adapter_path,
str(i2c_adapter_id),
hex(devid)[-2:])
# If sfp device is not present on bus, Add it
if not os.path.exists(sysfs_sfp_i2c_client_path):
ret = self._add_new_sfp_device(
sysfs_sfp_i2c_adapter_path, devid)
if ret != 0:
print("Error adding sfp device")
return None
sysfs_sfp_i2c_client_eeprom_path = "%s/eeprom" % sysfs_sfp_i2c_client_path
return sysfs_sfp_i2c_client_eeprom_path
def get_transceiver_dom_info_dict(self, port_num):
if port_num in self.qsfp_ports:
return SfpUtilBase.get_transceiver_dom_info_dict(self, port_num)
else:
transceiver_dom_info_dict = {}
offset = 0
file_path = self._get_port_eeprom_path(port_num, self.DOM_EEPROM_ADDR)
if not self._sfp_eeprom_present(file_path, 0):
return None
try:
sysfsfile_eeprom = open(file_path, "rb")
except IOError:
print("Error: reading sysfs file %s" % file_path)
return None
sfpd_obj = sff8472Dom(None, 1)
if sfpd_obj is None:
return None
dom_temperature_raw = self._read_eeprom_specific_bytes(
sysfsfile_eeprom, (offset + SFP_TEMPE_OFFSET), SFP_TEMPE_WIDTH)
if dom_temperature_raw is not None:
print(dom_temperature_raw)
dom_temperature_data = sfpd_obj.parse_temperature(dom_temperature_raw, 0)
print(dom_temperature_data)
else:
return None
dom_voltage_raw = self._read_eeprom_specific_bytes(
sysfsfile_eeprom, (offset + SFP_VLOT_OFFSET), SFP_VOLT_WIDTH)
if dom_voltage_raw is not None:
print(dom_voltage_raw)
dom_voltage_data = sfpd_obj.parse_voltage(dom_voltage_raw, 0)
else:
return None
dom_channel_monitor_raw = self._read_eeprom_specific_bytes(
sysfsfile_eeprom, (offset + SFP_CHANNL_MON_OFFSET), SFP_CHANNL_MON_WIDTH)
if dom_channel_monitor_raw is not None:
dom_channel_monitor_data = sfpd_obj.parse_channel_monitor_params(dom_channel_monitor_raw, 0)
else:
return None
try:
sysfsfile_eeprom.close()
except IOError:
print("Error: closing sysfs file %s" % file_path)
return None
transceiver_dom_info_dict['temperature'] = dom_temperature_data['data']['Temperature']['value']
transceiver_dom_info_dict['voltage'] = dom_voltage_data['data']['Vcc']['value']
transceiver_dom_info_dict['rx1power'] = dom_channel_monitor_data['data']['RXPower']['value']
transceiver_dom_info_dict['rx2power'] = 'N/A'
transceiver_dom_info_dict['rx3power'] = 'N/A'
transceiver_dom_info_dict['rx4power'] = 'N/A'
transceiver_dom_info_dict['tx1bias'] = dom_channel_monitor_data['data']['TXBias']['value']
transceiver_dom_info_dict['tx2bias'] = 'N/A'
transceiver_dom_info_dict['tx3bias'] = 'N/A'
transceiver_dom_info_dict['tx4bias'] = 'N/A'
transceiver_dom_info_dict['tx1power'] = dom_channel_monitor_data['data']['TXPower']['value']
transceiver_dom_info_dict['tx2power'] = 'N/A'
transceiver_dom_info_dict['tx3power'] = 'N/A'
transceiver_dom_info_dict['tx4power'] = 'N/A'
return transceiver_dom_info_dict
def get_transceiver_change_event(self, timeout=0):
global monitor
port_dict = {}
with SWPSEventMonitor() as monitor:
for event in monitor:
if event['SUBSYSTEM'] == 'swps':
#print('SWPS event. From %s, ACTION %s, IF_TYPE %s, IF_LANE %s' % (event['DEVPATH'], event['ACTION'], event['IF_TYPE'], event['IF_LANE']))
portname = event['DEVPATH'].split("/")[-1]
rc = re.match(r"port(?P<num>\d+)", portname)
if rc is not None:
if event['ACTION'] == "remove":
remove_num = int(rc.group("num"))
port_dict[remove_num] = "0"
#port_dict[rc.group("num")] = "0"
if event['ACTION'] == "add":
add_num = int(rc.group("num"))
port_dict[add_num] = "1"
#port_dict[rc.group("num")] = "1"
return True, port_dict
return False, {}