Files

143 lines
5.5 KiB
Python

"""
Keeping workers on the hub's version — so nobody runs ``--update`` on a Mac.
The hub knows the commit it was deployed from: ``deploy.sh`` writes it to
``DEPLOYED_COMMIT_FILE`` (``/data/deployed-commit``) on every successful or
no-op deploy. A worker's ``/health`` says the commit *its* checkout is on and
whether it can update itself (``sidecar/selfupdate.py``). Each liveness probe
compares the two (``update_status``) and, when the worker is behind,
``maybe_update`` calls its ``POST /update {commit}`` — the worker fetches that
commit from Gitea, restarts only if its side changed, and rolls back if the new
version doesn't come up. The hub never ships code; it only says which commit.
A worker *ahead* of the hub (someone ran ``ai-agent-worker update`` on it,
which follows main) is left alone: the ancestry check runs against the source
checkout mounted at ``AI_AGENT_SRC``. A target that failed is retried after
``FAILED_RETRY_S``; any other attempt after ``RETRY_S`` (a Mac that slept
mid-update, a commit not pushed yet). ``autoUpdate: false`` on the record turns
the automatic part off — *Update now* (``POST /api/workers/{id}/update``) still
works.
"""
from __future__ import annotations
import os
import re
import subprocess
import time
from fastapi import HTTPException
DEPLOYED_COMMIT_FILE = os.environ.get("DEPLOYED_COMMIT_FILE",
"/data/deployed-commit")
SRC_REPO = os.environ.get("AI_AGENT_SRC", "/workspace/projects/ai-agent")
RETRY_S = 30 * 60
FAILED_RETRY_S = 6 * 3600
_SHA_RE = re.compile(r"^[0-9a-f]{40}$")
# The statuses the Settings page shows (and the auto-update acts on).
CURRENT, OUTDATED, AHEAD, UPDATING, FAILED, UNSUPPORTED, UNKNOWN = (
"current", "outdated", "ahead", "updating", "failed", "unsupported",
"unknown")
_hub: list = [None, None] # [mtime, sha]
_ancestry: dict[tuple[str, str], bool | None] = {}
_attempts: dict[str, tuple[str, float]] = {} # worker id → (target, when)
def hub_commit() -> str | None:
"""The commit this hub was deployed from (None when no deploy wrote it)."""
try:
m = os.stat(DEPLOYED_COMMIT_FILE).st_mtime
except OSError:
return None
if _hub[0] != m:
try:
sha = open(DEPLOYED_COMMIT_FILE, encoding="utf-8").read().strip().lower()
except OSError:
sha = ""
_hub[:] = [m, sha if _SHA_RE.match(sha) else None]
return _hub[1]
def same(a: str | None, b: str | None) -> bool:
return bool(a and b) and (a.startswith(b) or b.startswith(a))
def is_ancestor(a: str, b: str) -> bool | None:
"""Is commit ``a`` an ancestor of ``b``? None when the source checkout
can't tell (not mounted, a commit it doesn't have)."""
key = (a, b)
if key not in _ancestry:
try:
rc = subprocess.run(["git", "-C", SRC_REPO, "merge-base",
"--is-ancestor", a, b],
capture_output=True, timeout=5).returncode
_ancestry[key] = {0: True, 1: False}.get(rc)
except (OSError, subprocess.SubprocessError):
_ancestry[key] = None
return _ancestry[key]
def update_status(w: dict, st: dict, hub: str | None = None) -> str:
"""Where a worker stands against the hub's commit."""
hub = hub if hub is not None else hub_commit()
commit = w.get("commit")
upd = st.get("update") or {}
if not commit:
# Online without a commit in /health: an install from before
# auto-update — it needs one `install-macos.sh --update` by hand.
return UNSUPPORTED if st.get("status") == "online" else UNKNOWN
if hub and same(commit, hub):
return CURRENT
if upd.get("state") == "updating":
return UPDATING
if not hub:
return UNKNOWN
if is_ancestor(hub, commit):
return AHEAD
if not w.get("updatable"):
return UNSUPPORTED
if upd.get("state") in ("failed", "rolledback") and same(upd.get("to"), hub):
return FAILED
return OUTDATED
def trigger(store, w: dict, sha: str) -> dict:
"""Ask the worker to move to ``sha``. Raises the sidecar's HTTPException."""
from .store import _now_iso, sidecar_request
_attempts[w["id"]] = (sha, time.time())
try:
out = sidecar_request(w["url"], w["token"], "/update", {"commit": sha},
timeout=10, label=f"worker {w.get('name') or w['id']}")
except HTTPException as e:
d = e.detail if isinstance(e.detail, dict) else {"message": str(e.detail)}
store.set_status(w["id"], updateError=d.get("message"))
raise
store.set_status(w["id"], updateError=None)
if out.get("started"):
# Until the worker's own update.json says so on the next probe.
store.set_status(w["id"], update={
"state": "updating", "from": w.get("commit"), "to": sha,
"startedAt": _now_iso(), "finishedAt": None, "error": None})
return out
def maybe_update(store, w: dict) -> bool:
"""The automatic half: True when an update was requested."""
if w.get("autoUpdate") is False or not store.online(w["id"]):
return False
hub = hub_commit()
status = update_status(w, store.status(w["id"]), hub)
if status not in (OUTDATED, FAILED):
return False
last = _attempts.get(w["id"])
wait = FAILED_RETRY_S if status == FAILED else RETRY_S
if last and last[0] == hub and time.time() - last[1] < wait:
return False
try:
trigger(store, w, hub)
except HTTPException:
return False
return True