Show the watcher itself as a read-only row on the dashboard

The watcher writes its self-update status (running vs latest commit,
up to date / updating / held / error) to data/self.json, kept out of
state.json so the removed-stack cleanup never touches it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
rainyy21
2026-11-11 16:36:54 -05:00
parent a54c625d66
commit 62a9cf28f5
4 changed files with 83 additions and 10 deletions
+47 -6
View File
@@ -322,6 +322,9 @@ SELF_UPDATE = os.environ.get("SELF_UPDATE", "").lower() in ("1", "true", "yes")
SELF_DIR = Path(os.environ.get("SELF_DIR", "/self")) # the checkout, mounted read-only
SELF_REMOTE = os.environ.get("SELF_REMOTE", "origin") # git remote in the checkout to update from
UPDATER = "gitops-watcher-updater"
# what the dashboard shows for the watcher itself. Not in state.json on purpose:
# everything in there that isn't in repos.yml gets stopped
SELF_STATUS_PATH = STATE_PATH.parent / "self.json"
# project: compose project we run in (never managed as a repo, see main())
# host_dir: where the checkout is on the host; image: our own image
@@ -329,6 +332,29 @@ UPDATER = "gitops-watcher-updater"
SELF: dict = {}
def save_self_status(status: str, note: str | None = None, remote: str | None = None) -> None:
"""status: ok (up to date) | updating | held (won't update, see note) | error"""
url = SELF.get("url") or ""
data = {
"name": url.rstrip("/").rsplit("/", 1)[-1].removesuffix(".git") or "watcher",
"url": redact(url),
"remote": SELF_REMOTE,
"branch": SELF.get("branch"),
"running": SELF.get("running"),
"latest": remote,
"status": status,
"note": note,
"started": SELF.get("started"),
"last_check": datetime.now().isoformat(timespec="seconds"),
}
try:
tmp = SELF_STATUS_PATH.with_suffix(".tmp")
tmp.write_text(json.dumps(data, indent=2))
tmp.replace(SELF_STATUS_PATH)
except OSError as e:
log("self", f"can't save {SELF_STATUS_PATH}: {e}")
def git_self(*args, timeout: float = 10) -> str:
return run(["git", "-C", str(SELF_DIR), *args], timeout=timeout)
@@ -345,12 +371,16 @@ def detect_self() -> None:
SELF["host_dir"] = labels.get("com.docker.compose.project.working_dir")
SELF["image"] = info.get("Config", {}).get("Image")
if not SELF_UPDATE:
SELF_STATUS_PATH.unlink(missing_ok=True) # don't show a stale row
return
if not (SELF_DIR / ".git").exists() or not SELF["host_dir"]:
log("self", f"self-update off: checkout not mounted at {SELF_DIR}")
return
try:
SELF["running"] = git_self("rev-parse", "HEAD")
SELF["branch"] = git_self("rev-parse", "--abbrev-ref", "HEAD")
SELF["url"] = git_self("remote", "get-url", SELF_REMOTE)
SELF["started"] = datetime.now().isoformat(timespec="seconds")
except Exception as e:
log("self", f"self-update off: {e}")
return
@@ -369,10 +399,13 @@ def check_self() -> None:
if not SELF.get("running"):
return
def note(msg: str) -> None: # log each skip reason once, not every round
remote = None
def note(msg: str, status: str = "held") -> None: # log each reason once, not every round
if SELF.get("note") != msg:
log("self", msg)
SELF["note"] = msg
save_self_status(status, msg, remote)
try:
branch = git_self("rev-parse", "--abbrev-ref", "HEAD")
@@ -380,10 +413,16 @@ def check_self() -> None:
local = git_self("rev-parse", "HEAD")
dirty = git_self("status", "--porcelain", "--untracked-files=no")
except Exception as e:
note(f"can't check for updates: {e}")
note(f"can't check for updates: {e}", "error")
return
if remote == SELF["running"]:
SELF["note"] = None
save_self_status("ok", None, remote)
return
if remote == SELF.get("tried"): # this commit already failed once
note(f"update to {remote[:7]} failed, waiting for a newer commit "
f"(docker logs {UPDATER})", "error")
return
if remote == SELF["running"] or remote == SELF.get("tried"):
return # up to date, or this commit already failed once
if dirty:
note(f"{SELF_REMOTE}/{branch} has {remote[:7]}, but the checkout has uncommitted changes: not updating")
return
@@ -398,7 +437,8 @@ def check_self() -> None:
try:
state = run(["docker", "inspect", "-f", "{{.State.Running}}", UPDATER])
if state == "true":
return # an update is already running
save_self_status("updating", f"updating to {remote[:7]}", remote)
return
run(["docker", "rm", UPDATER])
except RuntimeError:
pass # no old updater
@@ -419,10 +459,11 @@ def check_self() -> None:
"--entrypoint", "sh", SELF["image"], "-c", script,
], timeout=60)
except Exception as e:
note(f"can't start the updater: {e}")
note(f"can't start the updater: {e}", "error")
return
SELF["tried"] = remote
SELF["note"] = None
save_self_status("updating", f"updating to {remote[:7]}, restarting in a moment", remote)
log("self", f"updating to {remote[:7]}, the watcher restarts in a moment "
f"(progress: docker logs -f {UPDATER})")