"""Run the controller, passwordless LAN panel and SSH export in one container.""" import argparse import os from pathlib import Path import signal import subprocess import sys import threading import time import urllib.request import yaml import homegate as h BASE = Path(__file__).resolve().parent def runtime_environment(source): env = dict(source) defaults = { "HOMEGATE_CONFIG": "/config/services.yaml", "HOMEGATE_STATE": "/data", "HOMEGATE_CONTROL": "/control", "HOMEGATE_CONNECTIONS": "/config/connections.json", "HOMEGATE_MANAGED_UI": "1", "UI_AUTH_MODE": "none", "UI_LISTEN_HOST": "0.0.0.0", "UI_LISTEN_PORT": "8081", "PYTHONDONTWRITEBYTECODE": "1", "PYTHONUNBUFFERED": "1", } for key, value in defaults.items(): env.setdefault(key, value) return env def prepare(env): for directory in (Path(env["HOMEGATE_CONFIG"]).parent, Path(env["HOMEGATE_STATE"]), Path(env["HOMEGATE_CONTROL"])): directory.mkdir(parents=True, exist_ok=True) def configured(env): return all(Path(env[key]).is_file() for key in ("HOMEGATE_CONFIG", "HOMEGATE_CONNECTIONS")) def supervise(commands, env, deferred=()): stopped = threading.Event() previous = {sig: signal.signal(sig, lambda *_: stopped.set()) for sig in (signal.SIGTERM, signal.SIGINT)} children = [] try: for command in commands: if stopped.is_set(): return 0 children.append(subprocess.Popen(command, env=env)) while not stopped.wait(0.25): if deferred and configured(env): for command in deferred: children.append(subprocess.Popen(command, env=env)) deferred = () for child in children: if child.poll() is not None: print(f"Homegate process exited with status {child.returncode}; restarting the container", flush=True) return 1 return 0 finally: for child in children: if child.poll() is None: child.terminate() deadline = time.monotonic() + 8 for child in children: try: child.wait(timeout=max(0, deadline - time.monotonic())) except subprocess.TimeoutExpired: child.kill() child.wait() for sig, handler in previous.items(): signal.signal(sig, handler) def health(env): opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) requests = ["http://127.0.0.1:8081/healthz"] if configured(env): requests.append("http://127.0.0.1:8080/healthz") for request in requests: with opener.open(request, timeout=3) as response: response.read() return 0 def main(): os.umask(0o077) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("command", nargs="?", default="all", choices=("all", "once", "validate", "fingerprint", "rotate-ca", "ssh-config")) parser.add_argument("--health", action="store_true") args = parser.parse_args() env = runtime_environment(os.environ) if args.health: return health(env) prepare(env) controller = [sys.executable, str(BASE / "homegate.py")] if args.command != "all": h.require(configured(env), "Complete the first-run setup in the web panel") return subprocess.call(controller + [args.command], env=env) return supervise([[sys.executable, str(BASE / "homegate_ui.py")]], env, deferred=[controller + ["run"], controller + ["serve"]]) if __name__ == "__main__": try: sys.exit(main()) except (h.Error, OSError, ValueError, TypeError, KeyError, yaml.YAMLError) as exc: print(f"Homegate: {exc}", file=sys.stderr) sys.exit(1)