Skip to content

Commit

Permalink
Migrate from sonic-daemon-base package to sonic-py-common package (so…
Browse files Browse the repository at this point in the history
…nic-net#74)

As part of consolidating all common Python-based functionality into the new sonic-py-common package, this pull request migrates from importing the sonic-daemon-base package to importing the sonic-py-common package. This is the next step toward resolving sonic-net#4999.

- Also reorganize imports for consistency
  • Loading branch information
jleveque authored Aug 5, 2020
1 parent 49d145c commit ec2c3bc
Show file tree
Hide file tree
Showing 7 changed files with 185 additions and 205 deletions.
17 changes: 6 additions & 11 deletions sonic-ledd/scripts/ledd
Original file line number Diff line number Diff line change
Expand Up @@ -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")

Expand All @@ -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):
Expand All @@ -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
Expand All @@ -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()
Expand All @@ -106,7 +101,7 @@ class DaemonLedd(DaemonBase):
return 1

def main():
ledd = DaemonLedd()
ledd = DaemonLedd(SYSLOG_IDENTIFIER)
ledd.run()

if __name__ == '__main__':
Expand Down
46 changes: 20 additions & 26 deletions sonic-pcied/scripts/pcied
Original file line number Diff line number Diff line change
Expand Up @@ -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")

Expand All @@ -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
Expand All @@ -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)
Expand All @@ -84,52 +78,52 @@ 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 =========================================================================
#


def main():
pcied = DaemonPcied()
pcied = DaemonPcied(SYSLOG_IDENTIFIER)
pcied.run()

if __name__ == '__main__':
Expand Down
49 changes: 23 additions & 26 deletions sonic-psud/scripts/psud
Original file line number Diff line number Diff line change
Expand Up @@ -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")

Expand Down Expand Up @@ -49,8 +48,6 @@ PSU_INFO_UPDATE_PERIOD_SECS = 3

PSUUTIL_LOAD_ERROR = 1

logger = Logger(SYSLOG_IDENTIFIER)

platform_psuutil = None
platform_chassis = None

Expand Down Expand Up @@ -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 ===================================================================
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -196,46 +193,46 @@ 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 = {}

# 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
Expand All @@ -249,22 +246,22 @@ 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):
psu_tbl._del(PSU_INFO_KEY_TEMPLATE.format(psu_index))

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:
Expand All @@ -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)
Expand Down Expand Up @@ -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)
])
Expand All @@ -368,7 +365,7 @@ class DaemonPsud(DaemonBase):
#

def main():
psud = DaemonPsud()
psud = DaemonPsud(SYSLOG_IDENTIFIER)
psud.run()

if __name__ == '__main__':
Expand Down
Loading

0 comments on commit ec2c3bc

Please sign in to comment.