Fix pytest issue

This commit is contained in:
roger530-ho 2023-03-15 01:42:57 +00:00
parent cb2be41675
commit 2a96a94a29
No known key found for this signature in database
GPG Key ID: 9BFB0185DB2A8016
14 changed files with 1320 additions and 177 deletions

View File

@ -4,7 +4,7 @@
"num_psus":2,
"num_fantrays":6,
"num_fans_pertray":2,
"num_ports":34,
"num_ports":32,
"num_temps":6,
"pddf_dev_types":
{
@ -1657,7 +1657,11 @@
{ "attr_name":"psu_i_out", "attr_devaddr":"0x58", "attr_devtype":"pmbus", "attr_offset":"0x8c", "attr_mask":"0x0", "attr_cmpval":"0xff", "attr_len":"2"},
{ "attr_name":"psu_p_out", "attr_devaddr":"0x58", "attr_devtype":"pmbus", "attr_offset":"0x96", "attr_mask":"0x0", "attr_cmpval":"0xff", "attr_len":"2"},
{ "attr_name":"psu_fan1_speed_rpm", "attr_devaddr":"0x58", "attr_devtype":"pmbus", "attr_offset":"0x90", "attr_mask":"0x0", "attr_cmpval":"0xff", "attr_len":"2"},
{ "attr_name":"psu_temp1_input", "attr_devaddr":"0x58", "attr_devtype":"pmbus", "attr_offset":"0x8d", "attr_mask":"0x0", "attr_cmpval":"0xff", "attr_len":"2"}
{ "attr_name":"psu_temp1_input", "attr_devaddr":"0x58", "attr_devtype":"pmbus", "attr_offset":"0x8d", "attr_mask":"0x0", "attr_cmpval":"0xff", "attr_len":"2"},
{ "attr_name":"psu_v_out_max", "attr_devaddr":"0x58", "attr_devtype":"pmbus", "attr_offset":"0xa5", "attr_mask":"0x0", "attr_cmpval":"0xff", "attr_len":"2"},
{ "attr_name":"psu_v_out_min", "attr_devaddr":"0x58", "attr_devtype":"pmbus", "attr_offset":"0xa4", "attr_mask":"0x0", "attr_cmpval":"0xff", "attr_len":"2"},
{ "attr_name":"psu_p_out_max", "attr_devaddr":"0x58", "attr_devtype":"pmbus", "attr_offset":"0xa7", "attr_mask":"0x0", "attr_cmpval":"0xff", "attr_len":"2"},
{ "attr_name":"psu_temp1_high_threshold", "attr_devaddr":"0x58", "attr_devtype":"pmbus", "attr_offset":"0xa8", "attr_mask":"0x0", "attr_cmpval":"0xff", "attr_len":"2"}
]
}
},
@ -1705,7 +1709,11 @@
{ "attr_name":"psu_i_out", "attr_devaddr":"0x5b", "attr_devtype":"pmbus", "attr_offset":"0x8c", "attr_mask":"0x0", "attr_cmpval":"0xff", "attr_len":"2"},
{ "attr_name":"psu_p_out", "attr_devaddr":"0x5b", "attr_devtype":"pmbus", "attr_offset":"0x96", "attr_mask":"0x0", "attr_cmpval":"0xff", "attr_len":"2"},
{ "attr_name":"psu_fan1_speed_rpm", "attr_devaddr":"0x5b", "attr_devtype":"pmbus", "attr_offset":"0x90", "attr_mask":"0x0", "attr_cmpval":"0xff", "attr_len":"2"},
{ "attr_name":"psu_temp1_input", "attr_devaddr":"0x5b", "attr_devtype":"pmbus", "attr_offset":"0x8d", "attr_mask":"0x0", "attr_cmpval":"0xff", "attr_len":"2"}
{ "attr_name":"psu_temp1_input", "attr_devaddr":"0x5b", "attr_devtype":"pmbus", "attr_offset":"0x8d", "attr_mask":"0x0", "attr_cmpval":"0xff", "attr_len":"2"},
{ "attr_name":"psu_v_out_max", "attr_devaddr":"0x5b", "attr_devtype":"pmbus", "attr_offset":"0xa5", "attr_mask":"0x0", "attr_cmpval":"0xff", "attr_len":"2"},
{ "attr_name":"psu_v_out_min", "attr_devaddr":"0x5b", "attr_devtype":"pmbus", "attr_offset":"0xa4", "attr_mask":"0x0", "attr_cmpval":"0xff", "attr_len":"2"},
{ "attr_name":"psu_p_out_max", "attr_devaddr":"0x5b", "attr_devtype":"pmbus", "attr_offset":"0xa7", "attr_mask":"0x0", "attr_cmpval":"0xff", "attr_len":"2"},
{ "attr_name":"psu_temp1_high_threshold", "attr_devaddr":"0x5b", "attr_devtype":"pmbus", "attr_offset":"0xa8", "attr_mask":"0x0", "attr_cmpval":"0xff", "attr_len":"2"}
]
}
},

View File

@ -1,6 +1,11 @@
{
"chassis": {
"name": "7726-32X",
"thermal_manager":false,
"status_led": {
"controllable": true,
"colors": ["green", "red", "off"]
},
"components": [
{
"name": "MB_CPLD1"
@ -23,112 +28,298 @@
],
"fans": [
{
"name": "FAN-1F"
"name": "FAN-1F",
"speed": {
"controllable": true,
"minimum": 32
},
"status_led": {
"controllable": false
}
},
{
"name": "FAN-1R"
"name": "FAN-1R",
"speed": {
"controllable": true,
"minimum": 32
},
"status_led": {
"controllable": false
}
},
{
"name": "FAN-2F"
"name": "FAN-2F",
"speed": {
"controllable": true,
"minimum": 32
},
"status_led": {
"controllable": false
}
},
{
"name": "FAN-2R"
"name": "FAN-2R",
"speed": {
"controllable": true,
"minimum": 32
},
"status_led": {
"controllable": false
}
},
{
"name": "FAN-3F"
"name": "FAN-3F",
"speed": {
"controllable": true,
"minimum": 32
},
"status_led": {
"controllable": false
}
},
{
"name": "FAN-3R"
"name": "FAN-3R",
"speed": {
"controllable": true,
"minimum": 32
},
"status_led": {
"controllable": false
}
},
{
"name": "FAN-4F"
"name": "FAN-4F",
"speed": {
"controllable": true,
"minimum": 32
},
"status_led": {
"controllable": false
}
},
{
"name": "FAN-4R"
"name": "FAN-4R",
"speed": {
"controllable": true,
"minimum": 32
},
"status_led": {
"controllable": false
}
},
{
"name": "FAN-5F"
"name": "FAN-5F",
"speed": {
"controllable": true,
"minimum": 32
},
"status_led": {
"controllable": false
}
},
{
"name": "FAN-5R"
"name": "FAN-5R",
"speed": {
"controllable": true,
"minimum": 32
},
"status_led": {
"controllable": false
}
},
{
"name": "FAN-6F"
"name": "FAN-6F",
"speed": {
"controllable": true,
"minimum": 32
},
"status_led": {
"controllable": false
}
},
{
"name": "FAN-6R"
"name": "FAN-6R",
"speed": {
"controllable": true,
"minimum": 32
},
"status_led": {
"controllable": false
}
}
],
"fan_drawers":[
{
"name": "FanTray1",
"status_led": {
"controllable": false
},
"num_fans" : 2,
"fans": [
{
"name": "FAN-1F"
"name": "FAN-1F",
"speed": {
"controllable": true,
"minimum": 32
},
"status_led": {
"controllable": false
}
},
{
"name": "FAN-1R"
"name": "FAN-1R",
"speed": {
"controllable": true,
"minimum": 32
},
"status_led": {
"controllable": false
}
}
]
},
{
"name": "FanTray2",
"status_led": {
"controllable": false
},
"num_fans" : 2,
"fans": [
{
"name": "FAN-2F"
"name": "FAN-2F",
"speed": {
"controllable": true,
"minimum": 32
},
"status_led": {
"controllable": false
}
},
{
"name": "FAN-2R"
"name": "FAN-2R",
"speed": {
"controllable": true,
"minimum": 32
},
"status_led": {
"controllable": false
}
}
]
},
{
"name": "FanTray3",
"status_led": {
"controllable": false
},
"num_fans" : 2,
"fans": [
{
"name": "FAN-3F"
"name": "FAN-3F",
"speed": {
"controllable": true,
"minimum": 32
},
"status_led": {
"controllable": false
}
},
{
"name": "FAN-3R"
"name": "FAN-3R",
"speed": {
"controllable": true,
"minimum": 32
},
"status_led": {
"controllable": false
}
}
]
},
{
"name": "FanTray4",
"status_led": {
"controllable": false
},
"num_fans" : 2,
"fans": [
{
"name": "FAN-4F"
"name": "FAN-4F",
"speed": {
"controllable": true,
"minimum": 32
},
"status_led": {
"controllable": false
}
},
{
"name": "FAN-4R"
"name": "FAN-4R",
"speed": {
"controllable": true,
"minimum": 32
},
"status_led": {
"controllable": false
}
}
]
},
{
"name": "FanTray5",
"status_led": {
"controllable": false
},
"num_fans" : 2,
"fans": [
{
"name": "FAN-5F"
"name": "FAN-5F",
"speed": {
"controllable": true,
"minimum": 32
},
"status_led": {
"controllable": false
}
},
{
"name": "FAN-5R"
"name": "FAN-5R",
"speed": {
"controllable": true,
"minimum": 32
},
"status_led": {
"controllable": false
}
}
]
},
{
"name": "FanTray6",
"status_led": {
"controllable": false
},
"num_fans" : 2,
"fans": [
{
"name": "FAN-6F"
"name": "FAN-6F",
"speed": {
"controllable": true,
"minimum": 32
},
"status_led": {
"controllable": false
}
},
{
"name": "FAN-6R"
"name": "FAN-6R",
"speed": {
"controllable": true,
"minimum": 32
},
"status_led": {
"controllable": false
}
}
]
}
@ -136,6 +327,9 @@
"psus": [
{
"name": "PSU-1",
"status_led": {
"controllable": false
},
"fans": [
{
"name": "PSU-1 FAN-1"
@ -143,12 +337,18 @@
],
"thermals": [
{
"name": "PSU-1 temp sensor 1"
"name": "PSU-1 temp sensor 1",
"controllable": false,
"low-crit-threshold": false,
"high-crit-threshold": false
}
]
},
{
"name": "PSU-2",
"status_led": {
"controllable": false
},
"fans": [
{
"name": "PSU-2 FAN-1"
@ -156,29 +356,62 @@
],
"thermals": [
{
"name": "PSU-2 temp sensor 1"
"name": "PSU-2 temp sensor 2",
"controllable": false,
"low-crit-threshold": false,
"high-crit-threshold": false
}
]
}
],
"thermals": [
{
"name": "CB_temp(0x4B)"
"name": "CB_temp(0x4B)",
"controllable": true,
"low-threshold": false,
"high-threshold": true,
"low-crit-threshold": false,
"high-crit-threshold": false
},
{
"name": "FB_temp(0x4C)"
"name": "FB_temp(0x4C)",
"controllable": true,
"low-threshold": false,
"high-threshold": true,
"low-crit-threshold": false,
"high-crit-threshold": false
},
{
"name": "MB_FrontMAC_temp(0x49)"
"name": "MB_FrontMAC_temp(0x49)",
"controllable": true,
"low-threshold": false,
"high-threshold": true,
"low-crit-threshold": false,
"high-crit-threshold": false
},
{
"name": "MB_LeftCenter_temp(0x4A)"
"name": "MB_LeftCenter_temp(0x4A)",
"controllable": true,
"low-threshold": false,
"high-threshold": true,
"low-crit-threshold": false,
"high-crit-threshold": false
},
{
"name": "MB_RearMAC_temp(0x48)"
"name": "MB_RearMAC_temp(0x48)",
"controllable": true,
"low-threshold": false,
"high-threshold": true,
"low-crit-threshold": false,
"high-crit-threshold": false
},
{
"name": "coretemp-isa-0000"
"name": "coretemp-isa-0000",
"controllable": false,
"low-threshold": false,
"high-threshold": true,
"low-crit-threshold": false,
"high-crit-threshold": true
}
],
"sfps": [

View File

@ -0,0 +1,14 @@
{
"chassis": {
"7726-32X-O-AC-F": {
"component": {
"MB_CPLD1": { },
"MB_CPLD2": { },
"MB_CPLD3": { },
"FAN_CPLD": { },
"CPU_CPLD": { },
"BIOS": { }
}
}
}
}

View File

@ -1,9 +1,7 @@
{
"services_to_ignore": [],
"devices_to_ignore": [
"asic",
"psu.voltage",
"psu.temperature"
"asic"
],
"user_defined_checkers": [],
"polling_interval": 60,

View File

@ -129,4 +129,4 @@ class Chassis(PddfChassis):
Returns:
string: Revision value of device
"""
return 'N/A'
return self._eeprom.revision_str()

View File

@ -6,8 +6,10 @@
#############################################################################
try:
import subprocess
import os
import json
from sonic_platform_base.component_base import ComponentBase
from sonic_py_common.general import getstatusoutput_noshell
except ImportError as e:
raise ImportError(str(e) + "- required module not found")
@ -52,8 +54,8 @@ class Component(ComponentBase):
# Retrieves the CPLD firmware version
cpld_version = dict()
for cpld_name in CPLD_ADDR_MAPPING:
cmd = "i2cget -f -y {0} {1} 0x1".format(CPLD_ADDR_MAPPING[cpld_name][0], CPLD_ADDR_MAPPING[cpld_name][1])
status, value = subprocess.getstatusoutput(cmd)
cmd = ["i2cget", "-f", "-y", CPLD_ADDR_MAPPING[cpld_name][0], CPLD_ADDR_MAPPING[cpld_name][1], "0x1"]
status, value = getstatusoutput_noshell(cmd)
if not status:
cpld_version_raw = value.rstrip()
cpld_version[cpld_name] = "{}".format(int(cpld_version_raw,16))
@ -100,7 +102,36 @@ class Component(ComponentBase):
Returns:
A boolean, True if install successfully, False if not
"""
raise NotImplementedError
ret, output = getstatusoutput_noshell(["tar", "-C", "/tmp", "-xzf", image_path ] )
if ret != 0 :
print("Installation failed because of wrong image package")
return False
if False == os.path.exists("/tmp/install.json") :
print("Installation failed without jsonfile")
return False
input_file = open ('/tmp/install.json')
json_array = json.load(input_file)
ret = 1
for item in json_array:
if item.get('id')==None or item.get('path')==None:
continue
if self.name == item['id'] and item['path'] and item.get('cpu'):
print( "Find", item['id'], item['path'], item['cpu'] )
ret, output = getstatusoutput_noshell(["/tmp/run_install.sh", item['id'], item['path'], item['cpu'] ])
if ret==0:
break
elif self.name == item['id'] and item['path']:
print( "Find", item['id'], item['path'] )
ret, output = getstatusoutput_noshell(["/tmp/run_install.sh", item['id'], item['path'] ])
if ret==0:
break
if ret==0:
return True
else :
return False
def get_presence(self):
"""

View File

@ -2,87 +2,13 @@
try:
from sonic_platform_pddf_base.pddf_eeprom import PddfEeprom
import os
except ImportError as e:
raise ImportError(str(e) + "- required module not found")
CACHE_ROOT = '/var/cache/sonic/decode-syseeprom'
CACHE_FILE = 'syseeprom_cache'
class Eeprom(PddfEeprom):
_TLV_INFO_MAX_LEN = 256
pddf_obj = {}
plugin_data = {}
def __init__(self, pddf_data=None, pddf_plugin_data=None):
#PddfEeprom.__init__(self, pddf_data, pddf_plugin_data)
if not pddf_data or not pddf_plugin_data:
raise ValueError('PDDF JSON data error')
self.pddf_obj = pddf_data
self.plugin_data = pddf_plugin_data
# system EEPROM always has device name EEPROM1
self.eeprom_path = self.pddf_obj.get_path("EEPROM1", "eeprom")
if self.eeprom_path is None:
return
super(PddfEeprom, self).__init__(self.eeprom_path, 0, '', True)
self.eeprom_tlv_dict = dict()
# Create the cache directory if not created
if not os.path.exists(CACHE_ROOT):
try:
os.makedirs(CACHE_ROOT)
except Exception as e:
print("Error in creating Eeprom cache directory - {}".format(str(e)))
# Assign cache_name in eeprom_base.py
try:
self.set_cache_name(os.path.join(CACHE_ROOT, CACHE_FILE))
except:
pass
try:
self.eeprom_data = self.read_eeprom()
except Exception as e:
self.eeprom_data = "N/A"
raise RuntimeError("Eeprom is not Programmed - Error: {}".format(str(e)))
else:
eeprom = self.eeprom_data
try:
self.update_cache(eeprom)
except:
pass
if not self.is_valid_tlvinfo_header(eeprom):
return
total_length = ((eeprom[9]) << 8) | (eeprom[10])
tlv_index = self._TLV_INFO_HDR_LEN
tlv_end = self._TLV_INFO_HDR_LEN + total_length
while (tlv_index + 2) < len(eeprom) and tlv_index < tlv_end:
if not self.is_valid_tlv(eeprom[tlv_index:]):
break
tlv = eeprom[tlv_index:tlv_index + 2
+ (eeprom[tlv_index + 1])]
code = "0x%02X" % ((tlv[0]))
if (tlv[0]) == self._TLV_CODE_VENDOR_EXT:
value = str(((tlv[2]) << 24) | ((tlv[3]) << 16) |
((tlv[4]) << 8) | (tlv[5]))
value += str(tlv[6:6 + (tlv[1])])
else:
name, value = self.decoder(None, tlv)
self.eeprom_tlv_dict[code] = value
if (eeprom[tlv_index]) == self._TLV_CODE_CRC_32:
break
tlv_index += (eeprom[tlv_index+1]) + 2
PddfEeprom.__init__(self, pddf_data, pddf_plugin_data)
# Provide the functions/variables below for which implementation is to be overwritten

View File

@ -1,11 +1,21 @@
try:
import time
from sonic_py_common.logger import Logger
from .sfp import Sfp
except ImportError as e:
raise ImportError(repr(e) + " - required module not found")
POLL_INTERVAL_IN_SEC = 1
# SFP errors that will block eeprom accessing
SFP_BLOCKING_ERRORS = [
Sfp.SFP_ERROR_BIT_I2C_STUCK,
Sfp.SFP_ERROR_BIT_BAD_EEPROM,
Sfp.SFP_ERROR_BIT_UNSUPPORTED_CABLE,
Sfp.SFP_ERROR_BIT_HIGH_TEMP,
Sfp.SFP_ERROR_BIT_BAD_CABLE
]
class SfpEvent:
''' Listen to insert/remove sfp events '''
@ -46,15 +56,54 @@ class SfpEvent:
if changed_ports != 0:
for sfp in self._sfp_list:
i=sfp.get_position_in_parent() - 1
if (changed_ports & (1 << i)):
if (bitmap & (1 << i)) == 0:
port_dict[i+1] = '0'
else:
port_dict[i+1] = '1'
if (changed_ports & (1 << i)) == 0:
continue
if (bitmap & (1 << i)) == 0:
port_dict[i+1] = '0'
else:
# sfp.refresh_optoe_dev_class()
sfp_state_bits = self.get_sfp_state_bits(sfp, True)
sfp_state_bits = self.check_sfp_blocking_errors(sfp_state_bits)
port_dict[i+1] = str(sfp_state_bits)
# Update the cache dict
self._sfp_change_event_data['present'] = bitmap
return True, change_dict
else:
return True, change_dict
def get_sfp_state_bits(self, sfp, present):
sfp_state_bits = 0
if present is True:
sfp_state_bits |= Sfp.SFP_STATUS_BIT_INSERTED
else:
return sfp_state_bits
status = sfp.validate_eeprom()
if status is None:
sfp_state_bits |= Sfp.SFP_ERROR_BIT_I2C_STUCK
return sfp_state_bits
elif status is not True:
sfp_state_bits |= Sfp.SFP_ERROR_BIT_BAD_EEPROM
return sfp_state_bits
status = sfp.validate_temperature()
if status is None:
sfp_state_bits |= Sfp.SFP_ERROR_BIT_I2C_STUCK
return sfp_state_bits
elif status is not True:
sfp_state_bits |= Sfp.SFP_ERROR_BIT_HIGH_TEMP
return sfp_state_bits
return sfp_state_bits
def check_sfp_blocking_errors(self, sfp_state_bits):
for i in SFP_BLOCKING_ERRORS:
if (i & sfp_state_bits) == 0:
continue
sfp_state_bits |= Sfp.SFP_ERROR_BIT_BLOCKING
return sfp_state_bits

View File

@ -63,3 +63,16 @@ class Fan(PddfFan):
return super().get_speed()
else:
return super().get_target_speed()
def get_direction(self):
"""
Retrieves the direction of fan
Returns:
A string, either FAN_DIRECTION_INTAKE or FAN_DIRECTION_EXHAUST
depending on fan direction
"""
direction = super().get_direction()
if direction is not None and len(direction) > 0:
return direction
return 'N/A'

View File

@ -1,8 +1,14 @@
import os
import struct
import subprocess
import json
import fcntl
from mmap import *
from sonic_py_common import device_info
from sonic_py_common import logger
from threading import Lock
from typing import cast
from sonic_py_common.general import getstatusoutput_noshell_pipe
from sonic_py_common.general import getstatusoutput_noshell
HOST_CHK_CMD = ["docker"]
EMPTY_STRING = ""
@ -33,6 +39,13 @@ class APIHelper():
status = False
return status, result
def run_interactive_command(self, cmd):
try:
os.system(cmd)
except Exception:
return False
return True
def read_txt_file(self, file_path):
try:
with open(file_path, 'r', errors='replace') as fd:
@ -51,3 +64,305 @@ class APIHelper():
except IOError:
return False
return True
def ipmi_raw(self, netfn, cmd):
status = True
result = ""
try:
err, raw_data = getstatusoutput_noshell_pipe(['ipmitool', 'raw', str(netfn), str(cmd)])
if err == [0]:
result = raw_data.strip()
else:
status = False
except Exception:
status = False
return status, result
def ipmi_fru_id(self, id, key=None):
status = True
result = ""
try:
if (key is None):
err, raw_data = getstatusoutput_noshell_pipe(['ipmitool', 'fru', 'print', str(id)])
else:
err, raw_data = getstatusoutput_noshell_pipe(['ipmitool', 'fru', 'print', str(id)], ['grep', str(key)])
if err == [0] or err == [0, 0]:
result = raw_data.strip()
else:
status = False
except Exception:
status = False
return status, result
def ipmi_set_ss_thres(self, id, threshold_key, value):
status = True
result = ""
try:
err, raw_data = getstatusoutput_noshell_pipe(['ipmitool', 'sensor', 'thresh', str(id), str(threshold_key), str(value)])
if err == [0]:
result = raw_data.strip()
else:
status = False
except Exception:
status = False
return status, result
class FileLock:
"""
Due to pmon docker not installing the py-filelock, this class
implements a simple file lock feature.
Ref: https://github.com/tox-dev/py-filelock/blob/main/src/filelock/
"""
def __init__(self, lock_file):
self._lock_file = lock_file
self._thread_lock = Lock()
self.is_locked = False
def acquire(self):
with self._thread_lock:
if self.is_locked:
return
fd = os.open(self._lock_file, flags=(os.O_RDWR | os.O_CREAT | os.O_TRUNC))
fcntl.flock(fd, fcntl.LOCK_EX)
self._lock_file_fd = fd
self.is_locked = True
def release(self):
with self._thread_lock:
if self.is_locked:
fd = cast(int, self._lock_file_fd)
self._lock_file_fd = None
fcntl.flock(fd, fcntl.LOCK_UN)
os.close(fd)
self.is_locked = False
def __enter__(self):
self.acquire()
return self
def __exit__(self, exc_type, exc_val, traceback):
self.release()
def __del__(self):
self.release()
DEVICE_THRESHOLD_JSON_PATH = "/tmp/device_threshold.json"
class DeviceThreshold:
HIGH_THRESHOLD = 'high_threshold'
LOW_THRESHOLD = 'low_threshold'
HIGH_CRIT_THRESHOLD = 'high_critical_threshold'
LOW_CRIT_THRESHOLD = 'low_critical_threshold'
NOT_AVAILABLE = 'N/A'
def __init__(self, th_name = NOT_AVAILABLE):
self.flock = FileLock("{}.lock".format(DEVICE_THRESHOLD_JSON_PATH))
self.name = th_name
self.__log = logger.Logger(log_identifier="DeviceThreshold")
self.__db_data = {}
self.__db_mtime = 0
def __reload_db(self):
try:
db_data = {}
with self.flock:
with open(DEVICE_THRESHOLD_JSON_PATH, "r") as db_file:
db_data = json.load(db_file)
except Exception as e:
self.__log.log_warning('{}'.format(str(e)))
return None
return db_data
def __get_data(self, field):
"""
Retrieves data frome JSON file by field
Args :
field: String
Returns:
A string if getting is successfully, 'N/A' if not
"""
if os.path.exists(DEVICE_THRESHOLD_JSON_PATH):
new_mtime = os.path.getmtime(DEVICE_THRESHOLD_JSON_PATH)
if new_mtime != self.__db_mtime:
new_data = self.__reload_db()
if new_data is not None:
self.__db_data = new_data
self.__db_mtime = new_mtime
if self.name not in self.__db_data.keys():
return self.NOT_AVAILABLE
if field not in self.__db_data[self.name].keys():
return self.NOT_AVAILABLE
return self.__db_data[self.name][field]
def __set_data(self, field, new_val):
"""
Set data to JSON file by field
Args :
field: String
new_val: String
Returns:
A boolean, True if setting is set successfully, False if not
"""
if self.name not in self.__db_data.keys():
self.__db_data[self.name] = {}
old_val = self.__db_data[self.name].get(field, None)
if old_val is not None and old_val == new_val:
return True
self.__db_data[self.name][field] = new_val
try:
with self.flock:
db_data = {}
mode = "r+" if os.path.exists(DEVICE_THRESHOLD_JSON_PATH) else "w+"
with open(DEVICE_THRESHOLD_JSON_PATH, mode) as db_file:
if mode == "r+":
db_data = json.load(db_file)
if self.name not in db_data.keys():
db_data[self.name] = {}
db_data[self.name][field] = new_val
if mode == "r+":
db_file.seek(0)
# erase old data
db_file.truncate(0)
# write all data
json.dump(db_data, db_file, indent=4)
self.__db_mtime = os.path.getmtime(DEVICE_THRESHOLD_JSON_PATH)
except Exception as e:
self.__log.log_error('{}'.format(str(e)))
return False
return True
def get_high_threshold(self):
"""
Retrieves the high threshold temperature from JSON file.
Returns:
string : the high threshold temperature of thermal,
e.g. "30.125"
"""
return self.__get_data(self.HIGH_THRESHOLD)
def set_high_threshold(self, temperature):
"""
Sets the high threshold temperature of thermal
Args :
temperature: A string of temperature, e.g. "30.125"
Returns:
A boolean, True if threshold is set successfully, False if not
"""
if isinstance(temperature, str) is not True:
raise TypeError('The parameter requires string type.')
try:
if temperature != self.NOT_AVAILABLE:
float(temperature)
except ValueError:
raise ValueError('The parameter requires a float string. ex:\"30.1\"')
return self.__set_data(self.HIGH_THRESHOLD, temperature)
def get_low_threshold(self):
"""
Retrieves the low threshold temperature from JSON file.
Returns:
string : the low threshold temperature of thermal,
e.g. "30.125"
"""
return self.__get_data(self.LOW_THRESHOLD)
def set_low_threshold(self, temperature):
"""
Sets the low threshold temperature of thermal
Args :
temperature: A string of temperature, e.g. "30.125"
Returns:
A boolean, True if threshold is set successfully, False if not
"""
if isinstance(temperature, str) is not True:
raise TypeError('The parameter requires string type.')
try:
if temperature != self.NOT_AVAILABLE:
float(temperature)
except ValueError:
raise ValueError('The parameter requires a float string. ex:\"30.1\"')
return self.__set_data(self.LOW_THRESHOLD, temperature)
def get_high_critical_threshold(self):
"""
Retrieves the high critical threshold temperature from JSON file.
Returns:
string : the high critical threshold temperature of thermal,
e.g. "30.125"
"""
return self.__get_data(self.HIGH_CRIT_THRESHOLD)
def set_high_critical_threshold(self, temperature):
"""
Sets the high critical threshold temperature of thermal
Args :
temperature: A string of temperature, e.g. "30.125"
Returns:
A boolean, True if threshold is set successfully, False if not
"""
if isinstance(temperature, str) is not True:
raise TypeError('The parameter requires string type.')
try:
if temperature != self.NOT_AVAILABLE:
float(temperature)
except ValueError:
raise ValueError('The parameter requires a float string. ex:\"30.1\"')
return self.__set_data(self.HIGH_CRIT_THRESHOLD, temperature)
def get_low_critical_threshold(self):
"""
Retrieves the low critical threshold temperature from JSON file.
Returns:
string : the low critical threshold temperature of thermal,
e.g. "30.125"
"""
return self.__get_data(self.LOW_CRIT_THRESHOLD)
def set_low_critical_threshold(self, temperature):
"""
Sets the low critical threshold temperature of thermal
Args :
temperature: A string of temperature, e.g. "30.125"
Returns:
A boolean, True if threshold is set successfully, False if not
"""
if isinstance(temperature, str) is not True:
raise TypeError('The parameter requires string type.')
try:
if temperature != self.NOT_AVAILABLE:
float(temperature)
except ValueError:
raise ValueError('The parameter requires a float string. ex:\"30.1\"')
return self.__set_data(self.LOW_CRIT_THRESHOLD, temperature)

View File

@ -11,8 +11,6 @@ except ImportError as e:
class Psu(PddfPsu):
"""PDDF Platform-Specific PSU class"""
PLATFORM_PSU_CAPACITY = 1200
def __init__(self, index, pddf_data=None, pddf_plugin_data=None):
PddfPsu.__init__(self, index, pddf_data, pddf_plugin_data)
@ -38,28 +36,30 @@ class Psu(PddfPsu):
def get_name(self):
return "PSU-{}".format(self.psu_index)
def get_maximum_supplied_power(self):
def get_temperature_high_threshold(self):
"""
Retrieves the maximum supplied power by PSU (or PSU capacity)
Retrieves the high threshold temperature of PSU
Returns:
A float number, the maximum power output in Watts.
e.g. 1200.1
A float number, the high threshold temperature of PSU in Celsius
up to nearest thousandth of one degree Celsius, e.g. 30.125
"""
return float(self.PLATFORM_PSU_CAPACITY)
threshold = super().get_temperature_high_threshold()
def get_capacity(self):
for psu_thermal_idx in range(self.num_psu_thermals):
try:
tmp = self._thermal_list[psu_thermal_idx].get_high_threshold()
if threshold > tmp or threshold == 0.0:
threshold = tmp
except Exception:
pass
return threshold
def get_revision(self):
"""
Gets the capacity (maximum output power) of the PSU in watts
Retrieves the hardware revision of the device
Returns:
An integer, the capacity of PSU
string: Revision value of device
"""
return (self.PLATFORM_PSU_CAPACITY)
def get_type(self):
"""
Gets the type of the PSU
Returns:
A string, the type of PSU (AC/DC)
"""
return "AC"
return 'N/A'

View File

@ -14,8 +14,20 @@ class Sfp(PddfSfp):
PDDF Platform-Specific Sfp class
"""
SFP_TYPE_CODE_LIST = [
0x03, # SFP/SFP+/SFP28
0x0b # DWDM-SFP/SFP+
]
QSFP_TYPE_CODE_LIST = [
0x0c, # QSFP
0x0d, # QSFP+ or later
0x11, # QSFP28 or later
0xe1 # QSFP28 EDFA
]
def __init__(self, index, pddf_data=None, pddf_plugin_data=None):
PddfSfp.__init__(self, index, pddf_data, pddf_plugin_data)
self.index = self.port_index
# Provide the functions/variables below for which implementation is to be overwritten
def __get_path_to_port_config_file(self):
@ -38,3 +50,144 @@ class Sfp(PddfSfp):
name = logical_port_list[self.port_index-1] or "Unknown"
return name
def __validate_eeprom_sfp(self):
checksum_test = 0
eeprom_raw = self.read_eeprom(0, 96)
if eeprom_raw is None:
return None
for i in range(0, 63):
checksum_test = (checksum_test + eeprom_raw[i]) & 0xFF
else:
if checksum_test != eeprom_raw[63]:
return False
checksum_test = 0
for i in range(64, 95):
checksum_test = (checksum_test + eeprom_raw[i]) & 0xFF
else:
if checksum_test != eeprom_raw[95]:
return False
api = self.get_xcvr_api()
if api is None:
return False
if api.is_flat_memory():
return True
checksum_test = 0
eeprom_raw = self.read_eeprom(384, 96)
if eeprom_raw is None:
return None
for i in range(0, 95):
checksum_test = (checksum_test + eeprom_raw[i]) & 0xFF
else:
if checksum_test != eeprom_raw[95]:
return False
return True
def __validate_eeprom_qsfp(self):
checksum_test = 0
eeprom_raw = self.read_eeprom(128, 96)
if eeprom_raw is None:
return None
for i in range(0, 63):
checksum_test = (checksum_test + eeprom_raw[i]) & 0xFF
else:
if checksum_test != eeprom_raw[63]:
return False
checksum_test = 0
for i in range(64, 95):
checksum_test = (checksum_test + eeprom_raw[i]) & 0xFF
else:
if checksum_test != eeprom_raw[95]:
return False
api = self.get_xcvr_api()
if api is None:
return False
if api.is_flat_memory():
return True
return True
def validate_eeprom(self):
id_byte_raw = self.read_eeprom(0, 1)
if id_byte_raw is None:
return None
id = id_byte_raw[0]
if id in self.QSFP_TYPE_CODE_LIST:
return self.__validate_eeprom_qsfp()
elif id in self.SFP_TYPE_CODE_LIST:
return self.__validate_eeprom_sfp()
else:
return False
def validate_temperature(self):
temperature = self.get_temperature()
if temperature is None:
return None
threshold_dict = self.get_transceiver_threshold_info()
if threshold_dict is None:
return None
if isinstance(temperature, float) is not True:
return True
if isinstance(threshold_dict['temphighalarm'], float) is not True:
return True
return threshold_dict['temphighalarm'] > temperature
def __get_error_description(self):
if not self.get_presence():
return self.SFP_STATUS_UNPLUGGED
err_stat = self.SFP_STATUS_BIT_INSERTED
status = self.validate_eeprom()
if status is not True:
err_stat = (err_stat | self.SFP_ERROR_BIT_BAD_EEPROM)
status = self.validate_temperature()
if status is not True:
err_stat = (err_stat | self.SFP_ERROR_BIT_HIGH_TEMP)
if err_stat is self.SFP_STATUS_BIT_INSERTED:
return self.SFP_STATUS_OK
else:
err_desc = ''
cnt = 0
for key in self.SFP_ERROR_BIT_TO_DESCRIPTION_DICT:
if (err_stat & key) != 0:
if cnt > 0:
err_desc = err_desc + "|"
cnt = cnt + 1
err_desc = err_desc + self.SFP_ERROR_BIT_TO_DESCRIPTION_DICT[key].replace(" ", "_")
return err_desc
def get_error_description(self):
"""
Retrives the error descriptions of the SFP module
Returns:
String that represents the current error descriptions of vendor specific errors
In case there are multiple errors, they should be joined by '|',
like: "Bad EEPROM|Unsupported cable"
"""
try:
ret = super().get_error_description()
if ret is not None:
return ret
except NotImplementedError:
pass
return self.__get_error_description()

View File

@ -3,17 +3,79 @@
try:
from sonic_platform_pddf_base.pddf_thermal import PddfThermal
from .helper import DeviceThreshold
except ImportError as e:
raise ImportError(str(e) + "- required module not found")
NOT_AVAILABLE = DeviceThreshold.NOT_AVAILABLE
HIGH_THRESHOLD = DeviceThreshold.HIGH_THRESHOLD
LOW_THRESHOLD = DeviceThreshold.LOW_THRESHOLD
HIGH_CRIT_THRESHOLD = DeviceThreshold.HIGH_CRIT_THRESHOLD
LOW_CRIT_THRESHOLD = DeviceThreshold.LOW_CRIT_THRESHOLD
DEFAULT_THRESHOLD = {
'CB_temp(0x4B)' : {
HIGH_THRESHOLD : '80.0',
LOW_THRESHOLD : NOT_AVAILABLE,
HIGH_CRIT_THRESHOLD : NOT_AVAILABLE,
LOW_CRIT_THRESHOLD : NOT_AVAILABLE
},
'FB_temp(0x4C)' : {
HIGH_THRESHOLD : '80.0',
LOW_THRESHOLD : NOT_AVAILABLE,
HIGH_CRIT_THRESHOLD : NOT_AVAILABLE,
LOW_CRIT_THRESHOLD : NOT_AVAILABLE
},
'MB_FrontMAC_temp(0x49)' : {
HIGH_THRESHOLD : '80.0',
LOW_THRESHOLD : NOT_AVAILABLE,
HIGH_CRIT_THRESHOLD : NOT_AVAILABLE,
LOW_CRIT_THRESHOLD : NOT_AVAILABLE
},
'MB_LeftCenter_temp(0x4A)' : {
HIGH_THRESHOLD : '80.0',
LOW_THRESHOLD : NOT_AVAILABLE,
HIGH_CRIT_THRESHOLD : NOT_AVAILABLE,
LOW_CRIT_THRESHOLD : NOT_AVAILABLE
},
'MB_RearMAC_temp(0x48)' : {
HIGH_THRESHOLD : '80.0',
LOW_THRESHOLD : NOT_AVAILABLE,
HIGH_CRIT_THRESHOLD : NOT_AVAILABLE,
LOW_CRIT_THRESHOLD : NOT_AVAILABLE
},
'coretemp-isa-0000' : {
HIGH_THRESHOLD : '82.0',
LOW_THRESHOLD : NOT_AVAILABLE,
HIGH_CRIT_THRESHOLD : '104.0',
LOW_CRIT_THRESHOLD : NOT_AVAILABLE
},
'PSU-1 temp sensor 1' : {
HIGH_THRESHOLD : '80.0',
LOW_THRESHOLD : NOT_AVAILABLE,
HIGH_CRIT_THRESHOLD : NOT_AVAILABLE,
LOW_CRIT_THRESHOLD : NOT_AVAILABLE
},
'PSU-2 temp sensor 1' : {
HIGH_THRESHOLD : '80.0',
LOW_THRESHOLD : NOT_AVAILABLE,
HIGH_CRIT_THRESHOLD : NOT_AVAILABLE,
LOW_CRIT_THRESHOLD : NOT_AVAILABLE
}
}
class Thermal(PddfThermal):
"""PDDF Platform-Specific Thermal class"""
def __init__(self, index, pddf_data=None, pddf_plugin_data=None, is_psu_thermal=False, psu_index=0):
PddfThermal.__init__(self, index, pddf_data, pddf_plugin_data, is_psu_thermal, psu_index)
# Threshold Configuration
self.__conf = DeviceThreshold(self.get_name())
# Default threshold.
self.__default_threshold = DEFAULT_THRESHOLD[self.get_name()]
self.min_temperature = None
self.max_temperature = None
self.pddf_obj = pddf_data
self.thermal_obj_name = "TEMP{}".format(self.thermal_index)
self.thermal_obj = self.pddf_obj.data[self.thermal_obj_name]
@ -36,3 +98,175 @@ class Thermal(PddfThermal):
if get_temp is not None:
return True if get_temp else False
def get_temperature(self):
current = super().get_temperature()
if self.min_temperature is None or \
current < self.min_temperature:
self.min_temperature = current
if self.max_temperature is None or \
current > self.max_temperature:
self.max_temperature = current
return current
def set_high_threshold(self, temperature):
try:
value = float(temperature)
except Exception:
return False
# The new value can not be more than the default value.
default_value = self.__default_threshold[HIGH_THRESHOLD]
if default_value != NOT_AVAILABLE:
if value > float(default_value):
return False
try:
self.__conf.set_high_threshold(str(value))
except Exception:
return False
return True
def get_high_threshold(self):
value = self.__conf.get_high_threshold()
if value != NOT_AVAILABLE:
return float(value)
default_value = self.__default_threshold[HIGH_THRESHOLD]
if default_value != NOT_AVAILABLE:
return float(default_value)
raise NotImplementedError
def set_low_threshold(self, temperature):
try:
value = float(temperature)
except Exception:
return False
# The new value can not be less than the default value.
default_value = self.__default_threshold[LOW_THRESHOLD]
if default_value != NOT_AVAILABLE:
if value < float(default_value):
return False
try:
self.__conf.set_low_threshold(str(value))
except Exception:
return False
return True
def get_low_threshold(self):
value = self.__conf.get_low_threshold()
if value != NOT_AVAILABLE:
return float(value)
default_value = self.__default_threshold[LOW_THRESHOLD]
if default_value != NOT_AVAILABLE:
return float(default_value)
raise NotImplementedError
def set_high_critical_threshold(self, temperature):
try:
value = float(temperature)
except Exception:
return False
# The new value can not be more than the default value.
default_value = self.__default_threshold[HIGH_CRIT_THRESHOLD]
if default_value != NOT_AVAILABLE:
if value > float(default_value):
return False
try:
self.__conf.set_high_critical_threshold(str(value))
except Exception:
return False
return True
def get_high_critical_threshold(self):
value = self.__conf.get_high_critical_threshold()
if value != NOT_AVAILABLE:
return float(value)
default_value = self.__default_threshold[HIGH_CRIT_THRESHOLD]
if default_value != NOT_AVAILABLE:
return float(default_value)
raise NotImplementedError
def set_low_critical_threshold(self, temperature):
try:
value = float(temperature)
except Exception:
return False
# The new value can not be less than the default value.
default_value = self.__default_threshold[LOW_CRIT_THRESHOLD]
if default_value != NOT_AVAILABLE:
if value < float(default_value):
return False
try:
self.__conf.set_low_critical_threshold(str(value))
except Exception:
return False
return True
def get_low_critical_threshold(self):
value = self.__conf.get_low_critical_threshold()
if value != NOT_AVAILABLE:
return float(value)
default_value = self.__default_threshold[LOW_CRIT_THRESHOLD]
if default_value != NOT_AVAILABLE:
return float(default_value)
raise NotImplementedError
def get_model(self):
"""
Retrieves the model number (or part number) of the device
Returns:
string: Model/part number of device
"""
return 'N/A'
def get_serial(self):
"""
Retrieves the serial number of the device
Returns:
string: Serial number of device
"""
return 'N/A'
def get_minimum_recorded(self):
"""
Retrieves the minimum recorded temperature of thermal
Returns:
A float number, the minimum recorded temperature of thermal in Celsius
up to nearest thousandth of one degree Celsius, e.g. 30.125
"""
if self.min_temperature is None:
self.get_temperature()
return self.min_temperature
def get_maximum_recorded(self):
"""
Retrieves the maximum recorded temperature of thermal
Returns:
A float number, the maximum recorded temperature of thermal in Celsius
up to nearest thousandth of one degree Celsius, e.g. 30.125
"""
if self.min_temperature is None:
self.get_temperature()
return self.max_temperature

View File

@ -16,22 +16,27 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
Usage: %(scriptName)s [options] command object
usage: accton_as7726_32x_util.py [-h] [-d] [-f] {install,clean,threshold} ...
options:
-h | --help : this help message
-d | --debug : run with debug mode
-f | --force : ignore error during installation or clean
command:
install : install drivers and generate related sysfs nodes
clean : uninstall drivers and remove related sysfs nodes
AS7726-32X Platform Utility
optional arguments:
-h, --help show this help message and exit
-d, --debug run with debug mode
-f, --force ignore error during installation or clean
Utility Command:
{install,clean,threshold}
install : install drivers and generate related sysfs nodes
clean : uninstall drivers and remove related sysfs nodes
threshold : modify thermal threshold
"""
import subprocess
import getopt
import sys
import logging
import re
import time
import argparse
from sonic_py_common.general import getstatusoutput_noshell
PROJECT_NAME = 'as7726_32x'
@ -109,37 +114,44 @@ def main():
global DEBUG
global args
global FORCE
global THRESHOLD_RANGE_LOW, THRESHOLD_RANGE_HIGH
if len(sys.argv)<2:
show_help()
util_parser = argparse.ArgumentParser(description="AS7726-32X Platform Utility")
util_parser.add_argument("-d", "--debug", dest='debug', action='store_true', default=False,
help="run with debug mode")
util_parser.add_argument("-f", "--force", dest='force', action='store_true', default=False,
help="ignore error during installation or clean")
subcommand = util_parser.add_subparsers(dest='cmd', title='Utility Command', required=True)
subcommand.add_parser('install', help=': install drivers and generate related sysfs nodes')
subcommand.add_parser('clean', help=': uninstall drivers and remove related sysfs nodes')
threshold_parser = subcommand.add_parser('threshold', help=': modify thermal threshold')
threshold_parser.add_argument("-l", dest='list', action='store_true', default=False,
help="list avaliable thermal")
threshold_parser.add_argument("-t", dest='thermal', type=str, metavar='THERMAL_NAME',
help="thermal name, ex: -t 'Temp sensor 1'")
threshold_parser.add_argument("-ht", dest='high_threshold', type=restricted_float,
metavar='THRESHOLD_VALUE',
help="high threshold: %.1f ~ %.1f" % (THRESHOLD_RANGE_LOW, THRESHOLD_RANGE_HIGH))
threshold_parser.add_argument("-hct", dest='high_crit_threshold', type=restricted_float,
metavar='THRESHOLD_VALUE',
help="high critical threshold : %.1f ~ %.1f" % (THRESHOLD_RANGE_LOW, THRESHOLD_RANGE_HIGH))
args = util_parser.parse_args()
options, args = getopt.getopt(sys.argv[1:], 'hdf', ['help',
'debug',
'force',
])
if DEBUG == True:
print(options)
print(args)
print((len(sys.argv)))
for opt, arg in options:
if opt in ('-h', '--help'):
show_help()
elif opt in ('-d', '--debug'):
DEBUG = True
logging.basicConfig(level=logging.INFO)
elif opt in ('-f', '--force'):
FORCE = 1
else:
logging.info('no option')
for arg in args:
if arg == 'install':
do_install()
elif arg == 'clean':
do_uninstall()
else:
show_help()
DEBUG = args.debug
if DEBUG:
logging.basicConfig(level=logging.INFO)
FORCE = 1 if args.force else 0
if args.cmd == 'install':
do_install()
elif args.cmd == 'clean':
do_uninstall()
elif args.cmd == 'threshold':
do_threshold()
return 0
@ -365,5 +377,162 @@ def device_exist():
ret2, log = log_os_system("ls "+i2c_prefix+"i2c-2", 0)
return not(ret1 or ret2)
THRESHOLD_RANGE_LOW = 30.0
THRESHOLD_RANGE_HIGH = 110.0
# Code to initialize chassis object
init_chassis_code = \
"import sonic_platform.platform\n"\
"platform = sonic_platform.platform.Platform()\n"\
"chassis = platform.get_chassis()\n\n"
# Looking for thermal
looking_for_thermal_code = \
"thermal = None\n"\
"all_thermals = chassis.get_all_thermals()\n"\
"for psu in chassis.get_all_psus():\n"\
" all_thermals += psu.get_all_thermals()\n"\
"for tmp in all_thermals:\n"\
" if '{}' == tmp.get_name():\n"\
" thermal = tmp\n"\
" break\n"\
"if thermal == None:\n"\
" print('{} not found!')\n"\
" exit(1)\n\n"
def avaliable_thermals():
global init_chassis_code
get_all_thermal_name_code = \
"thermal_list = []\n"\
"all_thermals = chassis.get_all_thermals()\n"\
"for psu in chassis.get_all_psus():\n"\
" all_thermals += psu.get_all_thermals()\n"\
"for tmp in all_thermals:\n"\
" thermal_list.append(tmp.get_name())\n"\
"print(str(thermal_list)[1:-1])\n"
all_code = "{}{}".format(init_chassis_code, get_all_thermal_name_code)
status, output = getstatusoutput_noshell(["docker", "exec", "pmon", "python3", "-c", all_code])
if status != 0:
return ""
return output
def restricted_float(x):
global THRESHOLD_RANGE_LOW, THRESHOLD_RANGE_HIGH
try:
x = float(x)
except ValueError:
raise argparse.ArgumentTypeError("%r not a floating-point literal" % (x,))
if x < THRESHOLD_RANGE_LOW or x > THRESHOLD_RANGE_HIGH:
raise argparse.ArgumentTypeError("%r not in range [%.1f ~ %.1f]" %
(x, THRESHOLD_RANGE_LOW, THRESHOLD_RANGE_HIGH))
return x
def get_high_threshold(name):
global init_chassis_code, looking_for_thermal_code
get_high_threshold_code = \
"try:\n"\
" print(thermal.get_high_threshold())\n"\
" exit(0)\n"\
"except NotImplementedError:\n"\
" print('Not implement the get_high_threshold method!')\n"\
" exit(1)"
all_code = "{}{}{}".format(init_chassis_code, looking_for_thermal_code.format(name, name),
get_high_threshold_code)
status, output = getstatusoutput_noshell(["docker", "exec", "pmon", "python3", "-c", all_code])
if status == 1:
return None
return float(output)
def get_high_crit_threshold(name):
global init_chassis_code, looking_for_thermal_code
get_high_crit_threshold_code = \
"try:\n"\
" print(thermal.get_high_critical_threshold())\n"\
" exit(0)\n"\
"except NotImplementedError:\n"\
" print('Not implement the get_high_critical_threshold method!')\n"\
" exit(1)"
all_code = "{}{}{}".format(init_chassis_code, looking_for_thermal_code.format(name, name),
get_high_crit_threshold_code)
status, output = getstatusoutput_noshell(["docker", "exec", "pmon", "python3", "-c", all_code])
if status == 1:
return None
return float(output)
def do_threshold():
global args, init_chassis_code, looking_for_thermal_code
if args.list:
print("Thermals: " + avaliable_thermals())
return
if args.thermal is None:
print("The following arguments are required: -t")
return
set_threshold_code = ""
if args.high_threshold is not None:
if args.high_crit_threshold is not None and \
args.high_threshold >= args.high_crit_threshold:
print("Invalid Threshold!(High threshold can not be more than " \
"or equal to high critical threshold.)")
exit(1)
high_crit = get_high_crit_threshold(args.thermal)
if high_crit is not None and \
args.high_threshold >= high_crit:
print("Invalid Threshold!(High threshold can not be more than " \
"or equal to high critical threshold.)")
exit(1)
set_threshold_code += \
"try:\n"\
" if thermal.set_high_threshold({}) is False:\n"\
" print('{}: set_high_threshold failure!')\n"\
" exit(1)\n"\
"except NotImplementedError:\n"\
" print('Not implement the set_high_threshold method!')\n"\
"print('Apply the new high threshold successfully.')\n"\
"\n".format(args.high_threshold, args.thermal)
if args.high_crit_threshold is not None:
high = get_high_threshold(args.thermal)
if high is not None and \
args.high_crit_threshold <= high:
print("Invalid Threshold!(High critical threshold can not " \
"be less than or equal to high threshold.)")
exit(1)
set_threshold_code += \
"try:\n"\
" if thermal.set_high_critical_threshold({}) is False:\n"\
" print('{}: set_high_critical_threshold failure!')\n"\
" exit(1)\n"\
"except NotImplementedError:\n"\
" print('Not implement the set_high_critical_threshold method!')\n"\
"print('Apply the new high critical threshold successfully.')\n"\
"\n".format(args.high_crit_threshold, args.thermal)
if set_threshold_code == "":
return
all_code = "{}{}{}".format(init_chassis_code, looking_for_thermal_code.format(args.thermal, args.thermal), set_threshold_code)
status, output = getstatusoutput_noshell(["docker", "exec", "pmon", "python3", "-c", all_code])
print(output)
if __name__ == "__main__":
main()