housekeep(fastapi): simplify aurweb.spawn.stop()

Signed-off-by: Kevin Morris <kevr@0cost.org>
This commit is contained in:
Kevin Morris 2021-11-20 13:31:09 -08:00
parent 0b5d088016
commit 191198ca41
No known key found for this signature in database
GPG key ID: F7E46DED420788F3

View file

@ -18,6 +18,8 @@ import tempfile
import time import time
import urllib import urllib
from typing import Iterable, List
import aurweb.config import aurweb.config
import aurweb.schema import aurweb.schema
@ -127,17 +129,15 @@ def start():
spawn_child(["nginx", "-p", temporary_dir, "-c", generate_nginx_config()]) spawn_child(["nginx", "-p", temporary_dir, "-c", generate_nginx_config()])
def stop(): def _kill_children(children: Iterable, exceptions: List[Exception] = []) \
-> List[Exception]:
""" """
Stop all the child processes. Kill each process found in `children`.
If an exception occurs during the process, the process continues anyway :param children: Iterable of child processes
because we dont want to leave runaway processes around, and all the :param exceptions: Exception memo
exceptions are finally raised as a single ProcessExceptions. :return: `exceptions`
""" """
global children
atexit.unregister(stop)
exceptions = []
for p in children: for p in children:
try: try:
p.terminate() p.terminate()
@ -145,6 +145,18 @@ def stop():
print(f":: Sent SIGTERM to {p.args}", file=sys.stderr) print(f":: Sent SIGTERM to {p.args}", file=sys.stderr)
except Exception as e: except Exception as e:
exceptions.append(e) exceptions.append(e)
return exceptions
def _wait_for_children(children: Iterable, exceptions: List[Exception] = []) \
-> List[Exception]:
"""
Wait for each process to end found in `children`.
:param children: Iterable of child processes
:param exceptions: Exception memo
:return: `exceptions`
"""
for p in children: for p in children:
try: try:
rc = p.wait() rc = p.wait()
@ -154,6 +166,24 @@ def stop():
raise Exception(f"Process {p.args} exited with {rc}") raise Exception(f"Process {p.args} exited with {rc}")
except Exception as e: except Exception as e:
exceptions.append(e) exceptions.append(e)
return exceptions
def stop() -> None:
"""
Stop all the child processes.
If an exception occurs during the process, the process continues anyway
because we dont want to leave runaway processes around, and all the
exceptions are finally raised as a single ProcessExceptions.
:raises: ProcessException
:return: None
"""
global children
atexit.unregister(stop)
exceptions = _kill_children(children)
exceptions = _wait_for_children(children, exceptions)
children = [] children = []
if exceptions: if exceptions:
raise ProcessExceptions("Errors terminating the child processes:", raise ProcessExceptions("Errors terminating the child processes:",