Skip to content

Commit

Permalink
Drop homebrew daemonize.
Browse files Browse the repository at this point in the history
  • Loading branch information
brainbot-devops committed Aug 14, 2019
1 parent 910a9cb commit fb76663
Showing 1 changed file with 0 additions and 85 deletions.
85 changes: 0 additions & 85 deletions scenario_player/services/utils/factories.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,91 +53,6 @@ def construct_flask_app(
return app


def daemonize(pidfile: pathlib.Path, *, stdin="/dev/null", stdout="/dev/null", stderr="/dev/null"):
"""Daemonize the currently run script, using a double fork.
Any commands executed after this function is called will be run in the daemonized process.
Usage::
if __name__ == "__main__":
daemonize("/tmp/my_daemon.pid")
my_func_to_run_daemonized()
"""
if pidfile.exists():
raise RuntimeError("Already running")

# First fork (detaches from parent)
try:
if os.fork() > 0:
raise SystemExit(0) # Parent exit
except OSError:
raise RuntimeError("fork #1 failed.")

os.chdir("/")
os.umask(0)
os.setsid()
# Second fork (relinquish session leadership)
try:
if os.fork() > 0:
raise SystemExit(0)
except OSError:
raise RuntimeError("fork #2 failed.")

# Flush I/O buffers
sys.stdout.flush()
sys.stderr.flush()

# Replace file descriptors for stdin, stdout, and stderr
with open(stdin, "rb", 0) as f:
os.dup2(f.fileno(), sys.stdin.fileno())
with open(stdout, "ab", 0) as f:
os.dup2(f.fileno(), sys.stdout.fileno())
with open(stderr, "ab", 0) as f:
os.dup2(f.fileno(), sys.stderr.fileno())

# Write the PID file
pidfile.write_text(str(os.getpid()))

# Arrange to have the PID file removed on exit/signal
atexit.register(lambda: pidfile.unlink())

# Signal handler for termination (required)
def sigterm_handler(signo, frame):
raise SystemExit(1)

signal.signal(signal.SIGTERM, sigterm_handler)


def start_daemon(pid_file: pathlib.Path, func, *args, stdout=None, stderr=None, **kwargs):
"""Run a function as a daemon process.
Takes care of redirecting stdout and stderr to a logfile, instead of /dev/null.
Any additional args and kwargs are passed to `func`.
"""
stdout = stdout or "/var/log/scenario-player/{func.__name__}.stdout"
stderr = stderr or "/var/log/scenario-player/{func.__name__}.stderr"
try:
daemonize(pid_file, stdout=stdout, stderr=stderr)
except RuntimeError as e:
print(e, file=sys.stderr)
raise SystemExit(1)

func(*args, **kwargs)


def stop_daemon(pid_file: pathlib.Path):
"""Stop the daemon with the given `pid_file`."""
if pid_file.exists():
pid = int(pid_file.read_text())
os.kill(pid, signal.SIGTERM)
else:
print("Not running", file=sys.stderr)
raise SystemExit(1)


def default_service_daemon_cli():
"""Create an :class:`argparse.ArgumentParser` with a minimalistic set of CLI options.
Expand Down

0 comments on commit fb76663

Please sign in to comment.