From 5f7081320255d3ccf4976e180c087ec27dd047cb Mon Sep 17 00:00:00 2001 From: rainyy21 Date: Wed, 11 Nov 2026 16:17:05 -0500 Subject: [PATCH] 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 --- .gitignore | 6 +- Dockerfile | 3 +- app/cli.py | 85 +---- app/watcher.py | 410 +++++++++++++++++++++++-- app/web/{web => }/app.py | 90 +++--- app/web/docker-compose.yml | 48 --- app/web/{web => }/static/app.js | 24 +- app/web/{web => }/static/style.css | 0 app/web/{web => }/templates/base.html | 0 app/web/{web => }/templates/index.html | 6 +- app/web/watcher_additions.py | 194 ------------ docker-compose.yml | 51 ++- requirements.txt | 2 + 13 files changed, 533 insertions(+), 386 deletions(-) rename app/web/{web => }/app.py (85%) delete mode 100644 app/web/docker-compose.yml rename app/web/{web => }/static/app.js (94%) rename app/web/{web => }/static/style.css (100%) rename app/web/{web => }/templates/base.html (100%) rename app/web/{web => }/templates/index.html (97%) delete mode 100644 app/web/watcher_additions.py diff --git a/.gitignore b/.gitignore index 3b6c344..985206e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,7 @@ -.env +.env stacks/ __pycache__/ .venv/ repos.yml - - +config/ +data/ diff --git a/Dockerfile b/Dockerfile index c6c1c11..2441bcd 100644 --- a/Dockerfile +++ b/Dockerfile @@ -8,7 +8,8 @@ COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt -COPY app/watcher.py app/cli.py ./ +# watcher.py + cli.py, and web/ for the gitops-web service (same image) +COPY app/ ./ ENV PYTHONUNBUFFERED=1 diff --git a/app/cli.py b/app/cli.py index 31e2f32..e1aaf8d 100644 --- a/app/cli.py +++ b/app/cli.py @@ -7,19 +7,21 @@ import typer from rich.console import Console from rich.markup import escape from rich.table import Table -from ruamel.yaml import YAML -from ruamel.yaml.error import CommentMark -from ruamel.yaml.tokens import CommentToken - from watcher import ( CONFIG_PATH, NAME_RE, STACKS_DIR, + append_entry, + compose_cmd, + delete_entry, + find_index, load_config, + load_config_rt, load_state, normalize, redact, request_check, + save_config_rt, ) app = typer.Typer(help="control the gitops-watcher.") @@ -74,60 +76,6 @@ def find_repo(name: str, quiet: bool = False) -> dict | None: fail(f"no repo named '{name}' in {CONFIG_PATH}") -# round-trip YAML keeps comments and layout when add/remove edit repos.yml -rt_yaml = YAML() -rt_yaml.indent(mapping=2, sequence=4, offset=2) -rt_yaml.preserve_quotes = True - - -def load_config_rt(): - try: - with CONFIG_PATH.open() as f: - return rt_yaml.load(f) or {} - except FileNotFoundError: - return {} - - -def save_config_rt(data) -> None: - # write in place (no temp file + rename): repos.yml is a single-file bind - # mount in docker, and replacing the file would detach it from the container - with CONFIG_PATH.open("w") as f: - rt_yaml.dump(data, f) - - -# ruamel stores the blank lines/comments *after* a list entry on that entry's -# last key, so they have to be moved by hand when entries are added or removed -def _trailing(entry): - tok = entry.ca.items.get(list(entry.keys())[-1]) - return tok[2] if tok and len(tok) > 2 else None - - -def _set_trailing(entry, token) -> None: - tok = entry.ca.items.setdefault(list(entry.keys())[-1], [None, None, None, None]) - tok[2] = token - - -def append_entry(repos, entry: dict) -> None: - """Append with a blank line before it, like the hand-written entries.""" - if repos and _trailing(repos[-1]) is None: - _set_trailing(repos[-1], CommentToken("\n\n", CommentMark(0), None)) - repos.append(entry) - - -def delete_entry(repos, idx: int) -> None: - """Delete an entry, keeping the comment that sits above the entry after it.""" - after = _trailing(repos[idx]) - if idx > 0: - _set_trailing(repos[idx - 1], after) - elif after is not None: - text = "\n".join( - l.strip().lstrip("#").strip() for l in after.value.splitlines() if l.strip() - ) - if text: - repos.yaml_set_start_comment(text, indent=2) - del repos[idx] - - def config_names() -> list[str] | None: """Repo names from repos.yml, or None if it can't be read.""" try: @@ -277,10 +225,7 @@ def logs( else: compose_file = load_state().get(name, {}).get("compose_file") - cmd = ["docker", "compose", "-p", name] - if compose_file: - cmd += ["-f", compose_file] - cmd += ["logs", "--tail", str(tail)] + cmd = compose_cmd(name, path, compose_file) + ["logs", "--tail", str(tail)] if follow: cmd.append("--follow") # not captured: output streams straight to the terminal @@ -298,7 +243,8 @@ def check( wait: bool = typer.Option(False, "--wait", help="Wait for the result."), ): """Ask the watcher to check a repo now.""" - find_repo(name) # exits if it isn't in repos.yml + if find_repo(name)["paused"]: # find_repo exits if it isn't in repos.yml + fail(f"'{name}' is paused in {CONFIG_PATH}; unpause it first (or use Start in the website)") before = load_state().get(name, {}).get("last_check") request_check(name, force) console.print(f"requested a check of [cyan]{name}[/cyan]" + (" (forced redeploy)" if force else "")) @@ -338,10 +284,8 @@ def add( fail("token auth only works with https:// URLs") data = load_config_rt() - repos = data.get("repos") - if repos is None: - repos = data["repos"] = [] - if any(isinstance(r, dict) and r.get("name") == name for r in repos): + repos = data["repos"] + if find_index(repos, name) is not None: fail(f"'{name}' is already in {CONFIG_PATH}") # only write what was given, so the entry inherits from `defaults` @@ -367,11 +311,8 @@ def remove( ): """Remove a repo from repos.yml.""" data = load_config_rt() - repos = data.get("repos") or [] - idx = next( - (i for i, r in enumerate(repos) if isinstance(r, dict) and r.get("name") == name), - None, - ) + repos = data["repos"] + idx = find_index(repos, name) if idx is None: fail(f"no repo named '{name}' in {CONFIG_PATH}") diff --git a/app/watcher.py b/app/watcher.py index 63e9936..c698224 100644 --- a/app/watcher.py +++ b/app/watcher.py @@ -2,7 +2,9 @@ import base64 import json import os import re +import shlex import shutil +import socket import subprocess import time import signal @@ -11,13 +13,19 @@ from datetime import datetime from pathlib import Path import yaml +from ruamel.yaml import YAML +from ruamel.yaml.error import CommentMark +from ruamel.yaml.tokens import CommentToken CONFIG_PATH = Path(os.environ.get("CONFIG_PATH", "repos.yml")) STACKS_DIR = Path(os.environ.get("STACKS_DIR", "stacks")) CHECK_INTERVAL = int(os.environ.get("CHECK_INTERVAL", "60")) STATE_PATH = Path(os.environ.get("STATE_PATH", STACKS_DIR / ".state.json")) -# `cli.py check` drops a file here to make the watcher check a repo right away +# the CLI and the website drop request files here (check / deploy / stop / ...); +# the watcher wakes up, handles them, and deletes them REQUEST_DIR = Path(os.environ.get("REQUEST_DIR", STACKS_DIR / ".requests")) +# files edited in the website (.env, overrides...), copied into the clone before each deploy +LOCAL_DIR = Path(os.environ.get("LOCAL_DIR", STACKS_DIR / ".local")) # seconds before a command is killed GIT_TIMEOUT = int(os.environ.get("GIT_TIMEOUT", "300")) # clone / fetch @@ -133,6 +141,23 @@ def update(path: Path, branch: str, env: dict | None = None) -> None: # --- docker --- +OVERRIDES = ("compose.override.yaml", "compose.override.yml", + "docker-compose.override.yaml", "docker-compose.override.yml") + + +def compose_cmd(name: str, path: Path | None, compose_file: str | None) -> list[str]: + """docker compose -p [-f [-f ]]""" + cmd = ["docker", "compose", "-p", name] + if compose_file: + cmd += ["-f", compose_file] + # compose only auto-loads an override file when no -f is given, so add it ourselves + for override in OVERRIDES: + if path is not None and (path / override).is_file(): + cmd += ["-f", override] + break + return cmd + + def compose( name, *args, @@ -141,14 +166,22 @@ def compose( timeout: float = COMPOSE_TIMEOUT, ): """Build and run: docker compose -p [-f ] """ - cmd = ["docker", "compose", "-p", name] - if compose_file: - cmd += ["-f", compose_file] - return run(cmd + list(args), cwd=path, timeout=timeout) + return run(compose_cmd(name, path, compose_file) + list(args), cwd=path, timeout=timeout) + + +def sync_local_files(name: str, path: Path) -> None: + """Copy LOCAL_DIR//* into the clone, so compose sees .env, overrides, etc.""" + local = LOCAL_DIR / name + if not local.is_dir() or not path.is_dir(): + return + for f in local.iterdir(): + if f.is_file(): + shutil.copy2(f, path / f.name) def deploy(name, path, compose_file, pull: bool = True): log(name, "deploying...") + sync_local_files(name, path) if pull: pull_image(name, path, compose_file) compose( @@ -239,6 +272,7 @@ def check_repo(repo, state: dict) -> dict: if current.get("commit") == remote and cloned: # no new commit: refresh images / restart stopped containers. # `up -d` only recreates containers whose image or config changed. + sync_local_files(name, path) if repo["pull_image"]: pull_image(name, path, compose_file) compose( @@ -271,13 +305,127 @@ def remove_stack(name: str, state: dict) -> bool: path = STACKS_DIR / name if path.exists(): try: - stop(name, path, state[name].get("compose_file")) + stop(name, path, state.get(name, {}).get("compose_file")) except Exception as e: log(name, f"removed from config but can't stop it, will retry: {e}") return False return True +# --- self-update --- +# +# The watcher can't `docker compose up` its own stack: Docker would stop it halfway. +# So when its own repo has a new commit, it starts a one-off helper container that +# runs `git pull` + `docker compose up -d --build` in the checkout on the host. +# The helper isn't part of the stack, so it survives the restart. +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 +UPDATER = "gitops-watcher-updater" + +# 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 +# running: commit we were started from; tried: last commit an update was started for +SELF: dict = {} + + +def git_self(*args, timeout: float = 10) -> str: + return run(["git", "-C", str(SELF_DIR), *args], timeout=timeout) + + +def detect_self() -> None: + """Read our compose project and checkout path from our own container's labels.""" + try: + info = json.loads(run(["docker", "inspect", socket.gethostname()]))[0] + except Exception as e: + log("self", f"can't inspect own container: {e}") + return + labels = info.get("Config", {}).get("Labels") or {} + SELF["project"] = labels.get("com.docker.compose.project") + SELF["host_dir"] = labels.get("com.docker.compose.project.working_dir") + SELF["image"] = info.get("Config", {}).get("Image") + if not SELF_UPDATE: + 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") + except Exception as e: + log("self", f"self-update off: {e}") + return + log("self", f"self-update on, running {SELF['running'][:7]} from {SELF['host_dir']}") + # tell about a failed update from before the restart + try: + code = run(["docker", "inspect", "-f", "{{.State.ExitCode}}", UPDATER]) + if code != "0": + log("self", f"last self-update failed (exit {code}): docker logs {UPDATER}") + except Exception: + pass + + +def check_self() -> None: + """Start the updater if the watcher's own branch has a commit we aren't running.""" + if not SELF.get("running"): + return + + def note(msg: str) -> None: # log each skip reason once, not every round + if SELF.get("note") != msg: + log("self", msg) + SELF["note"] = msg + + try: + branch = git_self("rev-parse", "--abbrev-ref", "HEAD") + remote = remote_hash(git_self("remote", "get-url", "origin"), branch) + 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}") + return + if remote == SELF["running"] or remote == SELF.get("tried"): + return # up to date, or this commit already failed once + if dirty: + note(f"{branch} has {remote[:7]}, but the checkout has uncommitted changes: not updating") + return + if local != remote: + try: # remote is behind us = unpushed commits + git_self("merge-base", "--is-ancestor", remote, local) + note(f"the checkout has commits not pushed to {branch}: not updating") + return + except Exception: + pass # behind (or diverged: `pull --ff-only` will refuse) + + try: + state = run(["docker", "inspect", "-f", "{{.State.Running}}", UPDATER]) + if state == "true": + return # an update is already running + run(["docker", "rm", UPDATER]) + except RuntimeError: + pass # no old updater + + owner = SELF_DIR.stat() + docker_gid = os.stat("/var/run/docker.sock").st_gid + host_dir = SELF["host_dir"] + script = (f"git pull --ff-only origin {shlex.quote(branch)} && " + f"docker compose -p {shlex.quote(SELF['project'])} up -d --build") + try: + run([ + "docker", "run", "-d", "--name", UPDATER, + # as the checkout's owner, so pulled files aren't root-owned + "--user", f"{owner.st_uid}:{owner.st_gid}", "--group-add", str(docker_gid), + "-e", "HOME=/tmp", "-e", "GIT_TERMINAL_PROMPT=0", + "-v", "/var/run/docker.sock:/var/run/docker.sock", + "-v", f"{host_dir}:{host_dir}", "-w", host_dir, + "--entrypoint", "sh", SELF["image"], "-c", script, + ], timeout=60) + except Exception as e: + note(f"can't start the updater: {e}") + return + SELF["tried"] = remote + SELF["note"] = None + log("self", f"updating to {remote[:7]}, the watcher restarts in a moment " + f"(progress: docker logs -f {UPDATER})") + + # --- config --- def load_config() -> dict: with CONFIG_PATH.open() as f: @@ -300,9 +448,90 @@ def normalize(raw, defaults: dict) -> dict: repo.setdefault("branch", "main") repo.setdefault("compose_file", None) repo.setdefault("pull_image", True) + repo.setdefault("paused", False) return repo +def ensure_config() -> None: + """Create an empty repos.yml on first start, so there's something to add repos to.""" + if CONFIG_PATH.exists(): + return + CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True) + CONFIG_PATH.write_text( + "# repos the watcher deploys. Add with `cli.py add` or the website.\n" + "defaults:\n branch: main\n\nrepos: []\n" + ) + log("watcher", f"created empty {CONFIG_PATH}") + + +# round-trip YAML keeps comments and layout when repos.yml is edited by code +rt_yaml = YAML() +rt_yaml.indent(mapping=2, sequence=4, offset=2) +rt_yaml.preserve_quotes = True + + +def load_config_rt(): + try: + with CONFIG_PATH.open() as f: + data = rt_yaml.load(f) + except FileNotFoundError: + data = None + if data is None: + data = rt_yaml.load("repos: []\n") + if data.get("repos") is None: + data["repos"] = rt_yaml.load("[]") + return data + + +def save_config_rt(data) -> None: + # write in place (no temp file + rename): keeps the file's owner/permissions on the + # host, and still works if repos.yml is bind-mounted as a single file + with CONFIG_PATH.open("w") as f: + rt_yaml.dump(data, f) + + +def find_index(repos, name: str) -> int | None: + return next( + (i for i, r in enumerate(repos) if isinstance(r, dict) and r.get("name") == name), + None, + ) + + +# ruamel stores the blank lines/comments *after* a list entry on that entry's +# last key, so they have to be moved by hand when entries are added or removed +def _trailing(entry): + tok = entry.ca.items.get(list(entry.keys())[-1]) + return tok[2] if tok and len(tok) > 2 else None + + +def _set_trailing(entry, token) -> None: + tok = entry.ca.items.setdefault(list(entry.keys())[-1], [None, None, None, None]) + tok[2] = token + + +def append_entry(repos, entry: dict) -> None: + """Append with a blank line before it, like the hand-written entries.""" + if hasattr(repos, "fa"): + repos.fa.set_block_style() # `repos: []` would otherwise stay on one line + if repos and hasattr(repos[-1], "ca") and _trailing(repos[-1]) is None: + _set_trailing(repos[-1], CommentToken("\n\n", CommentMark(0), None)) + repos.append(entry) + + +def delete_entry(repos, idx: int) -> None: + """Delete an entry, keeping the comment that sits above the entry after it.""" + after = _trailing(repos[idx]) if hasattr(repos[idx], "ca") else None + if idx > 0 and hasattr(repos[idx - 1], "ca"): + _set_trailing(repos[idx - 1], after) + elif after is not None: + text = "\n".join( + l.strip().lstrip("#").strip() for l in after.value.splitlines() if l.strip() + ) + if text: + repos.yaml_set_start_comment(text, indent=2) + del repos[idx] + + # --- state --- def load_state() -> dict: if not STATE_PATH.exists(): @@ -327,32 +556,133 @@ def record(state: dict, name: str, **fields) -> None: state.setdefault(name, {}).update(fields) -# --- check requests (from cli.py) --- -def request_check(name: str, force: bool = False) -> None: +# --- requests (from cli.py and the website) --- +# +# A request is a JSON file in REQUEST_DIR: {"action": ..., "repo": , ...} +# check clear the retry backoff; the round then deploys if there's a new commit +# deploy like check, but redeploy even if nothing changed +# stop pause the repo in repos.yml and `docker compose down` it +# start unpause it; the round brings it back up +# add append {"entry": {...}} to repos.yml +# remove `docker compose down` (+ volumes and files if "wipe_volumes"), drop from repos.yml +ACTIONS = ("check", "deploy", "stop", "start", "add", "remove") + + +def queue_request(action: str, repo: str, **extra) -> None: + req = {"action": action, "repo": repo, + "created": datetime.now().isoformat(timespec="seconds"), **extra} REQUEST_DIR.mkdir(parents=True, exist_ok=True) - (REQUEST_DIR / f"{name}.json").write_text(json.dumps({"force": force})) + path = REQUEST_DIR / f"{time.time_ns()}-{action}-{repo}.json" + # write then rename, so the watcher never reads a half-written file + tmp = path.with_name(path.name + ".tmp") + tmp.write_text(json.dumps(req, indent=2)) + tmp.replace(path) + + +def request_check(name: str, force: bool = False) -> None: + queue_request("deploy" if force else "check", name) def has_requests() -> bool: return REQUEST_DIR.is_dir() and any(REQUEST_DIR.glob("*.json")) -def apply_requests(state: dict) -> None: - """Clear backoff for requested repos (and the deployed commit, if forced).""" - if not REQUEST_DIR.is_dir(): +def set_paused(name: str, paused: bool) -> None: + data = load_config_rt() + idx = find_index(data["repos"], name) + if idx is None: + raise RuntimeError(f"no repo named {name!r} in {CONFIG_PATH}") + if paused: + data["repos"][idx]["paused"] = True + else: + data["repos"][idx].pop("paused", None) + save_config_rt(data) + + +def handle_request(req: dict, state: dict) -> None: + action = req.get("action") + name = str(req.get("repo") or "") + if action not in ACTIONS: + raise RuntimeError(f"unknown action {action!r}") + if not NAME_RE.match(name): + raise RuntimeError(f"invalid repo name {name!r}") + if name == SELF.get("project") and action != "add": + raise RuntimeError(f"{name} is the watcher's own stack, it can't {action} itself") + log(name, f"request: {action}") + + if action == "add": + entry = req.get("entry") + if not isinstance(entry, dict) or entry.get("name") != name: + raise RuntimeError("add request has no valid entry") + config = load_config() + normalize(entry, config.get("defaults") or {}) # raises if invalid + data = load_config_rt() + if find_index(data["repos"], name) is not None: + raise RuntimeError(f"{name} is already in {CONFIG_PATH}") + append_entry(data["repos"], entry) + save_config_rt(data) + log(name, "added; deploys this round" + (" (paused)" if entry.get("paused") else "")) return - for f in REQUEST_DIR.glob("*.json"): - name = f.stem - try: - force = json.loads(f.read_text() or "{}").get("force", False) - except (json.JSONDecodeError, OSError): - force = False - f.unlink(missing_ok=True) - log(name, "check requested" + (" (forced redeploy)" if force else "")) + + config = load_config() + raw = next((r for r in config.get("repos") or [] + if isinstance(r, dict) and r.get("name") == name), None) + if raw is None: + raise RuntimeError(f"no repo named {name!r} in {CONFIG_PATH}") + repo = normalize(raw, config.get("defaults") or {}) + path = STACKS_DIR / name + + if action in ("check", "deploy", "start"): + if action == "start": + set_paused(name, False) if name in state: record(state, name, failed_commit=None, retry_at=None) - if force: - state[name].pop("commit", None) + if action == "deploy": + state[name].pop("commit", None) # forces a redeploy this round + + elif action == "stop": + set_paused(name, True) + if path.exists(): + stop(name, path, repo["compose_file"]) + record(state, name, status="paused", error=None) + + elif action == "remove": + wipe = bool(req.get("wipe_volumes")) + if path.exists(): + log(name, "stopping...") + compose(name, "down", "--remove-orphans", *(["-v"] if wipe else []), + path=path, compose_file=repo["compose_file"]) + data = load_config_rt() + idx = find_index(data["repos"], name) + if idx is not None: + delete_entry(data["repos"], idx) + save_config_rt(data) + if wipe: + shutil.rmtree(path, ignore_errors=True) + shutil.rmtree(LOCAL_DIR / name, ignore_errors=True) + state.pop(name, None) + log(name, "removed" + (" (volumes and files deleted)" if wipe else "")) + + +def process_requests(state: dict) -> None: + """Handle every queued request, oldest first. Each file is deleted once handled.""" + if not REQUEST_DIR.is_dir(): + return + for f in sorted(REQUEST_DIR.glob("*.json")): + req = None + try: + req = json.loads(f.read_text() or "{}") + if not isinstance(req, dict): + raise RuntimeError("request is not a JSON object") + handle_request(req, state) + except Exception as e: + name = req.get("repo") if isinstance(req, dict) else None + log(str(name or f.name), f"request failed: {e}") + if name in state: + record(state, name, status="error", error=f"request failed: {e}", + last_check=datetime.now().isoformat(timespec="seconds")) + finally: + f.unlink(missing_ok=True) def wait_for_next_round(seconds: float) -> None: @@ -367,15 +697,23 @@ def wait_for_next_round(seconds: float) -> None: # --- main loop --- def main() -> None: STACKS_DIR.mkdir(parents=True, exist_ok=True) + STATE_PATH.parent.mkdir(parents=True, exist_ok=True) + REQUEST_DIR.mkdir(parents=True, exist_ok=True) state = load_state() log("watcher", f"started, checking every {CHECK_INTERVAL}s") + # only on a fresh install: if stacks are running and repos.yml went missing, + # an empty one would make the watcher stop all of them + if not state: + ensure_config() + + detect_self() signal.signal(signal.SIGTERM, handle_stop) signal.signal(signal.SIGINT, handle_stop) while not STOP.is_set(): round_start = time.time() - apply_requests(state) + process_requests(state) checked = deployed = errors = 0 try: config = load_config() @@ -411,6 +749,27 @@ def main() -> None: seen.add(name) now = datetime.now().isoformat(timespec="seconds") + if name == SELF.get("project"): + # deploying/stopping it would stop the watcher itself mid-way + msg = "this is the watcher's own stack: remove it from repos.yml (it updates itself)" + if state.get(name, {}).get("error") != msg: + log(name, msg) + record(state, name, status="error", error=msg, last_check=now) + continue + if repo["paused"]: + # paused by hand in repos.yml (the stop request already did this): bring it down once + if state.get(name, {}).get("status") != "paused": + path = STACKS_DIR / name + try: + if path.exists(): + stop(name, path, repo["compose_file"]) + record(state, name, status="paused", error=None, last_check=now) + except Exception as e: + errors += 1 + log(name, f"paused but can't stop it: {e}") + record(state, name, status="error", error=str(e), last_check=now) + continue + checked += 1 try: result = check_repo(repo, state) @@ -463,7 +822,7 @@ def main() -> None: # entry (a typo can't take a stack down) or when stopping mid-loop # (`seen` would be incomplete). if config_ok and not STOP.is_set(): - for old in [n for n in state if n not in seen]: + for old in [n for n in state if n not in seen and n != SELF.get("project")]: if remove_stack(old, state): log(old, "removed from config, stack stopped") del state[old] @@ -483,6 +842,9 @@ def main() -> None: f"{errors} errors ({elapsed:.1f}s)", ) + if not STOP.is_set(): + check_self() + try: save_state(state) except OSError as e: diff --git a/app/web/web/app.py b/app/web/app.py similarity index 85% rename from app/web/web/app.py rename to app/web/app.py index 1a537fc..856781e 100644 --- a/app/web/web/app.py +++ b/app/web/app.py @@ -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//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__": diff --git a/app/web/docker-compose.yml b/app/web/docker-compose.yml deleted file mode 100644 index 3c91071..0000000 --- a/app/web/docker-compose.yml +++ /dev/null @@ -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 diff --git a/app/web/web/static/app.js b/app/web/static/app.js similarity index 94% rename from app/web/web/static/app.js rename to app/web/static/app.js index 4159895..39dfac9 100644 --- a/app/web/web/static/app.js +++ b/app/web/static/app.js @@ -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 () { diff --git a/app/web/web/static/style.css b/app/web/static/style.css similarity index 100% rename from app/web/web/static/style.css rename to app/web/static/style.css diff --git a/app/web/web/templates/base.html b/app/web/templates/base.html similarity index 100% rename from app/web/web/templates/base.html rename to app/web/templates/base.html diff --git a/app/web/web/templates/index.html b/app/web/templates/index.html similarity index 97% rename from app/web/web/templates/index.html rename to app/web/templates/index.html index 8875b25..4aedd11 100644 --- a/app/web/web/templates/index.html +++ b/app/web/templates/index.html @@ -125,8 +125,8 @@ never paste a token into the url, pick one below instead
-
-
+
+
@@ -137,7 +137,7 @@ only the env var name is saved, never the token itself