Move web app up a level, live dashboard refresh, self-update

- web: move app/web/web/* to app/web/, drop the old standalone compose
  file and watcher_additions.py (merged into watcher.py)
- web: /api/version fingerprint of state, config and queued requests;
  the page polls it every 2s and reloads as soon as the watcher acts
- watcher: self-update. When its own branch has a new commit and the
  checkout is clean, start a one-off gitops-watcher-updater container
  that runs git pull + docker compose up -d --build on the host checkout
- watcher: refuse to deploy/stop/remove its own compose project, which
  used to stop the watcher itself mid-way

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
rainyy21
2026-11-11 16:17:05 -05:00
parent 999f852805
commit 5f70813202
13 changed files with 533 additions and 386 deletions
+55 -35
View File
@@ -14,7 +14,7 @@ import json
import os
import re
import secrets
import time
import sys
from datetime import datetime
from pathlib import Path
@@ -22,14 +22,13 @@ import yaml
from flask import (Flask, abort, flash, jsonify, redirect, render_template,
request, session, url_for)
# ---------- settings (same env vars as the watcher) ----------
# 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)
# ---------- settings ----------
STATE_PATH = Path(os.environ.get("STATE_PATH", "data/state.json"))
CONFIG_PATH = Path(os.environ.get("CONFIG_PATH", "repos.yml"))
STACKS_DIR = Path(os.environ.get("STACKS_DIR", "stacks"))
LOCAL_DIR = Path(os.environ.get("LOCAL_DIR", "data/local"))
REQUESTS_DIR = Path(os.environ.get("REQUESTS_DIR", "data/requests"))
CHECK_INTERVAL = int(os.environ.get("CHECK_INTERVAL", "300"))
TOKEN_ENVS = [t for t in os.environ.get("TOKEN_ENVS", "GITEA_TOKEN,GITHUB_TOKEN").split(",") if t]
WEBHOOK_SECRET = os.environ.get("WEBHOOK_SECRET", "") # empty = webhooks turned off
@@ -54,7 +53,7 @@ def load_json(path: Path, default):
def load_repos() -> list[dict]:
"""repos.yml entries with defaults filled in (same rules as the watcher's normalize)."""
"""repos.yml entries with defaults filled in, by the watcher's own normalize()."""
try:
config = yaml.safe_load(CONFIG_PATH.read_text()) or {}
except (OSError, yaml.YAMLError):
@@ -62,14 +61,24 @@ def load_repos() -> list[dict]:
defaults = config.get("defaults") or {}
repos = []
for raw in config.get("repos") or []:
if not isinstance(raw, dict) or not raw.get("name"):
continue
repo = {"branch": "main", "compose_file": "docker-compose.yml",
"pull_images": False, "paused": False, **defaults, **raw}
repos.append(repo)
try:
repos.append(normalize(raw, defaults))
except ValueError:
continue # the watcher skips (and logs) invalid entries too
return repos
COMPOSE_NAMES = ("compose.yaml", "compose.yml", "docker-compose.yaml", "docker-compose.yml")
def compose_file_of(repo: dict) -> str | None:
"""The compose file the watcher uses: the configured one, or what compose would auto-detect."""
if repo["compose_file"]:
return repo["compose_file"]
root = STACKS_DIR / repo["name"]
return next((n for n in COMPOSE_NAMES if (root / n).is_file()), None)
def get_repo(name: str) -> dict:
for repo in load_repos():
if repo["name"] == name:
@@ -80,8 +89,8 @@ def get_repo(name: str) -> dict:
def pending_requests() -> dict[str, str]:
"""{repo name: action} for requests the watcher hasn't processed yet."""
pending = {}
if REQUESTS_DIR.is_dir():
for f in sorted(REQUESTS_DIR.glob("*.json")):
if REQUEST_DIR.is_dir():
for f in sorted(REQUEST_DIR.glob("*.json")):
req = load_json(f, None)
if isinstance(req, dict) and req.get("repo"):
pending.setdefault(req["repo"], req.get("action", "?"))
@@ -99,13 +108,6 @@ def write_atomic(path: Path, text: str, mode: int | None = None) -> None:
os.replace(tmp, path)
def queue_request(action: str, repo: str, **extra) -> None:
req = {"action": action, "repo": repo,
"created": datetime.now().isoformat(timespec="seconds"), **extra}
name = f"{time.time_ns()}-{action}-{repo}.json"
write_atomic(REQUESTS_DIR / name, json.dumps(req, indent=2))
# ---------- files ----------
def safe_path(base: Path, filename: str) -> Path:
@@ -173,7 +175,7 @@ def git_files(repo: dict) -> list[str]:
and (not p.name.startswith(".") or p.name == ".env.example")
and p.stat().st_size <= MAX_FILE):
names.append(p.name)
compose = repo["compose_file"]
compose = compose_file_of(repo)
return sorted(names, key=lambda n: (n != compose, n.lower()))
@@ -320,8 +322,8 @@ def add_repo():
f = request.form
name = f.get("name", "").strip()
url = f.get("url", "").strip()
branch = f.get("branch", "").strip() or "main"
compose_file = f.get("compose_file", "").strip() or "docker-compose.yml"
branch = f.get("branch", "").strip() # empty = repos.yml default
compose_file = f.get("compose_file", "").strip() # empty = let compose find it
token_env = f.get("token_env", "").strip()
problems = []
@@ -331,9 +333,9 @@ def add_repo():
problems.append(f"a repo named {name} already exists")
if not SAFE_URL.match(url):
problems.append("url: must be http(s) with no username or token in it")
if not SAFE_BRANCH.match(branch):
if branch and not SAFE_BRANCH.match(branch):
problems.append("branch name has invalid characters")
if not SAFE_FILE.match(compose_file):
if compose_file and not SAFE_FILE.match(compose_file):
problems.append("compose file must be a plain file name")
if token_env and token_env not in TOKEN_ENVS:
problems.append("unknown token")
@@ -342,11 +344,15 @@ def add_repo():
flash(p, "error")
return redirect(url_for("index"))
entry = {"name": name, "url": url, "branch": branch, "compose_file": compose_file}
entry = {"name": name, "url": url}
if branch:
entry["branch"] = branch
if compose_file:
entry["compose_file"] = compose_file
if token_env:
entry["token_env"] = token_env
if f.get("pull_images") == "on":
entry["pull_images"] = True
if f.get("pull_image") != "on":
entry["pull_image"] = False # the watcher's default is True
if f.get("deploy_now") != "on":
entry["paused"] = True
@@ -357,11 +363,25 @@ def add_repo():
# ---------- file editor API (used by app.js) ----------
@app.get("/api/version")
def version():
"""A cheap fingerprint of everything the dashboard shows.
The page polls this and reloads only when it changes."""
def mtime(p: Path) -> int:
try:
return p.stat().st_mtime_ns
except OSError:
return 0
pending = pending_requests()
raw = f"{mtime(STATE_PATH)}|{mtime(Path(CONFIG_PATH))}|{sorted(pending.items())}"
return jsonify(version=hashlib.sha1(raw.encode()).hexdigest()[:16], busy=bool(pending))
@app.get("/api/repos/<name>/files")
def list_files(name: str):
repo = get_repo(name)
local = local_files(name)
return jsonify(local=local, git=git_files(repo), compose_file=repo["compose_file"],
return jsonify(local=local, git=git_files(repo), compose_file=compose_file_of(repo),
missing_env=missing_env(name))
@@ -441,9 +461,9 @@ def webhook(name: str):
return jsonify(ok=True, ignored=f"push to {ref}")
if repo["paused"]:
return jsonify(ok=True, ignored="paused")
if name not in pending_requests(): # 5 quick pushes = 1 deploy
queue_request("deploy", name)
return jsonify(ok=True, queued="deploy"), 202
if name not in pending_requests(): # 5 quick pushes = 1 check
queue_request("check", name) # deploys if the branch has a new commit
return jsonify(ok=True, queued="check"), 202
if __name__ == "__main__":
-48
View File
@@ -1,48 +0,0 @@
services:
gitops-watcher:
build: .
container_name: gitops-watcher
restart: unless-stopped
stop_grace_period: 2m
environment:
CHECK_INTERVAL: 300
STACKS_DIR: /opt/gitops
CONFIG_PATH: /config/repos.yml
STATE_PATH: /data/state.json
LOCAL_DIR: /data/local
REQUESTS_DIR: /data/requests
GITEA_TOKEN: ${GITEA_TOKEN}
GITHUB_TOKEN: ${GITHUB_TOKEN}
volumes:
- /var/run/docker.sock:/var/run/docker.sock
# the watcher now WRITES repos.yml (add / stop / start / remove), so no :ro.
# mount the folder, not the file: os.replace() can't swap a single-file bind mount
- ./config:/config
- ./data:/data
- /opt/gitops:/opt/gitops
gitops-web:
build: .
container_name: gitops-web
restart: unless-stopped
command: ["gunicorn", "--workers", "1", "--threads", "4", "--bind", "0.0.0.0:5000",
"--chdir", "/app/web", "app:app"]
ports:
- "8088:5000" # LAN only until there's a login in front (NPM access list)
environment:
CHECK_INTERVAL: 300
STACKS_DIR: /opt/gitops
CONFIG_PATH: /config/repos.yml
STATE_PATH: /data/state.json
LOCAL_DIR: /data/local
REQUESTS_DIR: /data/requests
TOKEN_ENVS: GITEA_TOKEN,GITHUB_TOKEN # names only, for the add-repo dropdown
SECRET_KEY: ${WEB_SECRET_KEY}
WEBHOOK_SECRET: ${WEBHOOK_SECRET} # same value goes in the GitHub/Gitea webhook settings
volumes:
# NO docker socket: the website can't run containers, only ask the watcher
- ./config:/config:ro
- ./data:/data:ro # can read state.json...
- ./data/local:/data/local # ...but only write local files
- ./data/requests:/data/requests # ...and requests
- /opt/gitops:/opt/gitops:ro # read the clones to show repo files
@@ -323,8 +323,28 @@ document.addEventListener("click", async e => {
} catch (err) { toast(esc(err.message), "error"); }
});
/* ---------- auto-refresh (skipped while a dialog or the editor is open) ---------- */
setInterval(() => { if (!anyOpen()) location.reload(); }, 30000);
/* ---------- live refresh (skipped while a dialog or the editor is open) ----------
poll a tiny fingerprint of state.json / repos.yml / queued requests every 2s
and reload as soon as the watcher has acted, instead of waiting for a timer */
(function () {
let seen = null, changed = false;
async function poll() {
if (document.hidden) return;
try {
const res = await fetch("/api/version", { cache: "no-store" });
if (!res.ok) return;
const { version } = await res.json();
if (seen === null) seen = version;
else if (version !== seen) changed = true;
} catch { return; }
if (changed && !anyOpen()) location.reload();
}
poll();
setInterval(poll, 2000);
document.addEventListener("visibilitychange", poll);
// still refresh now and then so the "x min ago" times stay current
setInterval(() => { if (!anyOpen()) location.reload(); }, 60000);
})();
/* ---------- countdown ---------- */
(function () {
@@ -125,8 +125,8 @@
<span class="hint">never paste a token into the url, pick one below instead</span>
</div>
<div class="row2">
<div class="field"><label for="f-branch">branch</label><input type="text" id="f-branch" name="branch" value="main"></div>
<div class="field"><label for="f-compose">compose file</label><input type="text" id="f-compose" name="compose_file" value="docker-compose.yml"></div>
<div class="field"><label for="f-branch">branch</label><input type="text" id="f-branch" name="branch" placeholder="default (main)"></div>
<div class="field"><label for="f-compose">compose file</label><input type="text" id="f-compose" name="compose_file" placeholder="auto-detect"></div>
</div>
<div class="field">
<label for="f-token">token</label>
@@ -137,7 +137,7 @@
<span class="hint">only the env var name is saved, never the token itself</span>
</div>
<label class="check">
<input type="checkbox" name="pull_images">
<input type="checkbox" name="pull_image" checked>
<span>auto-update images<span class="sub">pull newer versions of <code>image:</code> services each round</span></span>
</label>
<label class="check">
-194
View File
@@ -1,194 +0,0 @@
"""
WATCHER SIDE: paste these into watcher.py so the website's buttons do something.
The website only writes request files and local files. These functions make
the watcher:
- copy data/local/<repo>/ into the clone before every deploy
- add docker-compose.override.yml when it exists
- skip paused repos
- process request files (deploy / stop / start / remove / add)
Each block says where it goes. Function names match the ones you already have:
run, log, compose, deploy, check_repo, local_hash, load_config, normalize,
record, STACKS_DIR, LOCAL_DIR, CONFIG_PATH.
"""
# =====================================================================
# 1. TOP OF FILE: new import + constant
# =====================================================================
import shutil # add next to your other imports
REQUESTS_DIR = Path(os.environ.get("REQUESTS_DIR", "data/requests"))
# =====================================================================
# 2. CONFIG SECTION: save_config (repos.yml is now written by the watcher)
# Note: yaml.safe_dump does NOT keep comments in repos.yml.
# =====================================================================
def save_config(config: dict) -> None:
tmp = CONFIG_PATH.with_name(CONFIG_PATH.name + ".tmp")
with open(tmp, "w") as f:
yaml.safe_dump(config, f, sort_keys=False, default_flow_style=False)
os.replace(tmp, CONFIG_PATH)
# and in normalize(), add one more fallback:
# repo.setdefault("paused", False)
# =====================================================================
# 3. DOCKER SECTION: replace compose() and deploy() with these
# =====================================================================
OVERRIDE = "docker-compose.override.yml"
def compose(name: str, *args: str, path: Path | None = None,
compose_file: str | None = None, timeout: int = DEFAULT_TIMEOUT) -> str:
cmd = ["docker", "compose", "-p", name]
if compose_file:
cmd += ["-f", compose_file]
# Compose only auto-loads an override when no -f is given, so add it ourselves
if path is not None and (path / OVERRIDE).is_file():
cmd += ["-f", OVERRIDE]
return run(cmd + list(args), cwd=path, timeout=timeout)
def sync_local_files(name: str, path: Path) -> None:
"""Copy data/local/<name>/* into the clone, so compose sees .env, overrides, etc."""
local = LOCAL_DIR / name
if not local.is_dir():
return
for f in local.iterdir():
if f.is_file():
shutil.copy2(f, path / f.name)
def deploy(repo: dict, path: Path) -> None:
name = repo["name"]
log(name, "deploying...")
sync_local_files(name, path) # NEW: before anything reads the files
if repo["pull_images"]:
pull_images(name, path, repo["compose_file"])
compose(name, "up", "-d", "--build", "--remove-orphans",
path=path, compose_file=repo["compose_file"], timeout=BUILD_TIMEOUT)
log(name, "deployed ✓")
# (DEFAULT_TIMEOUT / BUILD_TIMEOUT are the timeout constants from the timeouts step.
# If you named them differently, use your names.)
# =====================================================================
# 4. NEW SECTION "requests" (put it before main)
# =====================================================================
def find_entry(config: dict, name: str) -> dict | None:
for entry in config.get("repos") or []:
if isinstance(entry, dict) and entry.get("name") == name:
return entry
return None
def handle_request(req: dict, state: dict) -> None:
action = req.get("action")
name = req.get("repo", "")
config = load_config()
config["repos"] = config.get("repos") or []
now = datetime.now().isoformat(timespec="seconds")
if action == "add":
if find_entry(config, name):
raise RuntimeError(f"{name} already exists")
config["repos"].append(req["entry"])
save_config(config)
log(name, "added from web UI")
return # the normal round clones + deploys it
entry = find_entry(config, name)
if entry is None:
raise RuntimeError(f"no repo named {name!r}")
repo = normalize(entry, config.get("defaults") or {})
path = STACKS_DIR / name
if action in ("deploy", "start"):
if action == "start":
entry["paused"] = False
save_config(config)
repo["paused"] = False
if (path / ".git").exists():
deploy(repo, path)
commit = local_hash(path)
else:
commit = check_repo(repo)["commit"] # clones + deploys
record(state, name, status="ok", error=None, commit=commit,
last_check=now, last_deploy=now)
elif action == "stop":
entry["paused"] = True
save_config(config)
if path.exists():
compose(name, "down", "--remove-orphans")
log(name, "stopped (paused)")
elif action == "remove":
wipe = bool(req.get("wipe_volumes"))
if path.exists():
compose(name, "down", "--remove-orphans", *(["-v"] if wipe else []))
config["repos"] = [e for e in config["repos"]
if not (isinstance(e, dict) and e.get("name") == name)]
save_config(config)
shutil.rmtree(path, ignore_errors=True)
if wipe:
shutil.rmtree(LOCAL_DIR / name, ignore_errors=True)
state.pop(name, None)
log(name, "removed" + (" (volumes + local files deleted)" if wipe else ""))
else:
raise RuntimeError(f"unknown action {action!r}")
def process_requests(state: dict) -> None:
"""Run every queued request, oldest first. Each file is deleted once handled."""
REQUESTS_DIR.mkdir(parents=True, exist_ok=True)
for f in sorted(REQUESTS_DIR.glob("*.json")):
req = {}
try:
req = json.loads(f.read_text())
log(req.get("repo", "?"), f"request: {req.get('action')}")
handle_request(req, state)
except Exception as e:
name = req.get("repo", "?") if isinstance(req, dict) else "?"
log(name, f"request failed: {e}")
record(state, name, status="error", error=f"request failed: {e}",
last_check=datetime.now().isoformat(timespec="seconds"))
finally:
f.unlink(missing_ok=True)
save_state(state)
# =====================================================================
# 5. main(): three small changes
# =====================================================================
#
# a) at the START of each round, before load_config():
#
# process_requests(state)
#
# b) in the per-repo loop, right after `repo = normalize(raw, defaults)`:
#
# if repo["paused"]:
# continue
#
# c) so the website and webhooks react fast: wait_for_next_round() already
# wakes up early via has_requests(), but only for the CLI's REQUEST_DIR.
# Make it look at the website's folder too:
#
# def has_requests() -> bool:
# return any(d.is_dir() and any(d.glob("*.json"))
# for d in (REQUEST_DIR, REQUESTS_DIR))
#
# Only do this together with (a): if nothing deletes the files in
# REQUESTS_DIR, the watcher would wake up every second forever.
# (a full round then runs: requests first, then the normal checks)