class Platform(PlatformBase): def __init__(self): PlatformBase.__init__(self) if self._is_host(): self._chassis = Chassis() self._chassis.initialize_components() else: self._chassis = Chassis() self._chassis.initialize_psu() self._chassis.initialize_fan() self._chassis.initialize_eeprom() self._chassis.initialize_thermals() def _is_host(self): """ Test whether current process is running on the host or an docker return True for host and False for docker """ is_host = False try: proc = subprocess.Popen("docker --version 2>/dev/null", stdout=subprocess.PIPE, shell=True, stderr=subprocess.STDOUT) stdout = proc.communicate()[0] proc.wait() result = stdout.rstrip('\n') if result != '': is_host = True except OSError, e: pass return is_host
def test_change_event(self): from sonic_platform.sfp_event import sfp_event from sonic_platform.sfp import SFP return_port_dict = {1: '1'} def mock_check_sfp_status(self, port_dict, error_dict, timeout): port_dict.update(return_port_dict) return True if port_dict else False sfp_event.check_sfp_status = mock_check_sfp_status chassis = Chassis() # Call get_change_event with timeout=0, wait until an event is detected status, event_dict = chassis.get_change_event() assert status is True assert 'sfp' in event_dict and event_dict['sfp'][1] == '1' assert len(chassis._sfp_list) == 3 assert SFP.reinit.call_count == 1 # Call get_change_event with timeout=1.0 return_port_dict = {} status, event_dict = chassis.get_change_event(timeout=1.0) assert status is True assert 'sfp' in event_dict and not event_dict['sfp']
def test_sfp_get_error_status(self, mock_get_error_code): chassis = Chassis() # Fetch an SFP module to test sfp = chassis.get_sfp(1) description_dict = sfp._get_error_description_dict() for error in description_dict.keys(): mock_get_error_code.return_value = ( SX_PORT_MODULE_STATUS_PLUGGED_WITH_ERROR, error) description = sfp.get_error_description() assert description == description_dict[error] mock_get_error_code.return_value = ( SX_PORT_MODULE_STATUS_PLUGGED_WITH_ERROR, -1) description = sfp.get_error_description() assert description == "Unknown error (-1)" expected_description_list = [ (SX_PORT_MODULE_STATUS_INITIALIZING, "Initializing"), (SX_PORT_MODULE_STATUS_PLUGGED, "OK"), (SX_PORT_MODULE_STATUS_UNPLUGGED, "Unplugged"), (SX_PORT_MODULE_STATUS_PLUGGED_DISABLED, "Disabled") ] for oper_code, expected_description in expected_description_list: mock_get_error_code.return_value = (oper_code, -1) description = sfp.get_error_description() assert description == expected_description
def test_reboot_cause(self): from sonic_platform import utils from sonic_platform.chassis import REBOOT_CAUSE_ROOT chassis = Chassis() major, minor = chassis.get_reboot_cause() assert major == chassis.REBOOT_CAUSE_NON_HARDWARE assert minor == '' mock_file_content = {} def read_int_from_file(file_path, *args, **kwargs): return mock_file_content[file_path] utils.read_int_from_file = read_int_from_file for key, value in chassis.reboot_major_cause_dict.items(): file_path = os.path.join(REBOOT_CAUSE_ROOT, key) mock_file_content[file_path] = 1 major, minor = chassis.get_reboot_cause() assert major == value assert minor == '' mock_file_content[file_path] = 0 for key, value in chassis.reboot_minor_cause_dict.items(): file_path = os.path.join(REBOOT_CAUSE_ROOT, key) mock_file_content[file_path] = 1 major, minor = chassis.get_reboot_cause() assert major == chassis.REBOOT_CAUSE_HARDWARE_OTHER assert minor == value mock_file_content[file_path] = 0
def test_sfp_get_error_status(): chassis = Chassis() # Fetch an SFP module to test sfp = chassis.get_sfp(1) description_dict = sfp._get_error_description_dict() sfp.oper_code = SX_PORT_MODULE_STATUS_PLUGGED_WITH_ERROR for error in description_dict.keys(): sfp.error_code = error description = sfp.get_error_description() assert description == description_dict[sfp.error_code] sfp.error_code = -1 description = sfp.get_error_description() assert description == "Unknown error (-1)" expected_description_list = [ (SX_PORT_MODULE_STATUS_INITIALIZING, "Initializing"), (SX_PORT_MODULE_STATUS_PLUGGED, "OK"), (SX_PORT_MODULE_STATUS_UNPLUGGED, "Unplugged"), (SX_PORT_MODULE_STATUS_PLUGGED_DISABLED, "Disabled") ] for oper_code, expected_description in expected_description_list: sfp.oper_code = oper_code description = sfp.get_error_description() assert description == expected_description
def main(): print("---------------------") print("Chassis PSU Unit Test") print("---------------------") chassis = Chassis() for psu in chassis.get_all_psus(): if not psu.get_presence(): print(" Name: {} not present".format(psu.get_name())) else: print(" Name:", psu.get_name()) print(" Presence: {}, Status: {}, LED: {}".format( psu.get_presence(), psu.get_status(), psu.get_status_led())) print(" Model: {}, Serial#: {}, Part#: {}".format( psu.get_model(), psu.get_serial(), psu.get_part_number())) try: current = psu.get_current() except NotImplementedError: current = "NA" try: power = psu.get_power() except NotImplementedError: power = "NA" print(" Voltage: {}, Current: {}, Power: {}\n".format( psu.get_voltage(), current, power)) return
def test_chassis_led(self): chassis = Chassis() assert chassis._led is None assert chassis.set_status_led('red') is False physical_led = chassis._led assert physical_led is not None self._verify_non_shared_led(physical_led, chassis)
def summary(): """Show system-health summary information""" # Mock the redis for unit test purposes # try: if os.environ["UTILITIES_UNIT_TESTING"] == "1": modules_path = os.path.join(os.path.dirname(__file__), "..") sys.path.insert(0, modules_path) from tests.system_health_test import MockerManager from tests.system_health_test import MockerChassis HealthCheckerManager = MockerManager Chassis = MockerChassis except Exception: # Normal run... # if os.geteuid(): click.echo("Root privileges are required for this operation") return from health_checker.manager import HealthCheckerManager from sonic_platform.chassis import Chassis manager = HealthCheckerManager() if not manager.config.config_file_exists(): click.echo("System health configuration file not found, exit...") return chassis = Chassis() stat = manager.check(chassis) chassis.initizalize_system_led() led = chassis.get_status_led() click.echo("System status summary\n\n System status LED " + led) services_list = [] fs_list = [] device_list = [] for category, elements in stat.items(): for element in elements: if elements[element]['status'] != "OK": if 'Running' in elements[element]['message']: services_list.append(element) elif 'Accessible' in elements[element]['message']: fs_list.append(element) else: device_list.append(elements[element]['message']) if len(services_list) or len(fs_list): click.echo(" Services:\n Status: Not OK") else: click.echo(" Services:\n Status: OK") if len(services_list): services_list_string = str(services_list) click.echo(" Not Running: " + services_list_string.replace("[", "").replace(']', "")) if len(fs_list): fs_list_string = str(fs_list) click.echo(" Not Accessible: " + fs_list_string.replace("[", "").replace(']', "")) if len(device_list): click.echo(" Hardware:\n Status: Not OK") click.echo(" Reasons: " + device_list.pop()) while len(device_list): click.echo("\t " + device_list.pop()) else: click.echo(" Hardware:\n Status: OK")
def __init__(self): PlatformBase.__init__(self) if self._is_host(): self._chassis = Chassis() self._chassis.initialize_components() else: self._chassis = Chassis() self._chassis.initialize_psu() self._chassis.initialize_fan() self._chassis.initialize_eeprom()
def __init__(self): PlatformBase.__init__(self) self._chassis = Chassis() self._chassis.initialize_psu() self._chassis.initialize_eeprom() if utils.is_host(): self._chassis.initialize_components() self._chassis.initizalize_system_led() else: self._chassis.initialize_fan() self._chassis.initialize_thermals()
def test_chassis_thermal(self): from sonic_platform.thermal import THERMAL_NAMING_RULE os.path.exists = mock.MagicMock(return_value=True) chassis = Chassis() thermal_list = chassis.get_all_thermals() assert thermal_list thermal_dict = {thermal.get_name(): thermal for thermal in thermal_list} gearbox_thermal_rule = None cpu_thermal_rule = None for rule in THERMAL_NAMING_RULE['chassis thermals']: thermal_type = rule.get('type', 'single') if thermal_type == 'single': thermal_name = rule['name'] if rule['temperature'] == 'comex_amb': assert thermal_name not in thermal_dict continue default_present = rule.get('default_present', True) if not default_present: assert thermal_name not in thermal_dict continue assert thermal_name in thermal_dict thermal = thermal_dict[thermal_name] assert rule['temperature'] in thermal.temperature assert rule['high_threshold'] in thermal.high_threshold if 'high_threshold' in rule else thermal.high_threshold is None assert rule['high_critical_threshold'] in thermal.high_critical_threshold if 'high_critical_threshold' in rule else thermal.high_critical_threshold is None else: if 'Gearbox' in rule['name']: gearbox_thermal_rule = rule elif 'CPU Core' in rule['name']: cpu_thermal_rule = rule gearbox_thermal_count = 0 cpu_thermal_count = 0 for thermal in thermal_list: if 'Gearbox' in thermal.get_name(): start_index = gearbox_thermal_rule.get('start_index', 1) start_index += gearbox_thermal_count assert thermal.get_name() == gearbox_thermal_rule['name'].format(start_index) assert gearbox_thermal_rule['temperature'].format(start_index) in thermal.temperature assert gearbox_thermal_rule['high_threshold'].format(start_index) in thermal.high_threshold assert gearbox_thermal_rule['high_critical_threshold'].format(start_index) in thermal.high_critical_threshold gearbox_thermal_count += 1 elif 'CPU Core' in thermal.get_name(): start_index = cpu_thermal_rule.get('start_index', 1) start_index += cpu_thermal_count assert thermal.get_name() == cpu_thermal_rule['name'].format(start_index) assert cpu_thermal_rule['temperature'].format(start_index) in thermal.temperature assert cpu_thermal_rule['high_threshold'].format(start_index) in thermal.high_threshold assert cpu_thermal_rule['high_critical_threshold'].format(start_index) in thermal.high_critical_threshold cpu_thermal_count += 1 assert gearbox_thermal_count == 2 assert cpu_thermal_count == 2
def test_get_system_eeprom_info(): # remove the eeprom file to trigger the GRPC to # get the eeprom again eeprom = Eeprom() eeprom.reset() chassis = Chassis() eeprom_info = chassis.get_system_eeprom_info() assert eeprom_info != '' print('') for key, value in eeprom_info.items(): print("{}: {}".format(key, value))
def test_chassis_thermal_includes(self): from sonic_platform.thermal import THERMAL_NAMING_RULE DeviceDataManager.get_platform_name = mock.MagicMock(return_value='x86_64-nvidia_sn2201-r0') DeviceDataManager.get_thermal_capability = mock.MagicMock(return_value={'comex_amb': False, 'cpu_amb': True, 'swb_amb': True}) chassis = Chassis() thermal_list = chassis.get_all_thermals() assert thermal_list thermal_dict = {thermal.get_name(): thermal for thermal in thermal_list} for rule in THERMAL_NAMING_RULE['chassis thermals']: default_present = rule.get('default_present', True) if not default_present: thermal_name = rule['name'] assert thermal_name in thermal_dict
def main(): print("---------------------") print("Chassis Watchdog Test") print("---------------------") chassis = Chassis() watchdog = chassis.get_watchdog() print(" Armed: {}".format(watchdog.is_armed())) print(" Time Left: {}".format(watchdog.get_remaining_time())) return
def main(): print("---------------------------") print("Chassis Component Unit Test") print("---------------------------") chassis = Chassis() for component in chassis.get_all_components(): print(" Name: {}".format(component.get_name())) print(" Description: {}".format(component.get_description())) print(" FW version: {}\n".format( component.get_firmware_version())) return
def main(): print("---------------------") print("Chassis PSU Unit Test") print("---------------------") chassis = Chassis() for psu in chassis.get_all_psus(): print(" Name:", psu.get_name()) print(" Presence: {}, Status: {}, LED: {}".format( psu.get_presence(), psu.get_status(), psu.get_status_led())) print(" Model: {}, Serial: {}".format(psu.get_model(), psu.get_serial())) print(" Voltage: {}, Current: NO, Power: NO \n".format( psu.get_voltage())) return
def main(): print("-------------------------") print("Chassis Thermal Unit Test") print("-------------------------") chassis = Chassis() for thermal in chassis.get_all_thermals(): print(" Name:", thermal.get_name()) print(" Presence: {}, Status: {}".format(thermal.get_presence(), thermal.get_status())) print(" Model: {}, Serial: {}".format(thermal.get_model(), thermal.get_serial())) print(" Temperature: {}C, High Threshold: {}C\n".format(thermal.get_temperature(), thermal.get_high_threshold())) return
def main(): print("------------------------") print("Chassis eeprom Unit Test") print("------------------------") chassis = Chassis() eeprom = chassis.get_eeprom() print(" Model: {}, Service Tag: {}".format(eeprom.modelstr(), eeprom.service_tag_str())) print(" Part#: {}, Serial#: {}".format(eeprom.part_number_str(), eeprom.serial_number_str())) print(" Base MAC: {}".format(eeprom.base_mac_addr())) return
def main(): print("---------------------------") print("Chassis Component Unit Test") print("---------------------------") chassis = Chassis() return
def test_sfp_partial_and_then_full_initialize(): """ Verify SFP initialization flow (partial and then full): 1. get_sfp to tirgger a partial initialization 2. get_sfp for another SPF module and verify the partial initialization isn't executed again 3. get_all_sfps to trigger a full initialization """ chassis = Chassis() # Fetch a sfp # This should trigger SFP modules be partial initialized sfp1 = chassis.get_sfp(1) # Verify the SFP list has been created assert len(chassis._sfp_list) == chassis.PORT_END + 1 assert chassis.sfp_module_partial_initialized == True assert chassis.sfp_module_full_initialized == False # Fetch another SFP module sfp2 = chassis.get_sfp(2) # Verify the previous SFP module isn't changed assert sfp1 == chassis.get_sfp(1) # Fetch all SFP modules allsfp = chassis.get_all_sfps() # Verify sfp1 and sfp2 aren't changed assert sfp1 == chassis.get_sfp(1) assert sfp2 == chassis.get_sfp(2) # Verify the SFP has been fully initialized assert chassis.sfp_module_partial_initialized == True assert chassis.sfp_module_full_initialized == True
def main(): print("---------------------") print("Chassis Fan Unit Test") print("---------------------") chassis = Chassis() for fan in chassis.get_all_fans(): print(" Name:", fan.get_name()) print(" Presence: {}, Status: {}, LED: {}".format(fan.get_presence(), fan.get_status(), fan.get_status_led())) print(" Model: {}, Serial: {}".format(fan.get_model(), fan.get_serial())) print(" Direction: {}, Speed: {}RPM, Target Speed: {}%\n".format(fan.get_direction(), str(fan.get_speed()), str(fan.get_target_speed()))) return
def main(): print("-------------------------") print("Chassis Thermal Unit Test") print("-------------------------") chassis = Chassis() for thermal in chassis.get_all_thermals(): if not thermal.get_presence(): print(" Name: {} not present".format(thermal.get_name())) else: print(" Name:", thermal.get_name()) print(" Presence: {}, Status: {}".format( thermal.get_presence(), thermal.get_status())) print(" Model: {}, Serial#: {}".format( thermal.get_model(), thermal.get_serial())) print(" Temperature(C): {}".format( thermal.get_temperature())) try: low_thresh = thermal.get_low_threshold() except NotImplementedError: low_thresh = "NA" try: high_thresh = thermal.get_high_threshold() except NotImplementedError: high_thresh = "NA" print(" Low Threshold(C): {}, High Threshold(C): {}".format( low_thresh, high_thresh)) try: crit_low_thresh = thermal.get_low_critical_threshold() except NotImplementedError: crit_low_thresh = "NA" try: crit_high_thresh = thermal.get_high_critical_threshold() except NotImplementedError: crit_high_thresh = "NA" print( " Crit Low Threshold(C): {}, Crit High Threshold(C): {}\n" .format(crit_low_thresh, crit_high_thresh)) return
def test_sfp(self): # Test get_num_sfps, it should not create any SFP objects DeviceDataManager.get_sfp_count = mock.MagicMock(return_value=3) chassis = Chassis() assert chassis.get_num_sfps() == 3 assert len(chassis._sfp_list) == 0 # Index out of bound, return None sfp = chassis.get_sfp(4) assert sfp is None assert len(chassis._sfp_list) == 0 # Get one SFP, other SFP list should be initialized to None sfp = chassis.get_sfp(1) assert sfp is not None assert len(chassis._sfp_list) == 3 assert chassis._sfp_list[1] is None assert chassis._sfp_list[2] is None assert chassis.sfp_initialized_count == 1 # Get the SFP again, no new SFP created sfp1 = chassis.get_sfp(1) assert id(sfp) == id(sfp1) # Get another SFP, sfp_initialized_count increase sfp2 = chassis.get_sfp(2) assert sfp2 is not None assert chassis._sfp_list[2] is None assert chassis.sfp_initialized_count == 2 # Get all SFPs, but there are SFP already created, only None SFP created sfp_list = chassis.get_all_sfps() assert len(sfp_list) == 3 assert chassis.sfp_initialized_count == 3 assert list(filter(lambda x: x is not None, sfp_list)) assert id(sfp1) == id(sfp_list[0]) assert id(sfp2) == id(sfp_list[1]) # Get all SFPs, no SFP yet, all SFP created chassis._sfp_list = [] chassis.sfp_initialized_count = 0 sfp_list = chassis.get_all_sfps() assert len(sfp_list) == 3 assert chassis.sfp_initialized_count == 3
def test_sfp_full_initialize_without_partial(): """ Verify SFP initialization flow (full): 1. get_all_sfps to trigger a full initialization 2. get_sfp for a certain SFP module and verify the partial initialization isn't executed again """ chassis = Chassis() # Fetch all SFP modules allsfp = chassis.get_all_sfps() # Verify the SFP has been fully initialized assert chassis.sfp_module_partial_initialized == True assert chassis.sfp_module_full_initialized == True for sfp in allsfp: assert sfp is not None # Verify when get_sfp is called, the SFP modules won't be initialized again sfp1 = allsfp[0] assert sfp1 == chassis.get_sfp(1)
def __init__(self): # Initialize the JSON data self.pddf_data = pddfapi.PddfApi() with open('/usr/share/sonic/platform/pddf/pd-plugin.json') as pd: self.pddf_plugin_data = json.load(pd) if not self.pddf_data or not self.pddf_plugin_data: print("Error: PDDF JSON data is not loaded properly ... Exiting") raise ValueError PlatformBase.__init__(self) self._chassis = Chassis(self.pddf_data, self.pddf_plugin_data)
def test_revision_permission(self): old_dmi_file = sonic_platform.chassis.DMI_FILE #Override the dmi file sonic_platform.chassis.DMI_FILE = "/tmp/dmi_file" new_dmi_file = sonic_platform.chassis.DMI_FILE os.system("touch " + new_dmi_file) os.system("chmod -r " + new_dmi_file) chassis = Chassis() rev = chassis.get_revision() sonic_platform.chassis.DMI_FILE = old_dmi_file os.system("rm -f " + new_dmi_file) assert rev == "N/A"
def test_psu(self): from sonic_platform.psu import Psu, FixedPsu # Test creating hot swapable PSU DeviceDataManager.get_psu_count = mock.MagicMock(return_value=2) DeviceDataManager.is_psu_hotswapable = mock.MagicMock(return_value=True) chassis = Chassis() chassis.initialize_psu() assert len(chassis._psu_list) == 2 assert len(list(filter(lambda x: isinstance(x, Psu) ,chassis._psu_list))) == 2 # Test creating fixed PSU DeviceDataManager.get_psu_count = mock.MagicMock(return_value=3) DeviceDataManager.is_psu_hotswapable = mock.MagicMock(return_value=False) chassis._psu_list = [] chassis.initialize_psu() assert len(chassis._psu_list) == 3 assert len(list(filter(lambda x: isinstance(x, FixedPsu) ,chassis._psu_list))) == 3 # Test chassis.get_all_psus chassis._psu_list = [] psu_list = chassis.get_all_psus() assert len(psu_list) == 3 # Test chassis.get_psu chassis._psu_list = [] psu = chassis.get_psu(0) assert psu and isinstance(psu, FixedPsu) psu = chassis.get_psu(3) assert psu is None # Test chassis.get_num_psus chassis._psu_list = [] assert chassis.get_num_psus() == 3
def test_chassis_info(): chassis = Chassis() assert chassis.get_presence() is True assert chassis.get_status() is True reboot = chassis.get_reboot_cause() print("reboot_casue: {}".format(reboot)) assert reboot != '' assert chassis.is_modular_chassis() is True slot = chassis.get_supervisor_slot() print("supervisor slot: {}".format(slot)) assert slot == nokia_common.NOKIA_CPM_SLOT_NUMBER slot = chassis.get_my_slot() print("my slot: {}".format(slot)) assert slot != ''
def test_chassis_eeprom(self, mock_eeprom_info): mock_eeprom_info.return_value = { hex(Eeprom._TLV_CODE_PRODUCT_NAME): 'MSN3420', hex(Eeprom._TLV_CODE_PART_NUMBER): 'MSN3420-CB2FO', hex(Eeprom._TLV_CODE_MAC_BASE): '1C:34:DA:1C:9F:00', hex(Eeprom._TLV_CODE_SERIAL_NUMBER): 'MT2019X13878' } chassis = Chassis() assert chassis.get_name() == 'MSN3420' assert chassis.get_model() == 'MSN3420-CB2FO' assert chassis.get_base_mac() == '1C:34:DA:1C:9F:00' assert chassis.get_serial() == 'MT2019X13878' assert chassis.get_system_eeprom_info( ) == mock_eeprom_info.return_value
def test_status_led(): chassis = Chassis() list = [ ChassisBase.STATUS_LED_COLOR_OFF, ChassisBase.STATUS_LED_COLOR_RED, ChassisBase.STATUS_LED_COLOR_AMBER, ChassisBase.STATUS_LED_COLOR_GREEN ] for color in list: print('{}'.format(color)) chassis.set_status_led(color) print('Chassis get-led status is {}'.format(chassis.get_status_led())) assert color == chassis.get_status_led()