Skip to content

Commit 15ccb25

Browse files
committed
Refactor daemons based on sonic-daemon-common package
Signed-off-by: Kevin Wang <[email protected]>
1 parent e5d8155 commit 15ccb25

3 files changed

Lines changed: 72 additions & 424 deletions

File tree

  • sonic-ledd/scripts
  • sonic-psud/scripts
  • sonic-xcvrd/scripts

sonic-ledd/scripts/ledd

Lines changed: 14 additions & 132 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ try:
1515
import sys
1616
import syslog
1717
from swsscommon import swsscommon
18+
from sonic_daemon_base.daemon_base import DaemonBase
1819
except ImportError, e:
1920
raise ImportError (str(e) + " - required module not found")
2021

@@ -34,133 +35,18 @@ Options:
3435

3536
LED_MODULE_NAME = "led_control"
3637
LED_CLASS_NAME = "LedControl"
37-
38-
SONIC_CFGGEN = "/usr/local/bin/sonic-cfggen"
39-
MINIGRAPH_FILE = "/etc/sonic/minigraph.xml"
40-
HWSKU_KEY = "minigraph_hwsku"
41-
PLATFORM_KEY = "platform"
42-
43-
# platform directory in base image
44-
PLATFORM_ROOT = "/usr/share/sonic/device"
45-
46-
# platform root directory inside docker
47-
PLATFORM_ROOT_DOCKER = "/usr/share/sonic/platform"
48-
49-
REDIS_HOSTNAME = "localhost"
50-
REDIS_PORT = 6379
51-
REDIS_TIMEOUT_USECS = 0
52-
5338
SELECT_TIMEOUT = 1000
5439

55-
#========================== Syslog wrappers ==========================
56-
57-
def log_info(msg):
58-
syslog.openlog(SYSLOG_IDENTIFIER)
59-
syslog.syslog(syslog.LOG_INFO, msg)
60-
syslog.closelog()
61-
62-
def log_warning(msg):
63-
syslog.openlog(SYSLOG_IDENTIFIER)
64-
syslog.syslog(syslog.LOG_WARNING, msg)
65-
syslog.closelog()
66-
67-
def log_error(msg):
68-
syslog.openlog(SYSLOG_IDENTIFIER)
69-
syslog.syslog(syslog.LOG_ERR, msg)
70-
syslog.closelog()
71-
72-
#========================== Signal Handling ==========================
73-
74-
def signal_handler(sig, frame):
75-
if sig == signal.SIGHUP:
76-
log_info("Caught SIGHUP - ignoring...")
77-
return
78-
elif sig == signal.SIGINT:
79-
log_info("Caught SIGINT - exiting...")
80-
sys.exit(128 + sig)
81-
elif sig == signal.SIGTERM:
82-
log_info("Caught SIGTERM - exiting...")
83-
sys.exit(128 + sig)
84-
else:
85-
log_warning("Caught unhandled signal '" + sig + "'")
86-
87-
88-
#============ Functions to load platform-specific classes ============
89-
90-
# Returns platform and HW SKU
91-
def get_platform_and_hwsku():
92-
try:
93-
proc = subprocess.Popen([SONIC_CFGGEN, '-v', PLATFORM_KEY],
94-
stdout=subprocess.PIPE,
95-
shell=False,
96-
stderr=subprocess.STDOUT)
97-
stdout = proc.communicate()[0]
98-
proc.wait()
99-
platform = stdout.rstrip('\n')
100-
101-
proc = subprocess.Popen([SONIC_CFGGEN, '-m', MINIGRAPH_FILE, '-v', HWSKU_KEY],
102-
stdout=subprocess.PIPE,
103-
shell=False,
104-
stderr=subprocess.STDOUT)
105-
stdout = proc.communicate()[0]
106-
proc.wait()
107-
hwsku = stdout.rstrip('\n')
108-
except OSError, e:
109-
log_error("Cannot detect platform")
110-
raise OSError("Cannot detect platform")
111-
112-
return (platform, hwsku)
113-
114-
115-
# Loads platform-specific LED control module from source
116-
def load_platform_led_control_module():
117-
# Get platform and hwsku
118-
(platform, hwsku) = get_platform_and_hwsku()
119-
120-
# Load platform module from source
121-
platform_path = '/'.join([PLATFORM_ROOT, platform])
122-
hwsku_path = '/'.join([platform_path, hwsku])
123-
124-
module_file_base = '/'.join([platform_path, 'plugins', LED_MODULE_NAME + '.py'])
125-
126-
module_file_docker = '/'.join([PLATFORM_ROOT_DOCKER, 'plugins', LED_MODULE_NAME + '.py'])
127-
128-
# If we can't locate a platform-specific module, exit gracefully, assuming this
129-
# platform utilizes a hardware-based LED control solution
130-
if os.path.isfile(module_file_base):
131-
module_file = module_file_base
132-
elif os.path.isfile(module_file_docker):
133-
module_file = module_file_docker
134-
else:
135-
log_info("Failed to locate platform-specific %s module." % LED_MODULE_NAME)
136-
return None
137-
138-
try:
139-
module = imp.load_source(LED_MODULE_NAME, module_file)
140-
except IOError, e:
141-
log_error("Failed to load platform module '%s': %s" % (LED_MODULE_NAME, str(e)))
142-
return None
143-
144-
log_info("Loaded module '%s'." % LED_MODULE_NAME)
145-
146-
try:
147-
led_control_class = getattr(module, LED_CLASS_NAME)
148-
led_control = led_control_class()
149-
except AttributeError, e:
150-
log_error("Failed to instantiate '%s' class: %s" % (LED_CLASS_NAME, str(e)))
151-
return None
152-
153-
log_info("Instantiated class '%s.%s'." % (LED_MODULE_NAME, LED_CLASS_NAME))
154-
155-
return led_control
156-
15740
#=============================== Main ================================
15841

15942
def main():
160-
log_info("Starting up...")
43+
ledd_util = DaemonBase()
44+
if not ledd_util:
45+
print "Failed to load led daemon utilities"
46+
sys.exit(1)
16147

16248
if not os.geteuid() == 0:
163-
log_error("Must be root to run this daemon")
49+
ledd_util.log_error("Must be root to run this daemon")
16450
print "Error: Must be root to run this daemon"
16551
sys.exit(1)
16652

@@ -183,21 +69,17 @@ def main():
18369
print 'ledd version ' + VERSION
18470
sys.exit(0)
18571

186-
# Register our signal handlers
187-
signal.signal(signal.SIGHUP, signal_handler)
188-
signal.signal(signal.SIGINT, signal_handler)
189-
signal.signal(signal.SIGTERM, signal_handler)
190-
19172
# Load platform-specific LedControl module
192-
led_control = load_platform_led_control_module()
193-
if led_control is None:
194-
sys.exit(0)
73+
led_control = ledd_util.load_platform_util(LED_MODULE_NAME, LED_CLASS_NAME)
74+
if not led_control:
75+
ledd_util.log_error("failed to load ledutil")
76+
sys.exit(1)
19577

19678
# Open a handle to the Application database
19779
appl_db = swsscommon.DBConnector(swsscommon.APPL_DB,
198-
REDIS_HOSTNAME,
199-
REDIS_PORT,
200-
REDIS_TIMEOUT_USECS)
80+
ledd_util.redis_hostname,
81+
ledd_util.redis_port,
82+
ledd_util.redis_timeout_usecs)
20183

20284
# Subscribe to PORT table notifications in the Application DB
20385
sel = swsscommon.Select()
@@ -214,7 +96,7 @@ def main():
21496
# Do not flood log when select times out
21597
continue
21698
if state != swsscommon.Select.OBJECT:
217-
log_warning("sel.select() did not return swsscommon.Select.OBJECT")
99+
ledd_util.log_warning("sel.select() did not return swsscommon.Select.OBJECT")
218100
continue
219101

220102
(key, op, fvp) = sst.pop()

sonic-psud/scripts/psud

Lines changed: 17 additions & 133 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
#!/usr/bin/env python2
22

33
"""
4-
Psud
4+
psud
55
PSU information update daemon for SONiC
66
This daemon will loop to collect PSU related information and then write the information to state DB.
77
Currently it is implemented based on old plugins rather than new platform APIs. So the PSU information just
@@ -10,180 +10,64 @@
1010
"""
1111

1212
try:
13-
import getopt
14-
import os
15-
import imp
16-
import signal
17-
import subprocess
1813
import sys
19-
import syslog
2014
import time
2115
from swsscommon import swsscommon
16+
from sonic_daemon_base.daemon_base import DaemonBase
2217
except ImportError, e:
2318
raise ImportError (str(e) + " - required module not found")
2419

2520
#============================= Constants =============================
2621

27-
VERSION = '1.0'
28-
29-
SYSLOG_IDENTIFIER = os.path.basename(__file__)
3022
PLATFORM_SPECIFIC_MODULE_NAME = "psuutil"
3123
PLATFORM_SPECIFIC_CLASS_NAME = "PsuUtil"
3224

33-
# Platform root directory inside docker
34-
PLATFORM_ROOT_DOCKER = "/usr/share/sonic/platform"
35-
SONIC_CFGGEN_PATH = '/usr/local/bin/sonic-cfggen'
36-
HWSKU_KEY = 'DEVICE_METADATA.localhost.hwsku'
37-
PLATFORM_KEY = 'DEVICE_METADATA.localhost.platform'
38-
39-
# Global platform-specific psuutil class instance
40-
platform_psuutil = None
41-
42-
REDIS_HOSTNAME = "localhost"
43-
REDIS_PORT = 6379
44-
REDIS_TIMEOUT_MSECS = 0
45-
4625
PSU_INFO_UPDATE_PERIOD_SECS = 3
4726

48-
#========================== Syslog wrappers ==========================
49-
50-
def log_info(msg, also_print_to_console=False):
51-
syslog.openlog(SYSLOG_IDENTIFIER)
52-
syslog.syslog(syslog.LOG_INFO, msg)
53-
syslog.closelog()
54-
55-
if also_print_to_console:
56-
print msg
57-
58-
def log_warning(msg, also_print_to_console=False):
59-
syslog.openlog(SYSLOG_IDENTIFIER)
60-
syslog.syslog(syslog.LOG_WARNING, msg)
61-
syslog.closelog()
62-
63-
if also_print_to_console:
64-
print msg
65-
66-
def log_error(msg, also_print_to_console=False):
67-
syslog.openlog(SYSLOG_IDENTIFIER)
68-
syslog.syslog(syslog.LOG_ERR, msg)
69-
syslog.closelog()
70-
71-
if also_print_to_console:
72-
print msg
73-
74-
#========================== Signal Handling ==========================
75-
76-
def signal_handler(sig, frame):
77-
if sig == signal.SIGHUP:
78-
log_info("Caught SIGHUP - ignoring...")
79-
return
80-
elif sig == signal.SIGINT:
81-
log_info("Caught SIGINT - exiting...")
82-
sys.exit(128 + sig)
83-
elif sig == signal.SIGTERM:
84-
log_info("Caught SIGTERM - exiting...")
85-
sys.exit(128 + sig)
86-
else:
87-
log_warning("Caught unhandled signal '" + sig + "'")
88-
return
89-
9027
#============ Functions to load platform-specific classes ============
9128

92-
# Returns platform and HW SKU
93-
def get_platform_and_hwsku():
94-
try:
95-
proc = subprocess.Popen([SONIC_CFGGEN_PATH, '-H', '-v', PLATFORM_KEY],
96-
stdout=subprocess.PIPE,
97-
shell=False,
98-
stderr=subprocess.STDOUT)
99-
stdout = proc.communicate()[0]
100-
proc.wait()
101-
platform = stdout.rstrip('\n')
102-
103-
proc = subprocess.Popen([SONIC_CFGGEN_PATH, '-d', '-v', HWSKU_KEY],
104-
stdout=subprocess.PIPE,
105-
shell=False,
106-
stderr=subprocess.STDOUT)
107-
stdout = proc.communicate()[0]
108-
proc.wait()
109-
hwsku = stdout.rstrip('\n')
110-
except OSError, e:
111-
raise OSError("Cannot detect platform")
112-
113-
return (platform, hwsku)
114-
115-
# Loads platform specific psuutil module from source
116-
def load_platform_psuutil():
117-
global platform_psuutil
118-
119-
# Get platform and hwsku
120-
(platform, hwsku) = get_platform_and_hwsku()
121-
122-
# Load platform module from source
123-
platform_path = PLATFORM_ROOT_DOCKER
124-
hwsku_path = "/".join([platform_path, hwsku])
125-
126-
try:
127-
module_file = "/".join([platform_path, "plugins", PLATFORM_SPECIFIC_MODULE_NAME + ".py"])
128-
module = imp.load_source(PLATFORM_SPECIFIC_MODULE_NAME, module_file)
129-
except IOError, e:
130-
log_error("Failed to load platform module '%s': %s" % (PLATFORM_SPECIFIC_MODULE_NAME, str(e)), True)
131-
return -1
132-
133-
try:
134-
platform_psuutil_class = getattr(module, PLATFORM_SPECIFIC_CLASS_NAME)
135-
platform_psuutil = platform_psuutil_class()
136-
except AttributeError, e:
137-
log_error("Failed to instantiate '%s' class: %s" % (PLATFORM_SPECIFIC_CLASS_NAME, str(e)), True)
138-
return -2
139-
140-
return 0
141-
142-
def psu_db_update(psu_tbl, num_psus):
29+
def psu_db_update(psuutil, psu_tbl, num_psus):
14330
for psu_index in range(1, num_psus + 1):
14431
fvs = swsscommon.FieldValuePairs([('presence',
145-
'true' if platform_psuutil.get_psu_presence(psu_index) else 'false'),
32+
'true' if psuutil.get_psu_presence(psu_index) else 'false'),
14633
('status',
147-
'true' if platform_psuutil.get_psu_status(psu_index) else 'false')])
34+
'true' if psuutil.get_psu_status(psu_index) else 'false')])
14835
psu_tbl.set("PSU {}".format(psu_index), fvs)
14936

15037
#=============================== Main ================================
15138

15239
def main():
153-
log_info("Starting up...")
154-
155-
# Register our signal handlers
156-
signal.signal(signal.SIGHUP, signal_handler)
157-
signal.signal(signal.SIGINT, signal_handler)
158-
signal.signal(signal.SIGTERM, signal_handler)
40+
psud_util = DaemonBase()
41+
if not psud_util:
42+
print "Failed to load psu daemon utilities"
43+
sys.exit(1)
15944

16045
# Load platform-specific psuutil class
161-
err = load_platform_psuutil()
162-
if err != 0:
163-
log_error("failed to load psuutil")
46+
platform_psuutil = psud_util.load_platform_util(PLATFORM_SPECIFIC_MODULE_NAME, PLATFORM_SPECIFIC_CLASS_NAME)
47+
if not platform_psuutil:
48+
psud_util.log_error("failed to load psuutil")
16449
sys.exit(1)
16550

16651
state_db = swsscommon.DBConnector(swsscommon.STATE_DB,
167-
REDIS_HOSTNAME,
168-
REDIS_PORT,
169-
REDIS_TIMEOUT_MSECS)
52+
psud_util.redis_hostname,
53+
psud_util.redis_port,
54+
psud_util.redis_timeout_msecs)
17055
psu_tbl = swsscommon.Table(state_db, "PSU_INFO")
17156
chassis_tbl = swsscommon.Table(state_db, "CHASSIS_INFO")
17257
num_psus = platform_psuutil.get_num_psus()
17358
fvs = swsscommon.FieldValuePairs([('num_psus', str(num_psus))])
17459
chassis_tbl.set('chassis 1', fvs)
17560

17661
# Start main loop to listen to the PSU change event.
177-
log_info("Start main loop")
62+
psud_util.log_info("Start main loop")
17863
while True:
179-
psu_db_update(psu_tbl, num_psus)
64+
psu_db_update(platform_psuutil, psu_tbl, num_psus)
18065
time.sleep(PSU_INFO_UPDATE_PERIOD_SECS)
18166

18267
# Clean all the information from DB and then exit
18368
for psu_index in range(1, num_psus + 1):
18469
psu_tbl._del("PSU {}".format(psu_index))
18570
chassis_tbl._del('chassis 1')
186-
log_error("Error: return error from psu daemon, exiting...")
18771
return 1
18872

18973
if __name__ == '__main__':

0 commit comments

Comments
 (0)