diff options
author | Lars Wirzenius <liw@liw.fi> | 2020-07-19 10:16:22 +0300 |
---|---|---|
committer | Lars Wirzenius <liw@liw.fi> | 2020-07-19 10:50:12 +0300 |
commit | a634332270b609a3eb6b22caa79ec116e5b8c563 (patch) | |
tree | 743dac5c81603dadcbf5ca05c4b8c6c8c405c284 | |
parent | 11d2149cd728db3a7ae2a7cc843030009a1455e7 (diff) | |
download | ewww-a634332270b609a3eb6b22caa79ec116e5b8c563.tar.gz |
test: add daemon.py to start/stop daemons
-rw-r--r-- | daemon.py | 69 |
1 files changed, 69 insertions, 0 deletions
diff --git a/daemon.py b/daemon.py new file mode 100644 index 0000000..33057bd --- /dev/null +++ b/daemon.py @@ -0,0 +1,69 @@ +############################################################################# +# Start and stop daemons, or background processes. + + +import logging +import os +import signal + + +# Start a process in the background. +def start_daemon(ctx, name, argv): + logging.debug(f"Starting daemon {name}") + logging.debug(f" ctx={ctx.as_dict()}") + logging.debug(f" name={name}") + logging.debug(f" argv={argv}") + + if "daemon" not in ctx.as_dict(): + ctx["daemon"] = {} + assert name not in ctx["daemon"] + this = ctx["daemon"][name] = { + "pid-file": f"{name}.pid", + "stderr": f"{name}.stderr", + "stdout": f"{name}.stdout", + } + runcmd( + ctx, + [ + "/usr/sbin/daemonize", + "-c", + os.getcwd(), + "-p", + this["pid-file"], + "-e", + this["stderr"], + "-o", + this["stdout"], + ] + + argv, + ) + exit_code_is(ctx, 0) + this["pid"] = int(open("ewww.pid").read().strip()) + assert process_exists(this["pid"]) + + logging.debug(f"Started daemon {name}") + logging.debug(f" ctx={ctx.as_dict()}") + + +# Stop a daemon. +def stop_daemon(ctx, name): + logging.debug(f"Stopping daemon {name}") + logging.debug(f" ctx={ctx.as_dict()}") + logging.debug(f" ctx['daemon']={ctx.as_dict()['daemon']}") + + this = ctx["daemon"][name] + terminate_process(this["pid"], signal.SIGKILL) + + +# Does a process exist? +def process_exists(pid): + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + return True + + +# Terminate process. +def terminate_process(pid, signal): + os.kill(pid, signal) |