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:
+47
-6
@@ -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_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
|
SELF_REMOTE = os.environ.get("SELF_REMOTE", "origin") # git remote in the checkout to update from
|
||||||
UPDATER = "gitops-watcher-updater"
|
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())
|
# 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
|
# host_dir: where the checkout is on the host; image: our own image
|
||||||
@@ -329,6 +332,29 @@ UPDATER = "gitops-watcher-updater"
|
|||||||
SELF: dict = {}
|
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:
|
def git_self(*args, timeout: float = 10) -> str:
|
||||||
return run(["git", "-C", str(SELF_DIR), *args], timeout=timeout)
|
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["host_dir"] = labels.get("com.docker.compose.project.working_dir")
|
||||||
SELF["image"] = info.get("Config", {}).get("Image")
|
SELF["image"] = info.get("Config", {}).get("Image")
|
||||||
if not SELF_UPDATE:
|
if not SELF_UPDATE:
|
||||||
|
SELF_STATUS_PATH.unlink(missing_ok=True) # don't show a stale row
|
||||||
return
|
return
|
||||||
if not (SELF_DIR / ".git").exists() or not SELF["host_dir"]:
|
if not (SELF_DIR / ".git").exists() or not SELF["host_dir"]:
|
||||||
log("self", f"self-update off: checkout not mounted at {SELF_DIR}")
|
log("self", f"self-update off: checkout not mounted at {SELF_DIR}")
|
||||||
return
|
return
|
||||||
try:
|
try:
|
||||||
SELF["running"] = git_self("rev-parse", "HEAD")
|
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:
|
except Exception as e:
|
||||||
log("self", f"self-update off: {e}")
|
log("self", f"self-update off: {e}")
|
||||||
return
|
return
|
||||||
@@ -369,10 +399,13 @@ def check_self() -> None:
|
|||||||
if not SELF.get("running"):
|
if not SELF.get("running"):
|
||||||
return
|
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:
|
if SELF.get("note") != msg:
|
||||||
log("self", msg)
|
log("self", msg)
|
||||||
SELF["note"] = msg
|
SELF["note"] = msg
|
||||||
|
save_self_status(status, msg, remote)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
branch = git_self("rev-parse", "--abbrev-ref", "HEAD")
|
branch = git_self("rev-parse", "--abbrev-ref", "HEAD")
|
||||||
@@ -380,10 +413,16 @@ def check_self() -> None:
|
|||||||
local = git_self("rev-parse", "HEAD")
|
local = git_self("rev-parse", "HEAD")
|
||||||
dirty = git_self("status", "--porcelain", "--untracked-files=no")
|
dirty = git_self("status", "--porcelain", "--untracked-files=no")
|
||||||
except Exception as e:
|
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
|
return
|
||||||
if remote == SELF["running"] or remote == SELF.get("tried"):
|
|
||||||
return # up to date, or this commit already failed once
|
|
||||||
if dirty:
|
if dirty:
|
||||||
note(f"{SELF_REMOTE}/{branch} has {remote[:7]}, but the checkout has uncommitted changes: not updating")
|
note(f"{SELF_REMOTE}/{branch} has {remote[:7]}, but the checkout has uncommitted changes: not updating")
|
||||||
return
|
return
|
||||||
@@ -398,7 +437,8 @@ def check_self() -> None:
|
|||||||
try:
|
try:
|
||||||
state = run(["docker", "inspect", "-f", "{{.State.Running}}", UPDATER])
|
state = run(["docker", "inspect", "-f", "{{.State.Running}}", UPDATER])
|
||||||
if state == "true":
|
if state == "true":
|
||||||
return # an update is already running
|
save_self_status("updating", f"updating to {remote[:7]}", remote)
|
||||||
|
return
|
||||||
run(["docker", "rm", UPDATER])
|
run(["docker", "rm", UPDATER])
|
||||||
except RuntimeError:
|
except RuntimeError:
|
||||||
pass # no old updater
|
pass # no old updater
|
||||||
@@ -419,10 +459,11 @@ def check_self() -> None:
|
|||||||
"--entrypoint", "sh", SELF["image"], "-c", script,
|
"--entrypoint", "sh", SELF["image"], "-c", script,
|
||||||
], timeout=60)
|
], timeout=60)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
note(f"can't start the updater: {e}")
|
note(f"can't start the updater: {e}", "error")
|
||||||
return
|
return
|
||||||
SELF["tried"] = remote
|
SELF["tried"] = remote
|
||||||
SELF["note"] = None
|
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 "
|
log("self", f"updating to {remote[:7]}, the watcher restarts in a moment "
|
||||||
f"(progress: docker logs -f {UPDATER})")
|
f"(progress: docker logs -f {UPDATER})")
|
||||||
|
|
||||||
|
|||||||
+9
-3
@@ -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)
|
# share settings and rules with the watcher (app/watcher.py, one folder up)
|
||||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
from watcher import (CHECK_INTERVAL, CONFIG_PATH, LOCAL_DIR, # noqa: E402
|
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 ----------
|
# ---------- settings ----------
|
||||||
|
|
||||||
@@ -288,7 +289,11 @@ def index():
|
|||||||
next_in = max(0, int(CHECK_INTERVAL - since))
|
next_in = max(0, int(CHECK_INTERVAL - since))
|
||||||
stale = since > CHECK_INTERVAL * 2 + 60
|
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,
|
next_in=next_in, stale=stale, last_round=last_round,
|
||||||
interval=CHECK_INTERVAL, token_envs=TOKEN_ENVS)
|
interval=CHECK_INTERVAL, token_envs=TOKEN_ENVS)
|
||||||
|
|
||||||
@@ -373,7 +378,8 @@ def version():
|
|||||||
except OSError:
|
except OSError:
|
||||||
return 0
|
return 0
|
||||||
pending = pending_requests()
|
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))
|
return jsonify(version=hashlib.sha1(raw.encode()).hexdigest()[:16], busy=bool(pending))
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -331,3 +331,10 @@ span.commit:hover { text-decoration: none; }
|
|||||||
@keyframes blink { 50% { opacity: 0; } }
|
@keyframes blink { 50% { opacity: 0; } }
|
||||||
.editor-loading { padding: 16px; color: var(--muted); }
|
.editor-loading { padding: 16px; color: var(--muted); }
|
||||||
@media (prefers-reduced-motion: reduce) { .cursor { animation: none; } }
|
@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;
|
||||||
|
}
|
||||||
|
|||||||
@@ -29,7 +29,7 @@
|
|||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section class="panel">
|
<section class="panel">
|
||||||
{% if rows %}
|
{% if rows or me %}
|
||||||
<table>
|
<table>
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
@@ -38,6 +38,25 @@
|
|||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
|
{% 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) %}
|
||||||
|
<tr class="repo self-row {{ 'has-error' if me.status == 'error' }} {{ 'has-warn' if me.status == 'held' }}">
|
||||||
|
<td class="name-cell"><span class="name" title="{{ me.url }}">{{ me.name }}</span><span class="self-tag">this watcher</span></td>
|
||||||
|
<td data-label="status"><span class="status {{ cls }}"><span class="dot {{ cls }}"></span>{{ label }}</span></td>
|
||||||
|
<td data-label="commit">
|
||||||
|
{% if me.running %}<span class="commit" title="running {{ me.running }}">{{ me.running[:7] }}</span>{% endif %}
|
||||||
|
{% if me.latest and me.latest != me.running %}<span class="time"> → {{ me.latest[:7] }}</span>{% endif %}
|
||||||
|
</td>
|
||||||
|
<td data-label="last check"><span class="time" title="{{ me.last_check|pretty }}">{{ me.last_check|ago }}</span></td>
|
||||||
|
<td data-label="last deploy"><span class="time" title="started {{ me.started|pretty }}">{{ me.started|ago }}</span></td>
|
||||||
|
<td class="actions-cell"><span class="time" title="push to {{ me.remote }}/{{ me.branch }} and it pulls + rebuilds itself">auto · {{ me.remote }}/{{ me.branch }}</span></td>
|
||||||
|
</tr>
|
||||||
|
{% if me.note and me.status in ('held', 'error') %}
|
||||||
|
<tr class="{{ 'error-row' if me.status == 'error' else 'warn-row' }}"><td colspan="6"><span class="tree">└─ </span>{{ me.note }}</td></tr>
|
||||||
|
{% endif %}
|
||||||
|
{% endif %}
|
||||||
{% for r in rows %}
|
{% for r in rows %}
|
||||||
{% set warn = r.missing_env and r.status != 'error' and not r.busy %}
|
{% set warn = r.missing_env and r.status != 'error' and not r.busy %}
|
||||||
<tr class="repo {{ 'has-error' if r.status == 'error' and not r.busy }} {{ 'is-paused' if r.status == 'paused' }} {{ 'has-warn' if warn }}">
|
<tr class="repo {{ 'has-error' if r.status == 'error' and not r.busy }} {{ 'is-paused' if r.status == 'paused' }} {{ 'has-warn' if warn }}">
|
||||||
|
|||||||
Reference in New Issue
Block a user