From 62a9cf28f5aaca8a1dfc5d9484e7f3a5352d13ac Mon Sep 17 00:00:00 2001 From: rainyy21 Date: Wed, 11 Nov 2026 16:36:54 -0500 Subject: [PATCH] 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 --- app/watcher.py | 53 ++++++++++++++++++++++++++++++++---- app/web/app.py | 12 ++++++-- app/web/static/style.css | 7 +++++ app/web/templates/index.html | 21 +++++++++++++- 4 files changed, 83 insertions(+), 10 deletions(-) diff --git a/app/watcher.py b/app/watcher.py index 91b7cf9..e7acc04 100644 --- a/app/watcher.py +++ b/app/watcher.py @@ -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})") diff --git a/app/web/app.py b/app/web/app.py index 856781e..b44f677 100644 --- a/app/web/app.py +++ b/app/web/app.py @@ -25,7 +25,8 @@ from flask import (Flask, abort, flash, jsonify, redirect, render_template, # share settings and rules with the watcher (app/watcher.py, one folder up) sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) from watcher import (CHECK_INTERVAL, CONFIG_PATH, LOCAL_DIR, # noqa: E402 - REQUEST_DIR, STACKS_DIR, STATE_PATH, normalize, queue_request) + REQUEST_DIR, SELF_STATUS_PATH, STACKS_DIR, STATE_PATH, normalize, + queue_request) # ---------- settings ---------- @@ -288,7 +289,11 @@ def index(): next_in = max(0, int(CHECK_INTERVAL - since)) stale = since > CHECK_INTERVAL * 2 + 60 - return render_template("index.html", rows=rows, counts=counts, total=len(rows), + me = load_json(SELF_STATUS_PATH, None) # the watcher itself (see check_self in watcher.py) + if not isinstance(me, dict): + me = None + + return render_template("index.html", rows=rows, counts=counts, total=len(rows), me=me, next_in=next_in, stale=stale, last_round=last_round, interval=CHECK_INTERVAL, token_envs=TOKEN_ENVS) @@ -373,7 +378,8 @@ def version(): except OSError: return 0 pending = pending_requests() - raw = f"{mtime(STATE_PATH)}|{mtime(Path(CONFIG_PATH))}|{sorted(pending.items())}" + raw = (f"{mtime(STATE_PATH)}|{mtime(SELF_STATUS_PATH)}|{mtime(Path(CONFIG_PATH))}|" + f"{sorted(pending.items())}") return jsonify(version=hashlib.sha1(raw.encode()).hexdigest()[:16], busy=bool(pending)) diff --git a/app/web/static/style.css b/app/web/static/style.css index b3067e7..c6f8bd8 100644 --- a/app/web/static/style.css +++ b/app/web/static/style.css @@ -331,3 +331,10 @@ span.commit:hover { text-decoration: none; } @keyframes blink { 50% { opacity: 0; } } .editor-loading { padding: 16px; color: var(--muted); } @media (prefers-reduced-motion: reduce) { .cursor { animation: none; } } + +/* the watcher's own row (self-update, read-only) */ +.status.warn { color: var(--warn); } +.self-tag { + margin-left: 8px; padding: 1px 6px; border: 1px solid var(--muted); border-radius: 4px; + color: var(--muted); font-size: 11px; white-space: nowrap; +} diff --git a/app/web/templates/index.html b/app/web/templates/index.html index 4aedd11..c5b989f 100644 --- a/app/web/templates/index.html +++ b/app/web/templates/index.html @@ -29,7 +29,7 @@
- {% if rows %} + {% if rows or me %} @@ -38,6 +38,25 @@ + {% if me %} + {# the watcher itself: updates itself from its own repo, so no deploy/stop/remove here #} + {% set cls = {'ok': 'ok', 'updating': 'busy', 'held': 'warn', 'error': 'error'}.get(me.status, 'new') %} + {% set label = {'ok': 'up to date', 'updating': 'updating', 'held': 'held'}.get(me.status, me.status) %} + + + + + + + + + {% if me.note and me.status in ('held', 'error') %} + + {% endif %} + {% endif %} {% for r in rows %} {% set warn = r.missing_env and r.status != 'error' and not r.busy %}
{{ me.name }}this watcher{{ label }} + {% if me.running %}{{ me.running[:7] }}{% endif %} + {% if me.latest and me.latest != me.running %} โ†’ {{ me.latest[:7] }}{% endif %} + {{ me.last_check|ago }}{{ me.started|ago }}auto ยท {{ me.remote }}/{{ me.branch }}
โ””โ”€ {{ me.note }}