128 lines
4.3 KiB
Python
128 lines
4.3 KiB
Python
"""
|
|
A guest's own root domain at the zipgo host's public edge.
|
|
|
|
Setting a root domain on a guest's card (Settings → Users → <guest> → Web
|
|
address) is only half of it: the zipgo host's Traefik must pass the domain
|
|
through, and zipgo must manage its certificates. The host sidecar runs the
|
|
homelab's ``edge-domain`` tool for that (``/edge-domain``):
|
|
|
|
* :func:`setup_later` — on save, in a thread: ``add`` routes the domain and,
|
|
once its DNS points at the lab, makes its folder and restarts zipgo.
|
|
Idempotent; until the DNS is there it only routes — so it tries again every
|
|
:data:`RETRY_S` until the domain is ready (a fresh domain's delegation can
|
|
take an hour to reach the public resolvers), for up to :data:`GIVE_UP_S`
|
|
or until no guest has that domain any more. A backend restart drops the
|
|
retries; the card's *Check again* is the same call.
|
|
* :func:`status` — where it stands (``dns``, ``routed``, ``folder``,
|
|
``https``, ``ready``), for the card. Read-only.
|
|
* :func:`setup` — the card's *Check again*: ``add`` once more, which finishes
|
|
the job when the DNS has propagated since.
|
|
|
|
The last answer per domain is kept in memory (``checkedAt``) so the card
|
|
shows it at once; a ``users`` event tells the page when a setup ran.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import datetime
|
|
import logging
|
|
import threading
|
|
import time
|
|
|
|
from fastapi import HTTPException
|
|
|
|
log = logging.getLogger("ai-agent.users.edge")
|
|
|
|
# `add` can restart zipgo; the sidecar's own cap is 180 s.
|
|
SETUP_TIMEOUT_S = 200
|
|
STATUS_TIMEOUT_S = 90
|
|
RETRY_S = 600
|
|
GIVE_UP_S = 48 * 3600
|
|
|
|
_lock = threading.Lock()
|
|
_last: dict[str, dict] = {}
|
|
_running: set[str] = set()
|
|
_retrying: set[str] = set()
|
|
|
|
|
|
def _now_iso() -> str:
|
|
return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
|
|
|
|
def _call(deps, domain: str, action: str) -> dict:
|
|
from runs.sidecar_client import _sidecar_call
|
|
try:
|
|
out = _sidecar_call(deps, "/edge-domain", {"domain": domain, "action": action},
|
|
timeout=SETUP_TIMEOUT_S if action == "add" else STATUS_TIMEOUT_S)
|
|
except HTTPException as e:
|
|
d = e.detail
|
|
out = {"ok": False, "error": d.get("message") if isinstance(d, dict) else str(d)}
|
|
res = {"domain": domain, **(out.get("result") or {}), "checkedAt": _now_iso(),
|
|
"error": None if out.get("ok") else (out.get("error") or "the host didn't answer")}
|
|
res.setdefault("ready", False)
|
|
with _lock:
|
|
_last[domain] = res
|
|
return res
|
|
|
|
|
|
def last(domain: str) -> dict | None:
|
|
with _lock:
|
|
r = _last.get(domain)
|
|
return dict(r) if r else None
|
|
|
|
|
|
def status(deps, domain: str) -> dict:
|
|
return _call(deps, domain, "status")
|
|
|
|
|
|
def setup(deps, domain: str) -> dict:
|
|
with _lock:
|
|
if domain in _running:
|
|
raise HTTPException(409, f"{domain} is being set up already")
|
|
_running.add(domain)
|
|
try:
|
|
res = _call(deps, domain, "add")
|
|
finally:
|
|
with _lock:
|
|
_running.discard(domain)
|
|
deps.hub.publish({"type": "users"})
|
|
return res
|
|
|
|
|
|
def _wanted(deps, domain: str) -> bool:
|
|
return any((u.get("domain") or "") == domain for u in deps.users.all())
|
|
|
|
|
|
def setup_later(deps, domain: str) -> None:
|
|
""":func:`setup` on a thread — a save shouldn't wait on DNS lookups and
|
|
a zipgo restart — then again every :data:`RETRY_S` until it's ready."""
|
|
if not domain:
|
|
return
|
|
with _lock:
|
|
if domain in _retrying:
|
|
return # its retries are on already
|
|
_retrying.add(domain)
|
|
|
|
def run():
|
|
start = time.monotonic()
|
|
try:
|
|
while True:
|
|
try:
|
|
if setup(deps, domain).get("ready"):
|
|
return
|
|
except HTTPException:
|
|
pass # a *Check again* is running: try on the next round
|
|
except Exception:
|
|
log.exception("setting up %s at the edge failed", domain)
|
|
if time.monotonic() - start > GIVE_UP_S:
|
|
log.warning("%s still isn't ready at the edge: giving up", domain)
|
|
return
|
|
time.sleep(RETRY_S)
|
|
if not _wanted(deps, domain):
|
|
return
|
|
finally:
|
|
with _lock:
|
|
_retrying.discard(domain)
|
|
|
|
threading.Thread(target=run, daemon=True, name=f"edge-domain-{domain}").start()
|