Skip to content

Commit ab2c42e

Browse files
nazariigandriymoroz-mlnx
authored andcommitted
Refactored daemon base API: added Logger. (#2672)
* Refactored daemon base API: added Logger. Signed-off-by: Nazarii Hnydyn <[email protected]>
1 parent 67113ad commit ab2c42e

File tree

1 file changed

+94
-50
lines changed

1 file changed

+94
-50
lines changed

src/sonic-daemon-base/sonic_daemon_base/daemon_base.py

+94-50
Original file line numberDiff line numberDiff line change
@@ -4,82 +4,111 @@
44
import imp
55
import signal
66
import subprocess
7+
import os
78
import sys
89
import syslog
910
from swsscommon import swsscommon
1011
except ImportError, e:
1112
raise ImportError (str(e) + " - required module not found")
1213

13-
#============================= Constants =============================
14+
#
15+
# Constants ====================================================================
16+
#
17+
18+
# Redis DB information
19+
REDIS_HOSTNAME = 'localhost'
20+
REDIS_PORT = 6379
21+
REDIS_TIMEOUT_MSECS = 0
1422

1523
# Platform root directory inside docker
16-
PLATFORM_ROOT_DOCKER = "/usr/share/sonic/platform"
24+
PLATFORM_ROOT_DOCKER = '/usr/share/sonic/platform'
1725
SONIC_CFGGEN_PATH = '/usr/local/bin/sonic-cfggen'
1826
HWSKU_KEY = 'DEVICE_METADATA.localhost.hwsku'
1927
PLATFORM_KEY = 'DEVICE_METADATA.localhost.platform'
2028

29+
# Port config information
30+
PORT_CONFIG = 'port_config.ini'
31+
PORTMAP = 'portmap.ini'
32+
2133
EEPROM_MODULE_NAME = 'eeprom'
2234
EEPROM_CLASS_NAME = 'board'
2335

24-
class DaemonBase(object):
25-
# Redis DB information
26-
redis_hostname = "localhost"
27-
redis_port = 6379
28-
redis_timeout_msecs = 0
36+
#
37+
# Helper functions =============================================================
38+
#
2939

30-
def __init__(self):
31-
self.log_info("Starting up...")
32-
# Register our signal handlers
33-
signal.signal(signal.SIGHUP, self.signal_handler)
34-
signal.signal(signal.SIGINT, self.signal_handler)
35-
signal.signal(signal.SIGTERM, self.signal_handler)
40+
def db_connect(db):
41+
return swsscommon.DBConnector(db,
42+
REDIS_HOSTNAME,
43+
REDIS_PORT,
44+
REDIS_TIMEOUT_MSECS)
45+
46+
#
47+
# Helper classes ===============================================================
48+
#
49+
50+
class Logger(object):
51+
def __init__(self, syslog_identifier):
52+
syslog.openlog(ident=syslog_identifier, logoption=syslog.LOG_NDELAY, facility=syslog.LOG_DAEMON)
3653

3754
def __del__(self):
38-
self.log_error("Return from daemon, exiting...")
55+
syslog.closelog()
3956

40-
def run(self):
41-
raise NotImplementedError()
57+
def log_error(self, msg, also_print_to_console=False):
58+
syslog.syslog(syslog.LOG_ERR, msg)
59+
60+
if also_print_to_console:
61+
print msg
4262

43-
# ========================== Connect to DB ============================
44-
def db_connect(self, db):
45-
return swsscommon.DBConnector(db,
46-
self.redis_hostname,
47-
self.redis_port,
48-
self.redis_timeout_msecs)
63+
def log_warning(self, msg, also_print_to_console=False):
64+
syslog.syslog(syslog.LOG_WARNING, msg)
65+
66+
if also_print_to_console:
67+
print msg
68+
69+
def log_notice(self, msg, also_print_to_console=False):
70+
syslog.syslog(syslog.LOG_NOTICE, msg)
4971

50-
# ========================== Syslog wrappers ==========================
51-
def log_info(self, msg):
52-
syslog.openlog()
72+
if also_print_to_console:
73+
print msg
74+
75+
def log_info(self, msg, also_print_to_console=False):
5376
syslog.syslog(syslog.LOG_INFO, msg)
54-
syslog.closelog()
5577

56-
def log_warning(self, msg):
57-
syslog.openlog()
58-
syslog.syslog(syslog.LOG_WARNING, msg)
59-
syslog.closelog()
78+
if also_print_to_console:
79+
print msg
6080

61-
def log_error(self, msg):
62-
syslog.openlog()
63-
syslog.syslog(syslog.LOG_ERR, msg)
64-
syslog.closelog()
81+
def log_debug(self, msg, also_print_to_console=False):
82+
syslog.syslog(syslog.LOG_DEBUG, msg)
83+
84+
if also_print_to_console:
85+
print msg
6586

66-
#========================== Signal Handling ==========================
87+
#
88+
# Daemon =======================================================================
89+
#
90+
91+
class DaemonBase(object):
92+
def __init__(self):
93+
# Register our signal handlers
94+
signal.signal(signal.SIGHUP, self.signal_handler)
95+
signal.signal(signal.SIGINT, self.signal_handler)
96+
signal.signal(signal.SIGTERM, self.signal_handler)
97+
98+
# Signal handler
6799
def signal_handler(self, sig, frame):
68100
if sig == signal.SIGHUP:
69-
self.log_info("Caught SIGHUP - ignoring...")
70-
return
101+
syslog.syslog(syslog.LOG_INFO, "Caught SIGHUP - ignoring...")
71102
elif sig == signal.SIGINT:
72-
self.log_info("Caught SIGINT - exiting...")
103+
syslog.syslog(syslog.LOG_INFO, "Caught SIGINT - exiting...")
73104
sys.exit(128 + sig)
74105
elif sig == signal.SIGTERM:
75-
self.log_info("Caught SIGTERM - exiting...")
106+
syslog.syslog(syslog.LOG_INFO, "Caught SIGTERM - exiting...")
76107
sys.exit(128 + sig)
77108
else:
78-
self.log_warning("Caught unhandled signal '" + sig + "'")
79-
return
109+
syslog.syslog(syslog.LOG_WARNING, "Caught unhandled signal '" + sig + "'")
80110

81-
#============ Functions to load platform-specific classes ============
82-
# Returns platform and HW SKU
111+
# Returns platform and hwsku
83112
def get_platform_and_hwsku(self):
84113
try:
85114
proc = subprocess.Popen([SONIC_CFGGEN_PATH, '-H', '-v', PLATFORM_KEY],
@@ -98,12 +127,11 @@ def get_platform_and_hwsku(self):
98127
proc.wait()
99128
hwsku = stdout.rstrip('\n')
100129
except OSError, e:
101-
self.log_error("Cannot to detect platform")
102-
raise OSError("Cannot detect platform")
130+
raise OSError("Failed to detect platform: %s" % (str(e)))
103131

104132
return (platform, hwsku)
105133

106-
# Returns path to hwsku
134+
# Returns path to platform and hwsku
107135
def get_path_to_platform_and_hwsku(self):
108136
# Get platform and hwsku
109137
(platform, hwsku) = self.get_platform_and_hwsku()
@@ -114,6 +142,21 @@ def get_path_to_platform_and_hwsku(self):
114142

115143
return (platform_path, hwsku_path)
116144

145+
# Returns path to port config file
146+
def get_path_to_port_config_file(self):
147+
# Get platform and hwsku path
148+
(platform_path, hwsku_path) = self.get_path_to_platform_and_hwsku()
149+
150+
# First check for the presence of the new 'port_config.ini' file
151+
port_config_file_path = "/".join([hwsku_path, PORT_CONFIG])
152+
if not os.path.isfile(port_config_file_path):
153+
# port_config.ini doesn't exist. Try loading the legacy 'portmap.ini' file
154+
port_config_file_path = "/".join([hwsku_path, PORTMAP])
155+
if not os.path.isfile(port_config_file_path):
156+
raise IOError("Failed to detect port config file: %s" % (port_config_file_path))
157+
158+
return port_config_file_path
159+
117160
# Loads platform specific psuutil module from source
118161
def load_platform_util(self, module_name, class_name):
119162
platform_util = None
@@ -125,8 +168,7 @@ def load_platform_util(self, module_name, class_name):
125168
module_file = "/".join([platform_path, "plugins", module_name + ".py"])
126169
module = imp.load_source(module_name, module_file)
127170
except IOError, e:
128-
self.log_error("Failed to load platform module '%s': %s" % (module_name, str(e)))
129-
return None
171+
raise IOError("Failed to load platform module '%s': %s" % (module_name, str(e)))
130172

131173
try:
132174
platform_util_class = getattr(module, class_name)
@@ -136,8 +178,10 @@ def load_platform_util(self, module_name, class_name):
136178
else:
137179
platform_util = platform_util_class()
138180
except AttributeError, e:
139-
self.log_error("Failed to instantiate '%s' class: %s" % (class_name, str(e)))
140-
return None
181+
raise AttributeError("Failed to instantiate '%s' class: %s" % (class_name, str(e)))
141182

142183
return platform_util
143184

185+
# Runs daemon
186+
def run(self):
187+
raise NotImplementedError()

0 commit comments

Comments
 (0)