I need to write simple daemon with web interface.
The idea is to use python-daemon package and run wsgiref.simple_server
inside one thread.
Daemon works fine with the following code :
import daemon
import logging
import time
import signal
import threading
logfilename = '/var/log/testdaemon.log'
logger = logging.getLogger("DaemonLog")
logger.setLevel(logging.INFO)
formatter = logging.Formatter(
'%(asctime)s:%(levelname)s:%(message)s',
'%Y-%m-%d %H:%M:%S')
handler = logging.FileHandler(logfilename)
handler.setFormatter(formatter)
logger.addHandler(handler)
def initial_program_setup():
logger.info('daemon started')
def do_main_program():
while True:
time.sleep(1)
logger.info('another second passed')
def program_cleanup(signum, frame):
logger.info('daemon stops')
context.terminate(signum, frame)
def reload_program_config(signum, frame):
logger.info('reloading config')
context = daemon.DaemonContext()
context.signal_map = {
signal.SIGTERM: program_cleanup,
signal.SIGHUP: 'terminate',
signal.SIGUSR1: reload_program_config,
}
context.files_preserve = [handler.stream]
initial_program_setup()
with context:
do_main_program()
But if I start a thread in initial_program_setup()
like this :
def web_gui():
logger.info('weg gui started')
web = threading.Thread(target=web_gui)
web.setDaemon(True)
def initial_program_setup():
logger.info('daemon started')
web.start()
then looks like daemon exits after thread completes. Adding something like
while True:
time.sleep(1)
to web_gui()
(to make thread run forever, like a web server should) makes it even worse: even the line web gui started
doesn't show up in log.
My questions are:
- Why this doesn't work? What's the proper way to start thread in daemon?
- Maybe there is a better way to control daemon through web interface? With such architecture, I think I should start new thread for each interface page, which is hard to scale.
Thanks.