diff --git a/sonic-ledd/scripts/ledd b/sonic-ledd/scripts/ledd index c472a64684d3..331ccb20d73b 100644 --- a/sonic-ledd/scripts/ledd +++ b/sonic-ledd/scripts/ledd @@ -8,10 +8,9 @@ try: import getopt import sys + + from sonic_py_common import daemon_base from swsscommon import swsscommon - from sonic_daemon_base import daemon_base - from sonic_daemon_base.daemon_base import Logger - from sonic_daemon_base.daemon_base import DaemonBase except ImportError, e: raise ImportError (str(e) + " - required module not found") @@ -36,11 +35,7 @@ SELECT_TIMEOUT = 1000 LEDUTIL_LOAD_ERROR = 1 -logger = Logger(SYSLOG_IDENTIFIER) - -class DaemonLedd(DaemonBase): - def __init__(self): - DaemonBase.__init__(self) +class DaemonLedd(daemon_base.DaemonBase): # Run daemon def run(self): @@ -67,7 +62,7 @@ class DaemonLedd(DaemonBase): try: led_control = self.load_platform_util(LED_MODULE_NAME, LED_CLASS_NAME) except Exception as e: - logger.log_error("Failed to load ledutil: %s" % (str(e)), True) + self.log_error("Failed to load ledutil: %s" % (str(e)), True) sys.exit(LEDUTIL_LOAD_ERROR) # Open a handle to the Application database @@ -88,7 +83,7 @@ class DaemonLedd(DaemonBase): # Do not flood log when select times out continue if state != swsscommon.Select.OBJECT: - logger.log_warning("sel.select() did not return swsscommon.Select.OBJECT") + self.log_warning("sel.select() did not return swsscommon.Select.OBJECT") continue (key, op, fvp) = sst.pop() @@ -106,7 +101,7 @@ class DaemonLedd(DaemonBase): return 1 def main(): - ledd = DaemonLedd() + ledd = DaemonLedd(SYSLOG_IDENTIFIER) ledd.run() if __name__ == '__main__': diff --git a/sonic-pcied/scripts/pcied b/sonic-pcied/scripts/pcied index 428cc37b0b88..d34519d46213 100644 --- a/sonic-pcied/scripts/pcied +++ b/sonic-pcied/scripts/pcied @@ -13,8 +13,8 @@ try: import threading import swsssdk - from sonic_daemon_base.daemon_base import Logger - from sonic_daemon_base.daemon_base import DaemonBase + from sonic_py_common.daemon_base import DaemonBase + from sonic_py_common.device_info import get_platform except ImportError, e: raise ImportError(str(e) + " - required module not found") @@ -28,30 +28,24 @@ PCIE_TABLE_NAME = "PCIE_STATUS" PLATFORM_ROOT_PATH = '/usr/share/sonic/device' PCIE_CONF_FILE = 'pcie.yaml' -SONIC_CFGGEN_PATH = '/usr/local/bin/sonic-cfggen' -HWSKU_KEY = 'DEVICE_METADATA.localhost.hwsku' -PLATFORM_KEY = 'DEVICE_METADATA.localhost.platform' PCIED_MAIN_THREAD_SLEEP_SECS = 60 REDIS_HOSTIP = "127.0.0.1" -# Global logger class instance -logger = Logger(SYSLOG_IDENTIFIER) - # # Daemon ======================================================================= # class DaemonPcied(DaemonBase): - def __init__(self): - DaemonBase.__init__(self) + def __init__(self, log_identifier): + super(DaemonPcied, self).__init__(log_identifier) - platform, hwsku = DaemonBase.get_platform_and_hwsku(self) - pciefilePath = "/".join([PLATFORM_ROOT_PATH, platform, "plugins", PCIE_CONF_FILE]) + platform = get_platform() + pciefilePath = os.path.join(PLATFORM_ROOT_PATH, platform, "plugins", PCIE_CONF_FILE) sys.path.append(os.path.abspath(pciefilePath)) if not os.path.exists(pciefilePath): - logger.log_error("Platform pcie configuration file doesn't exist! exit pcied") + self.log_error("Platform pcie configuration file doesn't exist! Exiting ...") sys.exit("Platform PCIe Configuration file doesn't exist!") self.timeout = PCIED_MAIN_THREAD_SLEEP_SECS @@ -70,10 +64,10 @@ class DaemonPcied(DaemonBase): if PCIE_RESULT_REGEX in line: if "PASSED" in line and "PASSED" not in pcie_db_state: self.update_state_db("PCIE_STATUS|", "PCIE_DEVICES", "PASSED") - logger.log_info("PCIe device status check : PASSED") + self.log_info("PCIe device status check : PASSED") elif "FAILED" in line and "PASSED" in pcie_db_state: self.update_state_db("PCIE_STATUS|", "PCIE_DEVICES", "FAILED") - logger.log_info("PCIe device status check : FAILED") + self.log_info("PCIe device status check : FAILED") def read_state_db(self, key1, key2): return self.state_db.get('STATE_DB', key1, key2) @@ -84,44 +78,44 @@ class DaemonPcied(DaemonBase): # Signal handler def signal_handler(self, sig, frame): if sig == signal.SIGHUP: - logger.log_info("Caught SIGHUP - ignoring...") + self.log_info("Caught SIGHUP - ignoring...") elif sig == signal.SIGINT: - logger.log_info("Caught SIGINT - exiting...") + self.log_info("Caught SIGINT - exiting...") self.stop_event.set() elif sig == signal.SIGTERM: - logger.log_info("Caught SIGTERM - exiting...") + self.log_info("Caught SIGTERM - exiting...") self.stop_event.set() else: - logger.log_warning("Caught unhandled signal '" + sig + "'") + self.log_warning("Caught unhandled signal '" + sig + "'") # Initialize daemon def init(self): - logger.log_info("Start daemon init...") + self.log_info("Start daemon init...") # Deinitialize daemon def deinit(self): - logger.log_info("Start daemon deinit...") + self.log_info("Start daemon deinit...") # Run daemon def run(self): - logger.log_info("Starting up...") + self.log_info("Starting up...") # Start daemon initialization sequence self.init() # Start main loop - logger.log_info("Start daemon main loop") + self.log_info("Start daemon main loop") while not self.stop_event.wait(self.timeout): # Check the Pcie device status self.check_pcie_devices() - logger.log_info("Stop daemon main loop") + self.log_info("Stop daemon main loop") # Start daemon deinitialization sequence self.deinit() - logger.log_info("Shutting down...") + self.log_info("Shutting down...") # # Main ========================================================================= @@ -129,7 +123,7 @@ class DaemonPcied(DaemonBase): def main(): - pcied = DaemonPcied() + pcied = DaemonPcied(SYSLOG_IDENTIFIER) pcied.run() if __name__ == '__main__': diff --git a/sonic-psud/scripts/psud b/sonic-psud/scripts/psud index 1cd9b8b58fe6..8e776d78ce43 100644 --- a/sonic-psud/scripts/psud +++ b/sonic-psud/scripts/psud @@ -10,13 +10,12 @@ """ try: - import sys import signal + import sys import threading + + from sonic_py_common import daemon_base from swsscommon import swsscommon - from sonic_daemon_base import daemon_base - from sonic_daemon_base.daemon_base import Logger - from sonic_daemon_base.daemon_base import DaemonBase except ImportError, e: raise ImportError (str(e) + " - required module not found") @@ -49,8 +48,6 @@ PSU_INFO_UPDATE_PERIOD_SECS = 3 PSUUTIL_LOAD_ERROR = 1 -logger = Logger(SYSLOG_IDENTIFIER) - platform_psuutil = None platform_chassis = None @@ -119,9 +116,9 @@ def log_on_status_changed(normal_status, normal_log, abnormal_log): :return: """ if normal_status: - logger.log_notice(normal_log) + self.log_notice(normal_log) else: - logger.log_warning(abnormal_log) + self.log_warning(abnormal_log) # # PSU status =================================================================== @@ -162,7 +159,7 @@ class PsuStatus(object): def set_voltage(self, voltage, high_threshold, low_threshold): if not voltage or not high_threshold or not low_threshold: if self.voltage_good is not True: - logger.log_warning('PSU voltage or high_threshold or low_threshold become unavailable, ' + self.log_warning('PSU voltage or high_threshold or low_threshold become unavailable, ' 'voltage={}, high_threshold={}, low_threshold={}'.format(voltage, high_threshold, low_threshold)) self.voltage_good = True return False @@ -177,7 +174,7 @@ class PsuStatus(object): def set_temperature(self, temperature, high_threshold): if not temperature or not high_threshold: if self.temperature_good is not True: - logger.log_warning('PSU temperature or high_threshold become unavailable, ' + self.log_warning('PSU temperature or high_threshold become unavailable, ' 'temperature={}, high_threshold={}'.format(temperature, high_threshold)) self.temperature_good = True return False @@ -196,9 +193,9 @@ class PsuStatus(object): # Daemon ======================================================================= # -class DaemonPsud(DaemonBase): - def __init__(self): - DaemonBase.__init__(self) +class DaemonPsud(daemon_base.DaemonBase): + def __init__(self, log_identifier): + super(DaemonPsud, self).__init__(log_identifier) self.stop = threading.Event() self.psu_status_dict = {} @@ -206,36 +203,36 @@ class DaemonPsud(DaemonBase): # Signal handler def signal_handler(self, sig, frame): if sig == signal.SIGHUP: - logger.log_info("Caught SIGHUP - ignoring...") + self.log_info("Caught SIGHUP - ignoring...") elif sig == signal.SIGINT: - logger.log_info("Caught SIGINT - exiting...") + self.log_info("Caught SIGINT - exiting...") self.stop.set() elif sig == signal.SIGTERM: - logger.log_info("Caught SIGTERM - exiting...") + self.log_info("Caught SIGTERM - exiting...") self.stop.set() else: - logger.log_warning("Caught unhandled signal '" + sig + "'") + self.log_warning("Caught unhandled signal '" + sig + "'") # Run daemon def run(self): global platform_psuutil global platform_chassis - logger.log_info("Starting up...") + self.log_info("Starting up...") # Load new platform api class try: import sonic_platform.platform platform_chassis = sonic_platform.platform.Platform().get_chassis() except Exception as e: - logger.log_warning("Failed to load chassis due to {}".format(repr(e))) + self.log_warning("Failed to load chassis due to {}".format(repr(e))) # Load platform-specific psuutil class if platform_chassis is None: try: platform_psuutil = self.load_platform_util(PLATFORM_SPECIFIC_MODULE_NAME, PLATFORM_SPECIFIC_CLASS_NAME) except Exception as e: - logger.log_error("Failed to load psuutil: %s" % (str(e)), True) + self.log_error("Failed to load psuutil: %s" % (str(e)), True) sys.exit(PSUUTIL_LOAD_ERROR) # Connect to STATE_DB and create psu/chassis info tables @@ -249,14 +246,14 @@ class DaemonPsud(DaemonBase): chassis_tbl.set(CHASSIS_INFO_KEY_TEMPLATE.format(1), fvs) # Start main loop - logger.log_info("Start daemon main loop") + self.log_info("Start daemon main loop") while not self.stop.wait(PSU_INFO_UPDATE_PERIOD_SECS): psu_db_update(psu_tbl, psu_num) self.update_psu_data(psu_tbl) self._update_led_color(psu_tbl) - logger.log_info("Stop daemon main loop") + self.log_info("Stop daemon main loop") # Delete all the information from DB and then exit for psu_index in range(1, psu_num + 1): @@ -264,7 +261,7 @@ class DaemonPsud(DaemonBase): chassis_tbl._del(CHASSIS_INFO_KEY_TEMPLATE.format(1)) - logger.log_info("Shutting down...") + self.log_info("Shutting down...") def update_psu_data(self, psu_tbl): if not platform_chassis: @@ -274,7 +271,7 @@ class DaemonPsud(DaemonBase): try: self._update_single_psu_data(index + 1, psu, psu_tbl) except Exception as e: - logger.log_warning("Failed to update PSU data - {}".format(e)) + self.log_warning("Failed to update PSU data - {}".format(e)) def _update_single_psu_data(self, index, psu, psu_tbl): name = try_get(psu.get_name) @@ -358,7 +355,7 @@ class DaemonPsud(DaemonBase): ('led_status', str(try_get(psu_status.psu.get_status_led))) ]) except Exception as e: - logger.log_warning('Failed to get led status for psu {}'.format(index)) + self.log_warning('Failed to get led status for psu {}'.format(index)) fvs = swsscommon.FieldValuePairs([ ('led_status', NOT_AVAILABLE) ]) @@ -368,7 +365,7 @@ class DaemonPsud(DaemonBase): # def main(): - psud = DaemonPsud() + psud = DaemonPsud(SYSLOG_IDENTIFIER) psud.run() if __name__ == '__main__': diff --git a/sonic-syseepromd/scripts/syseepromd b/sonic-syseepromd/scripts/syseepromd index a2d373f5a7ef..5fb4a35815f0 100644 --- a/sonic-syseepromd/scripts/syseepromd +++ b/sonic-syseepromd/scripts/syseepromd @@ -9,12 +9,11 @@ ''' try: - import sys import signal + import sys import threading - from sonic_daemon_base.daemon_base import DaemonBase - from sonic_daemon_base.daemon_base import Logger - from sonic_daemon_base import daemon_base + + from sonic_py_common import daemon_base from swsscommon import swsscommon except ImportError, e: raise ImportError (str(e) + " - required module not found") @@ -34,12 +33,10 @@ ERR_EEPROMUTIL_LOAD = 5 EEPROM_TABLE_NAME = 'EEPROM_INFO' SYSLOG_IDENTIFIER = 'syseepromd' -# Global logger class instance -logger = Logger(SYSLOG_IDENTIFIER) -class DaemonSyseeprom(DaemonBase): - def __init__(self): - DaemonBase.__init__(self) +class DaemonSyseeprom(daemon_base.DaemonBase): + def __init__(self, log_identifier): + super(DaemonSyseeprom, self).__init__(log_identifier) self.stop_event = threading.Event() self.eeprom = None @@ -72,12 +69,12 @@ class DaemonSyseeprom(DaemonBase): def post_eeprom_to_db(self): eeprom = self._wrapper_read_eeprom() if eeprom is None : - logger.log_error("Failed to read eeprom") + self.log_error("Failed to read eeprom") return ERR_FAILED_EEPROM err = self._wrapper_update_eeprom_db(eeprom) if err: - logger.log_error("Failed to update eeprom info to database") + self.log_error("Failed to update eeprom info to database") return ERR_FAILED_UPDATE_DB self.eepromtbl_keys = self.eeprom_tbl.getKeys() @@ -104,19 +101,19 @@ class DaemonSyseeprom(DaemonBase): # Signal handler def signal_handler(self, sig, frame): if sig == signal.SIGHUP: - logger.log_info("Caught SIGHUP - ignoring...") + self.log_info("Caught SIGHUP - ignoring...") elif sig == signal.SIGINT: - logger.log_info("Caught SIGINT - exiting...") + self.log_info("Caught SIGINT - exiting...") self.stop_event.set() elif sig == signal.SIGTERM: - logger.log_info("Caught SIGTERM - exiting...") + self.log_info("Caught SIGTERM - exiting...") self.stop_event.set() else: - logger.log_warning("Caught unhandled signal '" + sig + "'") + self.log_warning("Caught unhandled signal '" + sig + "'") # Run daemon def run(self): - logger.log_info("Starting up...") + self.log_info("Starting up...") # First, try to load the new platform API try: @@ -124,14 +121,14 @@ class DaemonSyseeprom(DaemonBase): self.chassis = sonic_platform.platform.Platform().get_chassis() self.eeprom = self.chassis.get_eeprom() except Exception as e: - logger.log_warning("Failed to load platform-specific eeprom from sonic_platform package due to {}".format(repr(e))) + self.log_warning("Failed to load platform-specific eeprom from sonic_platform package due to {}".format(repr(e))) # If we didn't successfully load the class from the sonic_platform package, try loading the old plugin if not self.eeprom: try: self.eeprom = self.load_platform_util(PLATFORM_SPECIFIC_MODULE_NAME, PLATFORM_SPECIFIC_CLASS_NAME) except Exception as e: - logger.log_error("Failed to load platform-specific eeprom implementation: {}".format(repr(e))) + self.log_error("Failed to load platform-specific eeprom implementation: {}".format(repr(e))) if not self.eeprom: sys.exit(ERR_EEPROMUTIL_LOAD) @@ -139,34 +136,34 @@ class DaemonSyseeprom(DaemonBase): # Connect to STATE_DB and post syseeprom info to state DB rc = self.post_eeprom_to_db() if rc != POST_EEPROM_SUCCESS: - logger.log_error("Failed to post eeprom to database") + self.log_error("Failed to post eeprom to database") # Start main loop - logger.log_info("Start daemon main loop") + self.log_info("Start daemon main loop") while not self.stop_event.wait(EEPROM_INFO_UPDATE_PERIOD_SECS): rc = self.detect_eeprom_table_integrity() if not rc: - logger.log_info("sys eeprom table was changed, need update") + self.log_info("sys eeprom table was changed, need update") self.clear_db() rcs = self.post_eeprom_to_db() if rcs != POST_EEPROM_SUCCESS: - logger.log_error("Failed to post eeprom to database") + self.log_error("Failed to post eeprom to database") continue - logger.log_info("Stop daemon main loop") + self.log_info("Stop daemon main loop") # Delete all the information from DB and then exit self.clear_db() - logger.log_info("Shutting down...") + self.log_info("Shutting down...") # # Main ========================================================================= # def main(): - syseepromd = DaemonSyseeprom() + syseepromd = DaemonSyseeprom(SYSLOG_IDENTIFIER) syseepromd.run() if __name__ == '__main__': diff --git a/sonic-thermalctld/scripts/thermalctld b/sonic-thermalctld/scripts/thermalctld index 6d484a28e89d..2dd6ffe450e5 100644 --- a/sonic-thermalctld/scripts/thermalctld +++ b/sonic-thermalctld/scripts/thermalctld @@ -6,14 +6,13 @@ """ try: - import time import signal import threading + import time from datetime import datetime - from sonic_daemon_base import daemon_base - from sonic_daemon_base.daemon_base import Logger - from sonic_daemon_base.daemon_base import DaemonBase - from sonic_daemon_base.task_base import ProcessTaskBase + + from sonic_py_common import daemon_base + from sonic_py_common.task_base import ProcessTaskBase except ImportError as e: raise ImportError(str(e) + " - required module not found") @@ -24,7 +23,6 @@ except ImportError as e: SYSLOG_IDENTIFIER = 'thermalctld' NOT_AVAILABLE = 'N/A' -logger = Logger(SYSLOG_IDENTIFIER) # utility functions @@ -56,9 +54,9 @@ def log_on_status_changed(normal_status, normal_log, abnormal_log): :return: """ if normal_status: - logger.log_notice(normal_log) + self.log_notice(normal_log) else: - logger.log_warning(abnormal_log) + self.log_warning(abnormal_log) class FanStatus(object): @@ -119,11 +117,11 @@ class FanStatus(object): def _check_speed_value_available(self, speed, target_speed, tolerance, current_status): if speed == NOT_AVAILABLE or target_speed == NOT_AVAILABLE or tolerance == NOT_AVAILABLE: if tolerance > 100 or tolerance < 0: - logger.log_warning('Invalid tolerance value: {}'.format(tolerance)) + self.log_warning('Invalid tolerance value: {}'.format(tolerance)) return False if current_status is True: - logger.log_warning('Fan speed or target_speed or tolerance become unavailable, ' + self.log_warning('Fan speed or target_speed or tolerance become unavailable, ' 'speed={}, target_speed={}, tolerance={}'.format(speed, target_speed, tolerance)) return False return True @@ -210,7 +208,7 @@ class FanUpdater(object): Update all Fan information to database :return: """ - logger.log_debug("Start fan updating") + self.log_debug("Start fan updating") old_bad_fan_count = FanStatus.get_bad_fan_count() FanStatus.reset_fan_counter() @@ -220,7 +218,7 @@ class FanUpdater(object): try: self._refresh_fan_status(drawer, fan, fan_index) except Exception as e: - logger.log_warning('Failed to update FAN status - {}'.format(e)) + self.log_warning('Failed to update FAN status - {}'.format(e)) fan_index += 1 for psu_index, psu in enumerate(self.chassis.get_all_psus()): @@ -229,19 +227,19 @@ class FanUpdater(object): try: self._refresh_fan_status(None, fan, fan_index, '{} FAN'.format(psu_name), True) except Exception as e: - logger.log_warning('Failed to update PSU FAN status - {}'.format(e)) + self.log_warning('Failed to update PSU FAN status - {}'.format(e)) self._update_led_color() bad_fan_count = FanStatus.get_bad_fan_count() if bad_fan_count > 0 and old_bad_fan_count != bad_fan_count: - logger.log_warning("Insufficient number of working fans warning: {} fans are not working.".format( + self.log_warning("Insufficient number of working fans warning: {} fans are not working.".format( bad_fan_count )) elif old_bad_fan_count > 0 and bad_fan_count == 0: - logger.log_notice("Insufficient number of working fans warning cleared: all fans are back to normal.") + self.log_notice("Insufficient number of working fans warning cleared: all fans are back to normal.") - logger.log_debug("End fan updating") + self.log_debug("End fan updating") def _refresh_fan_status(self, fan_drawer, fan, index, name_prefix='FAN', is_psu_fan=False): """ @@ -345,7 +343,7 @@ class FanUpdater(object): fan.set_status_led(fan.STATUS_LED_COLOR_RED) fan_drawer.set_status_led(fan.STATUS_LED_COLOR_RED) except NotImplementedError as e: - logger.log_warning('Failed to set led to fan, set_status_led not implemented') + self.log_warning('Failed to set led to fan, set_status_led not implemented') def _update_led_color(self): for fan_name, fan_status in self.fan_status_dict.items(): @@ -354,7 +352,7 @@ class FanUpdater(object): ('led_status', str(try_get(fan_status.fan.get_status_led))) ]) except Exception as e: - logger.log_warning('Failed to get led status for fan') + self.log_warning('Failed to get led status for fan') fvs = swsscommon.FieldValuePairs([ ('led_status', NOT_AVAILABLE) ]) @@ -378,7 +376,7 @@ class TemperatureStatus(object): """ if temperature == NOT_AVAILABLE: if self.temperature is not None: - logger.log_warning('Temperature of {} become unavailable'.format(name)) + self.log_warning('Temperature of {} become unavailable'.format(name)) self.temperature = None return @@ -387,7 +385,7 @@ class TemperatureStatus(object): else: diff = abs(temperature - self.temperature) if diff > TemperatureStatus.TEMPERATURE_DIFF_THRESHOLD: - logger.log_warning( + self.log_warning( 'Temperature of {} changed too fast, from {} to {}, please check your hardware'.format( name, self.temperature, temperature)) self.temperature = temperature @@ -395,7 +393,7 @@ class TemperatureStatus(object): def _check_temperature_value_available(self, temperature, threshold, current_status): if temperature == NOT_AVAILABLE or threshold == NOT_AVAILABLE: if current_status is True: - logger.log_warning('Thermal temperature or threshold become unavailable, ' + self.log_warning('Thermal temperature or threshold become unavailable, ' 'temperature={}, threshold={}'.format(temperature, threshold)) return False return True @@ -469,14 +467,14 @@ class TemperatureUpdater(object): Update all temperature information to database :return: """ - logger.log_debug("Start temperature updating") + self.log_debug("Start temperature updating") for index, thermal in enumerate(self.chassis.get_all_thermals()): try: self._refresh_temperature_status(thermal, index) except Exception as e: - logger.log_warning('Failed to update thermal status - {}'.format(e)) + self.log_warning('Failed to update thermal status - {}'.format(e)) - logger.log_debug("End temperature updating") + self.log_debug("End temperature updating") def _refresh_temperature_status(self, thermal, index): """ @@ -557,7 +555,7 @@ class ThermalMonitor(ProcessTaskBase): Thread function to handle Fan status update and temperature status update :return: """ - logger.log_info("Start thermal monitoring loop") + self.log_info("Start thermal monitoring loop") # Start loop to update fan, temperature info in DB periodically wait_time = ThermalMonitor.INITIAL_INTERVAL @@ -572,28 +570,28 @@ class ThermalMonitor(ProcessTaskBase): wait_time = ThermalMonitor.INITIAL_INTERVAL if elapse > ThermalMonitor.UPDATE_ELAPSE_THRESHOLD: - logger.log_warning('Update fan and temperature status takes {} seconds, ' + self.log_warning('Update fan and temperature status takes {} seconds, ' 'there might be performance risk'.format(elapse)) self.fan_updater.deinit() self.temperature_updater.deinit() - logger.log_info("Stop thermal monitoring loop") + self.log_info("Stop thermal monitoring loop") # # Daemon ======================================================================= # -class ThermalControlDaemon(DaemonBase): +class ThermalControlDaemon(daemon_base.DaemonBase): # Interval to run thermal control logic INTERVAL = 60 POLICY_FILE = '/usr/share/sonic/platform/thermal_policy.json' - def __init__(self): + def __init__(self, log_identifier): """ Constructor of ThermalControlDaemon """ - DaemonBase.__init__(self) + super(ThermalControlDaemon, self).__init__(log_identifier) self.stop_event = threading.Event() # Signal handler @@ -605,22 +603,22 @@ class ThermalControlDaemon(DaemonBase): :return: """ if sig == signal.SIGHUP: - logger.log_info("Caught SIGHUP - ignoring...") + self.log_info("Caught SIGHUP - ignoring...") elif sig == signal.SIGINT: - logger.log_info("Caught SIGINT - exiting...") + self.log_info("Caught SIGINT - exiting...") self.stop_event.set() elif sig == signal.SIGTERM: - logger.log_info("Caught SIGTERM - exiting...") + self.log_info("Caught SIGTERM - exiting...") self.stop_event.set() else: - logger.log_warning("Caught unhandled signal '" + sig + "'") + self.log_warning("Caught unhandled signal '" + sig + "'") def run(self): """ Run main logical of this daemon :return: """ - logger.log_info("Starting up...") + self.log_info("Starting up...") import sonic_platform.platform chassis = sonic_platform.platform.Platform().get_chassis() @@ -636,31 +634,31 @@ class ThermalControlDaemon(DaemonBase): thermal_manager.load(ThermalControlDaemon.POLICY_FILE) thermal_manager.init_thermal_algorithm(chassis) except Exception as e: - logger.log_error('Caught exception while initializing thermal manager - {}'.format(e)) + self.log_error('Caught exception while initializing thermal manager - {}'.format(e)) while not self.stop_event.wait(ThermalControlDaemon.INTERVAL): try: if thermal_manager: thermal_manager.run_policy(chassis) except Exception as e: - logger.log_error('Caught exception while running thermal policy - {}'.format(e)) + self.log_error('Caught exception while running thermal policy - {}'.format(e)) try: if thermal_manager: thermal_manager.deinitialize() except Exception as e: - logger.log_error('Caught exception while destroy thermal manager - {}'.format(e)) + self.log_error('Caught exception while destroy thermal manager - {}'.format(e)) thermal_monitor.task_stop() - logger.log_info("Shutdown...") + self.log_info("Shutdown...") # # Main ========================================================================= # def main(): - thermal_control = ThermalControlDaemon() + thermal_control = ThermalControlDaemon(SYSLOG_IDENTIFIER) thermal_control.run() diff --git a/sonic-thermalctld/tests/test_thermalctld.py b/sonic-thermalctld/tests/test_thermalctld.py index 5a215e6cc770..00d92d672cbf 100644 --- a/sonic-thermalctld/tests/test_thermalctld.py +++ b/sonic-thermalctld/tests/test_thermalctld.py @@ -1,7 +1,9 @@ import os import sys + from mock import Mock, MagicMock, patch -from sonic_daemon_base import daemon_base +from sonic_py_common import daemon_base + from .mock_platform import MockChassis, MockFan, MockThermal NOT_AVAILABLE = 'N/A' diff --git a/sonic-xcvrd/scripts/xcvrd b/sonic-xcvrd/scripts/xcvrd index d92194c39590..a702f1efb024 100644 --- a/sonic-xcvrd/scripts/xcvrd +++ b/sonic-xcvrd/scripts/xcvrd @@ -6,20 +6,19 @@ """ try: + import ast + import json + import multiprocessing import os - import sys - import time import signal - import threading - import json import string - import ast - import multiprocessing - from swsscommon import swsscommon - from sonic_daemon_base import daemon_base - from sonic_daemon_base.daemon_base import Logger - from sonic_daemon_base.daemon_base import DaemonBase + import sys + import threading + import time + from enum import Enum + from sonic_py_common import daemon_base, device_info + from swsscommon import swsscommon except ImportError, e: raise ImportError (str(e) + " - required module not found") @@ -91,8 +90,6 @@ platform_sfputil = None # Global chassis object based on new platform api platform_chassis = None -# Global logger class instance -logger = Logger(SYSLOG_IDENTIFIER) # # Helper functions ============================================================= @@ -104,7 +101,7 @@ def logical_port_name_to_physical_port_list(port_name): if platform_sfputil.is_logical_port(port_name): return platform_sfputil.get_logical_to_physical(port_name) else: - logger.log_error("Invalid port '%s'" % port_name) + self.log_error("Invalid port '%s'" % port_name) return None else: return [int(port_name)] @@ -230,7 +227,7 @@ def post_port_sfp_info_to_db(logical_port_name, table, transceiver_dict, physical_port_list = logical_port_name_to_physical_port_list(logical_port_name) if physical_port_list is None: - logger.log_error("No physical ports found for logical port '%s'" % logical_port_name) + self.log_error("No physical ports found for logical port '%s'" % logical_port_name) return PHYSICAL_PORT_NOT_EXIST if len(physical_port_list) > 1: @@ -271,7 +268,7 @@ def post_port_sfp_info_to_db(logical_port_name, table, transceiver_dict, return SFP_EEPROM_NOT_READY except NotImplementedError: - logger.log_error("This functionality is currently not implemented for this platform") + self.log_error("This functionality is currently not implemented for this platform") sys.exit(NOT_IMPLEMENTED_ERROR) # Update port dom threshold info in db @@ -282,7 +279,7 @@ def post_port_dom_threshold_info_to_db(logical_port_name, table, physical_port_list = logical_port_name_to_physical_port_list(logical_port_name) if physical_port_list is None: - logger.log_error("No physical ports found for logical port '%s'" + self.log_error("No physical ports found for logical port '%s'" % logical_port_name) return PHYSICAL_PORT_NOT_EXIST @@ -331,7 +328,7 @@ def post_port_dom_threshold_info_to_db(logical_port_name, table, return SFP_EEPROM_NOT_READY except NotImplementedError: - logger.log_error("This functionality is currently not implemented for this platform") + self.log_error("This functionality is currently not implemented for this platform") sys.exit(NOT_IMPLEMENTED_ERROR) # Update port dom sensor info in db @@ -341,7 +338,7 @@ def post_port_dom_info_to_db(logical_port_name, table, stop_event=threading.Even physical_port_list = logical_port_name_to_physical_port_list(logical_port_name) if physical_port_list is None: - logger.log_error("No physical ports found for logical port '%s'" % logical_port_name) + self.log_error("No physical ports found for logical port '%s'" % logical_port_name) return PHYSICAL_PORT_NOT_EXIST if len(physical_port_list) > 1: @@ -414,7 +411,7 @@ def post_port_dom_info_to_db(logical_port_name, table, stop_event=threading.Even return SFP_EEPROM_NOT_READY except NotImplementedError: - logger.log_error("This functionality is currently not implemented for this platform") + self.log_error("This functionality is currently not implemented for this platform") sys.exit(NOT_IMPLEMENTED_ERROR) # Update port dom/sfp info in db @@ -451,7 +448,7 @@ def del_port_sfp_dom_info_from_db(logical_port_name, int_tbl, dom_tbl): physical_port_list = logical_port_name_to_physical_port_list(logical_port_name) if physical_port_list is None: - logger.log_error("No physical ports found for logical port '%s'" % logical_port_name) + self.log_error("No physical ports found for logical port '%s'" % logical_port_name) return PHYSICAL_PORT_NOT_EXIST if len(physical_port_list) > 1: @@ -468,7 +465,7 @@ def del_port_sfp_dom_info_from_db(logical_port_name, int_tbl, dom_tbl): dom_tbl._del(port_name) except NotImplementedError: - logger.log_error("This functionality is currently not implemented for this platform") + self.log_error("This functionality is currently not implemented for this platform") sys.exit(NOT_IMPLEMENTED_ERROR) # recover missing sfp table entries if any @@ -543,7 +540,7 @@ def get_media_settings_value(physical_port, key): if default_dict != 0: return default_dict else: - logger.log_error("Error: No values for physical port '%d'" + self.log_error("Error: No values for physical port '%d'" % physical_port) return {} if key[0] in media_dict: @@ -642,7 +639,7 @@ def notify_media_setting(logical_port_name, transceiver_dict, physical_port_list = logical_port_name_to_physical_port_list(logical_port_name) if physical_port_list is None: - logger.log_error("Error: No physical ports found for " + self.log_error("Error: No physical ports found for " "logical port '%s'" % logical_port_name) return PHYSICAL_PORT_NOT_EXIST @@ -654,11 +651,11 @@ def notify_media_setting(logical_port_name, transceiver_dict, num_logical_ports = len(logical_port_list) logical_idx = logical_port_list.index(logical_port_name) if not _wrapper_get_presence(physical_port): - logger.log_info("Media %d presence not detected during notify" + self.log_info("Media %d presence not detected during notify" % physical_port) continue if physical_port not in transceiver_dict: - logger.log_error("Media %d eeprom not populated in " + self.log_error("Media %d eeprom not populated in " "transceiver dict" % physical_port) continue @@ -669,7 +666,7 @@ def notify_media_setting(logical_port_name, transceiver_dict, media_dict = get_media_settings_value(physical_port, key) if(len(media_dict) == 0): - logger.log_error("Error in obtaining media setting") + self.log_error("Error in obtaining media setting") return fvs = swsscommon.FieldValuePairs(len(media_dict)) @@ -728,7 +725,7 @@ def init_port_sfp_status_tbl(stop_event=threading.Event()): break physical_port_list = logical_port_name_to_physical_port_list(logical_port_name) if physical_port_list is None: - logger.log_error("No physical ports found for logical port '%s'" % logical_port_name) + self.log_error("No physical ports found for logical port '%s'" % logical_port_name) update_port_transceiver_status_table(logical_port_name, status_tbl, SFP_STATUS_REMOVED) for physical_port in physical_port_list: @@ -752,7 +749,7 @@ class dom_info_update_task: self.task_stopping_event = threading.Event() def task_worker(self): - logger.log_info("Start DOM monitoring loop") + self.log_info("Start DOM monitoring loop") # Connect to STATE_DB and create transceiver dom info table state_db = daemon_base.db_connect("STATE_DB") @@ -767,7 +764,7 @@ class dom_info_update_task: post_port_dom_info_to_db(logical_port_name, dom_tbl, self.task_stopping_event) post_port_dom_threshold_info_to_db(logical_port_name, dom_tbl, self.task_stopping_event) - logger.log_info("Stop DOM monitoring loop") + self.log_info("Stop DOM monitoring loop") def task_run(self): if self.task_stopping_event.is_set(): @@ -807,11 +804,11 @@ class sfp_state_update_task: event = SYSTEM_FAIL port_dict[EVENT_ON_ALL_SFP] = SYSTEM_FAIL - logger.log_debug("mapping from {} {} to {}".format(status, port_dict, event)) + self.log_debug("mapping from {} {} to {}".format(status, port_dict, event)) return event def task_worker(self, stopping_event, sfp_error_event): - logger.log_info("Start SFP monitoring loop") + self.log_info("Start SFP monitoring loop") transceiver_dict = {} # Connect to STATE_DB and create transceiver dom/sfp info tables @@ -899,13 +896,13 @@ class sfp_state_update_task: next_state = state time_start = time.time() status, port_dict = _wrapper_get_transceiver_change_event(timeout) - logger.log_debug("Got event {} {} in state {}".format(status, port_dict, state)) + self.log_debug("Got event {} {} in state {}".format(status, port_dict, state)) event = self._mapping_event_from_change_event(status, port_dict) if event == SYSTEM_NOT_READY: if state == STATE_INIT: # system not ready, wait and retry if retry >= RETRY_TIMES_FOR_SYSTEM_READY: - logger.log_error("System failed to get ready in {} secs or received system error. Exiting...".format((RETRY_PERIOD_FOR_SYSTEM_READY_MSECS/1000)*RETRY_TIMES_FOR_SYSTEM_READY)) + self.log_error("System failed to get ready in {} secs or received system error. Exiting...".format((RETRY_PERIOD_FOR_SYSTEM_READY_MSECS/1000)*RETRY_TIMES_FOR_SYSTEM_READY)) next_state = STATE_EXIT sfp_error_event.set() else: @@ -921,16 +918,16 @@ class sfp_state_update_task: if time_diff < RETRY_PERIOD_FOR_SYSTEM_READY_MSECS/1000: time.sleep(RETRY_PERIOD_FOR_SYSTEM_READY_MSECS/1000 - time_diff) elif state == STATE_NORMAL: - logger.log_error("Got system_not_ready in normal state, treat as fatal. Exiting...") + self.log_error("Got system_not_ready in normal state, treat as fatal. Exiting...") next_state = STATE_EXIT else: next_state = STATE_EXIT elif event == SYSTEM_BECOME_READY: if state == STATE_INIT: next_state = STATE_NORMAL - logger.log_info("Got system_become_ready in init state, transition to normal state") + self.log_info("Got system_become_ready in init state, transition to normal state") elif state == STATE_NORMAL: - logger.log_info("Got system_become_ready in normal state, ignored") + self.log_info("Got system_become_ready in normal state, ignored") else: next_state = STATE_EXIT elif event == NORMAL_EVENT: @@ -945,18 +942,18 @@ class sfp_state_update_task: for key, value in port_dict.iteritems(): logical_port_list = platform_sfputil.get_physical_to_logical(int(key)) if logical_port_list is None: - logger.log_warning("Got unknown FP port index {}, ignored".format(key)) + self.log_warning("Got unknown FP port index {}, ignored".format(key)) continue for logical_port in logical_port_list: if value == SFP_STATUS_INSERTED: - logger.log_info("Got SFP inserted event") + self.log_info("Got SFP inserted event") # A plugin event will clear the error state. update_port_transceiver_status_table(logical_port, status_tbl, SFP_STATUS_INSERTED) - logger.log_info("receive plug in and update port sfp status table.") + self.log_info("receive plug in and update port sfp status table.") rc = post_port_sfp_info_to_db(logical_port, int_tbl, transceiver_dict) # If we didn't get the sfp info, assuming the eeprom is not ready, give a try again. if rc == SFP_EEPROM_NOT_READY: - logger.log_warning("SFP EEPROM is not ready. One more try...") + self.log_warning("SFP EEPROM is not ready. One more try...") time.sleep(TIME_FOR_SFP_READY_SECS) post_port_sfp_info_to_db(logical_port, int_tbl, transceiver_dict) post_port_dom_info_to_db(logical_port, dom_tbl) @@ -964,17 +961,17 @@ class sfp_state_update_task: notify_media_setting(logical_port, transceiver_dict, app_port_tbl) transceiver_dict.clear() elif value == SFP_STATUS_REMOVED: - logger.log_info("Got SFP removed event") + self.log_info("Got SFP removed event") update_port_transceiver_status_table(logical_port, status_tbl, SFP_STATUS_REMOVED) - logger.log_info("receive plug out and pdate port sfp status table.") + self.log_info("receive plug out and pdate port sfp status table.") del_port_sfp_dom_info_from_db(logical_port, int_tbl, dom_tbl) elif value in errors_block_eeprom_reading: - logger.log_info("Got SFP Error event") + self.log_info("Got SFP Error event") # Add port to error table to stop accessing eeprom of it # If the port already in the error table, the stored error code will # be updated to the new one. update_port_transceiver_status_table(logical_port, status_tbl, value) - logger.log_info("receive error update port sfp status table.") + self.log_info("receive error update port sfp status table.") # In this case EEPROM is not accessible, so remove the DOM info # since it will be outdated if long time no update. # but will keep the interface info in the DB since it static. @@ -982,7 +979,7 @@ class sfp_state_update_task: else: # SFP return unkown event, just ignore for now. - logger.log_warning("Got unknown event {}, ignored".format(value)) + self.log_warning("Got unknown event {}, ignored".format(value)) continue else: next_state = STATE_EXIT @@ -993,24 +990,24 @@ class sfp_state_update_task: # if system recovered in this period xcvrd will transit to INIT state # and continue run, if can not recover then exit. if retry >= RETRY_TIMES_FOR_SYSTEM_FAIL: - logger.log_error("System failed to recover in {} secs. Exiting...".format((RETRY_PERIOD_FOR_SYSTEM_FAIL_MSECS/1000)*RETRY_TIMES_FOR_SYSTEM_FAIL)) + self.log_error("System failed to recover in {} secs. Exiting...".format((RETRY_PERIOD_FOR_SYSTEM_FAIL_MSECS/1000)*RETRY_TIMES_FOR_SYSTEM_FAIL)) next_state = STATE_EXIT sfp_error_event.set() else: retry = retry + 1 waiting_time_compensation_with_sleep(time_start, RETRY_PERIOD_FOR_SYSTEM_FAIL_MSECS/1000) elif state == STATE_NORMAL: - logger.log_error("Got system_fail in normal state, treat as error, transition to INIT...") + self.log_error("Got system_fail in normal state, treat as error, transition to INIT...") next_state = STATE_INIT timeout = RETRY_PERIOD_FOR_SYSTEM_FAIL_MSECS retry = 0 else: next_state = STATE_EXIT else: - logger.log_warning("Got unknown event {} on state {}.".format(event, state)) + self.log_warning("Got unknown event {} on state {}.".format(event, state)) if next_state != state: - logger.log_debug("State transition from {} to {}".format(state, next_state)) + self.log_debug("State transition from {} to {}".format(state, next_state)) state = next_state if next_state == STATE_EXIT: @@ -1019,7 +1016,7 @@ class sfp_state_update_task: elif next_state == STATE_NORMAL: timeout = 0 - logger.log_info("Stop SFP monitoring loop") + self.log_info("Stop SFP monitoring loop") def task_run(self, sfp_error_event): if self.task_stopping_event.is_set(): @@ -1036,9 +1033,9 @@ class sfp_state_update_task: # Daemon ======================================================================= # -class DaemonXcvrd(DaemonBase): - def __init__(self): - DaemonBase.__init__(self) +class DaemonXcvrd(daemon_base.DaemonBase): + def __init__(self, log_identifier): + super(DaemonXcvrd, self).__init__(log_identifier) self.timeout = XCVRD_MAIN_THREAD_SLEEP_SECS self.stop_event = threading.Event() @@ -1047,15 +1044,15 @@ class DaemonXcvrd(DaemonBase): # Signal handler def signal_handler(self, sig, frame): if sig == signal.SIGHUP: - logger.log_info("Caught SIGHUP - ignoring...") + self.log_info("Caught SIGHUP - ignoring...") elif sig == signal.SIGINT: - logger.log_info("Caught SIGINT - exiting...") + self.log_info("Caught SIGINT - exiting...") self.stop_event.set() elif sig == signal.SIGTERM: - logger.log_info("Caught SIGTERM - exiting...") + self.log_info("Caught SIGTERM - exiting...") self.stop_event.set() else: - logger.log_warning("Caught unhandled signal '" + sig + "'") + self.log_warning("Caught unhandled signal '" + sig + "'") # Wait for port config is done def wait_for_port_config_done(self): @@ -1072,7 +1069,7 @@ class DaemonXcvrd(DaemonBase): if state == swsscommon.Select.TIMEOUT: continue if state != swsscommon.Select.OBJECT: - logger.log_warning("sel.select() did not return swsscommon.Select.OBJECT") + self.log_warning("sel.select() did not return swsscommon.Select.OBJECT") continue (key, op, fvp) = sst.pop() @@ -1082,11 +1079,11 @@ class DaemonXcvrd(DaemonBase): def load_media_settings(self): global media_settings global g_dict - (platform, hwsku_path) = self.get_path_to_platform_and_hwsku() + (platform_path, hwsku_path) = device_info.get_paths_to_platform_and_hwsku_dirs() - media_settings_file_path = "/".join([platform, "media_settings.json"]) + media_settings_file_path = os.path.join(platform_path, "media_settings.json") if not os.path.isfile(media_settings_file_path): - logger.log_info("xcvrd: No media file exists") + self.log_info("xcvrd: No media file exists") return {} media_file = open(media_settings_file_path, "r") @@ -1098,14 +1095,14 @@ class DaemonXcvrd(DaemonBase): global platform_sfputil global platform_chassis - logger.log_info("Start daemon init...") + self.log_info("Start daemon init...") # Load new platform api class try: import sonic_platform.platform import sonic_platform_base.sonic_sfp.sfputilhelper platform_chassis = sonic_platform.platform.Platform().get_chassis() - logger.log_info("chassis loaded {}".format(platform_chassis)) + self.log_info("chassis loaded {}".format(platform_chassis)) # we have to make use of sfputil for some features # even though when new platform api is used for all vendors. # in this sense, we treat it as a part of new platform api. @@ -1113,22 +1110,22 @@ class DaemonXcvrd(DaemonBase): # which is the root of new platform api. platform_sfputil = sonic_platform_base.sonic_sfp.sfputilhelper.SfpUtilHelper() except Exception as e: - logger.log_warning("Failed to load chassis due to {}".format(repr(e))) + self.log_warning("Failed to load chassis due to {}".format(repr(e))) # Load platform specific sfputil class if platform_chassis is None or platform_sfputil is None: try: platform_sfputil = self.load_platform_util(PLATFORM_SPECIFIC_MODULE_NAME, PLATFORM_SPECIFIC_CLASS_NAME) except Exception as e: - logger.log_error("Failed to load sfputil: %s" % (str(e)), True) + self.log_error("Failed to load sfputil: %s" % (str(e)), True) sys.exit(SFPUTIL_LOAD_ERROR) # Load port info try: - port_config_file_path = self.get_path_to_port_config_file() + port_config_file_path = device_info.get_path_to_port_config_file() platform_sfputil.read_porttab_mappings(port_config_file_path) except Exception, e: - logger.log_error("Failed to read port info: %s" % (str(e)), True) + self.log_error("Failed to read port info: %s" % (str(e)), True) sys.exit(PORT_CONFIG_LOAD_ERROR) # Connect to STATE_DB and create transceiver dom/sfp info tables @@ -1144,20 +1141,20 @@ class DaemonXcvrd(DaemonBase): is_warm_start = warmstart.isWarmStart() # Make sure this daemon started after all port configured - logger.log_info("Wait for port config is done") + self.log_info("Wait for port config is done") self.wait_for_port_config_done() # Post all the current interface dom/sfp info to STATE_DB - logger.log_info("Post all port DOM/SFP info to DB") + self.log_info("Post all port DOM/SFP info to DB") post_port_sfp_dom_info_to_db(is_warm_start, self.stop_event) # Init port sfp status table - logger.log_info("Init port sfp status table") + self.log_info("Init port sfp status table") init_port_sfp_status_tbl(self.stop_event) # Deinitialize daemon def deinit(self): - logger.log_info("Start daemon deinit...") + self.log_info("Start daemon deinit...") # Delete all the information from DB and then exit logical_port_list = platform_sfputil.logical @@ -1167,7 +1164,7 @@ class DaemonXcvrd(DaemonBase): # Run daemon def run(self): - logger.log_info("Starting up...") + self.log_info("Starting up...") # Start daemon initialization sequence self.init() @@ -1181,13 +1178,13 @@ class DaemonXcvrd(DaemonBase): sfp_state_update.task_run(self.sfp_error_event) # Start main loop - logger.log_info("Start daemon main loop") + self.log_info("Start daemon main loop") while not self.stop_event.wait(self.timeout): # Check the integrity of the sfp info table and recover the missing entries if any recover_missing_sfp_table_entries(platform_sfputil, self.int_tbl, self.status_tbl, self.stop_event) - logger.log_info("Stop daemon main loop") + self.log_info("Stop daemon main loop") # Stop the dom sensor info update thread dom_info_update.task_stop() @@ -1198,7 +1195,7 @@ class DaemonXcvrd(DaemonBase): # Start daemon deinitialization sequence self.deinit() - logger.log_info("Shutting down...") + self.log_info("Shutting down...") if self.sfp_error_event.is_set(): sys.exit(SFP_SYSTEM_ERROR) @@ -1208,7 +1205,7 @@ class DaemonXcvrd(DaemonBase): # def main(): - xcvrd = DaemonXcvrd() + xcvrd = DaemonXcvrd(SYSLOG_IDENTIFIER) xcvrd.run() if __name__ == '__main__':