Compare commits

...

10 Commits

Author SHA1 Message Date
rainyy21 5f70813202 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>
2026-11-11 16:17:05 -05:00
rainyy21 999f852805 forgot to add the .env.example 2026-11-11 09:53:31 -05:00
rainyy21 218d1a1366 added ed webhook to it 2026-11-11 09:50:38 -05:00
rainyy21 27e1c0047f build a website 2026-11-11 09:03:30 -05:00
rainyy21 92aba3bf38 finish the ain watcher command and finish the cli, modify the requirement and started a web template, modify the docker file 2026-11-11 00:16:45 -05:00
rainyy21 ddef48ad6b improve on it so now it check if there any update if there is pull and push it to the container 2026-11-10 12:32:50 -05:00
rainyy21 7b3bf37108 fix up some typo on the docker file and add enviroment 2026-11-10 12:32:08 -05:00
rainyy21 8cddb79686 added github key to .env.example 2026-11-10 12:31:05 -05:00
rainyy21 ce29d9ede7 fix up the docker file since i move file aroumd 2026-11-10 10:02:24 -05:00
rainyy21 287ea4b90c move the watcher to a app file and set up docker file and docker compose file 2026-11-09 13:39:25 -05:00
14 changed files with 2715 additions and 194 deletions
+5
View File
@@ -0,0 +1,5 @@
GITEA_TOKEN=your-real-token
GITHUB_TOKEN=your-real-token
WEB_SECRET_KEY=change-me
# generate with: openssl rand -hex 32
WEBHOOK_SECRET=change-me
+3 -2
View File
@@ -2,5 +2,6 @@
stacks/ stacks/
__pycache__/ __pycache__/
.venv/ .venv/
repos.yml
config/
data/
+16
View File
@@ -0,0 +1,16 @@
FROM python:3.12-alpine
RUN apk add --no-cache git docker-cli docker-cli-compose && git config --global --add safe.directory '*'
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# watcher.py + cli.py, and web/ for the gitops-web service (same image)
COPY app/ ./
ENV PYTHONUNBUFFERED=1
CMD ["python", "/app/watcher.py"]
View File
+332
View File
@@ -0,0 +1,332 @@
import os
import subprocess
import time
from datetime import datetime
import typer
from rich.console import Console
from rich.markup import escape
from rich.table import Table
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.")
console = Console()
def ago(iso: str | None) -> str:
"""'2026-11-11T09:30:00' -> '09:30:00 (5m ago)', or '-' if missing."""
if not iso:
return "-"
try:
then = datetime.fromisoformat(iso)
except ValueError:
return iso
secs = int((datetime.now() - then).total_seconds())
if secs < 60:
rel = f"{secs}s"
elif secs < 3600:
rel = f"{secs // 60}m"
elif secs < 86400:
rel = f"{secs // 3600}h"
else:
rel = f"{secs // 86400}d"
return f"{then:%m-%d %H:%M:%S} ({rel} ago)"
def fail(msg: str) -> None:
console.print(f"[red]{msg}[/red]")
raise typer.Exit(code=1)
def find_repo(name: str, quiet: bool = False) -> dict | None:
"""The normalized repo entry for `name` from repos.yml.
Exits with an error if it's missing or invalid, or returns None when quiet.
"""
try:
config = load_config()
except Exception as e:
fail(f"can't read {CONFIG_PATH}: {e}")
defaults = config.get("defaults") or {}
for raw in config.get("repos") or []:
if isinstance(raw, dict) and raw.get("name") == name:
try:
return normalize(raw, defaults)
except ValueError as e:
if quiet:
return None
fail(f"entry for '{name}' is invalid: {e}")
if quiet:
return None
fail(f"no repo named '{name}' in {CONFIG_PATH}")
def config_names() -> list[str] | None:
"""Repo names from repos.yml, or None if it can't be read."""
try:
config = load_config()
except Exception:
return None
defaults = config.get("defaults") or {}
names = []
for raw in config.get("repos") or []:
try:
names.append(normalize(raw, defaults)["name"])
except ValueError:
pass
return names
@app.command()
def status():
"""Show the status of every watched repo."""
state = load_state()
names = config_names()
# repos in the config but not checked yet show up as "pending"
for name in names or []:
state.setdefault(name, {"status": "pending"})
if not state:
console.print("[yellow]No data yet. Has the watcher run a round?[/yellow]")
return
table = Table(title="gitops-watcher")
table.add_column("Repo", style="cyan", no_wrap=True)
table.add_column("Status")
table.add_column("Commit")
table.add_column("Last check")
table.add_column("Last deploy")
table.add_column("Error", max_width=60)
failing = 0
for name, info in sorted(state.items()):
status = info.get("status") or "unknown"
if status == "ok":
status_cell = "[green]ok[/green]"
elif status == "error":
failing += 1
status_cell = "[red]error[/red]"
retry_at = info.get("retry_at")
if retry_at and retry_at > time.time():
mins = int((retry_at - time.time()) // 60) + 1
status_cell += f"\n[dim]retry in {mins}m ({info.get('failures', 1)}x)[/dim]"
else:
status_cell = f"[yellow]{escape(status)}[/yellow]"
if names is not None and name not in names:
status_cell += "\n[dim]not in config[/dim]"
# commit: first 7 chars, or "-" if missing
commit = (info.get("commit") or "-")[:7]
# times: show them, or "-" if missing
last_check = ago(info.get("last_check"))
last_deploy = ago(info.get("last_deploy"))
# error: last non-empty line, or "" if none. The first line is always
# "<command> failed:"; the actual cause is at the end of the output.
# escaped so [brackets] in git/docker output aren't read as rich markup
lines = [l for l in (info.get("error") or "").splitlines() if l.strip()]
error = escape(lines[-1]) if lines else ""
table.add_row(name, status_cell, commit, last_check, last_deploy, error)
console.print(table)
if names is None:
console.print("[yellow]couldn't read repos.yml; showing saved state only[/yellow]")
# non-zero exit when something is failing, so scripts/cron can alert on it
raise typer.Exit(code=1 if failing else 0)
@app.command()
def list_repos():
"""List repos from repos.yml with their settings."""
try:
config = load_config()
except Exception as e:
fail(f"can't read {CONFIG_PATH}: {e}")
defaults = config.get("defaults") or {}
entries = config.get("repos") or []
if not entries:
console.print(f"[yellow]no repos in {CONFIG_PATH}[/yellow]")
return
table = Table(title=str(CONFIG_PATH))
table.add_column("Repo", style="cyan", no_wrap=True)
table.add_column("URL")
table.add_column("Branch")
table.add_column("Compose file")
table.add_column("Pull")
table.add_column("Token")
invalid = 0
for i, raw in enumerate(entries):
try:
repo = normalize(raw, defaults)
except ValueError as e:
invalid += 1
label = raw.get("name") if isinstance(raw, dict) and raw.get("name") else f"repos[{i}]"
table.add_row(escape(str(label)), f"[red]invalid: {escape(str(e))}[/red]", "", "", "", "")
continue
token_env = repo.get("token_env")
if not token_env:
token = "[dim]none[/dim]"
elif os.environ.get(token_env):
token = f"{token_env} [green]set[/green]"
else:
token = f"{token_env} [red]not set[/red]"
table.add_row(
repo["name"],
escape(redact(repo["url"])),
repo["branch"],
repo["compose_file"] or "[dim]auto[/dim]",
"yes" if repo["pull_image"] else "no",
token,
)
console.print(table)
if invalid:
raise typer.Exit(code=1)
@app.command()
def logs(
name: str,
tail: int = typer.Option(50, help="Number of lines per container."),
follow: bool = typer.Option(False, "--follow", "-f", help="Keep streaming new lines."),
):
"""Show recent container logs for a stack."""
path = STACKS_DIR / name
if not path.is_dir():
fail(f"no stack folder at {path}; has '{name}' been deployed?")
# prefer the current config; fall back to the saved state for stacks
# that were removed from repos.yml but are still running
repo = find_repo(name, quiet=True)
if repo:
compose_file = repo["compose_file"]
else:
compose_file = load_state().get(name, {}).get("compose_file")
cmd = compose_cmd(name, path, compose_file) + ["logs", "--tail", str(tail)]
if follow:
cmd.append("--follow")
# not captured: output streams straight to the terminal
try:
code = subprocess.run(cmd, cwd=path).returncode
except KeyboardInterrupt:
code = 0
raise typer.Exit(code=code)
@app.command()
def check(
name: str,
force: bool = typer.Option(False, "--force", help="Redeploy even if nothing changed."),
wait: bool = typer.Option(False, "--wait", help="Wait for the result."),
):
"""Ask the watcher to check a repo now."""
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 ""))
console.print("[dim]clears any retry backoff; the watcher picks it up within a second[/dim]")
if not wait:
return
with console.status("waiting for the watcher..."):
try:
while True:
time.sleep(1)
info = load_state().get(name, {})
if info.get("last_check") != before:
break
except KeyboardInterrupt:
fail("stopped waiting (the check still happens)")
if info.get("status") == "ok":
console.print(f"[green]ok[/green] at {(info.get('commit') or '-')[:7]}")
else:
lines = [l for l in (info.get("error") or "").splitlines() if l.strip()]
fail(f"error: {lines[-1] if lines else 'unknown'}")
@app.command()
def add(
name: str,
url: str,
branch: str = typer.Option(None, help="Defaults to the branch in repos.yml defaults, or main."),
token_env: str = typer.Option(None, help="Name of the env var holding the access token."),
compose_file: str = typer.Option(None, help="Defaults to repos.yml defaults, or auto-detect."),
):
"""Add a repo to repos.yml."""
if not NAME_RE.match(name):
fail(f"invalid name '{name}': use lowercase letters, digits, '-' and '_'")
if token_env and not url.startswith("https://"):
fail("token auth only works with https:// URLs")
data = load_config_rt()
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`
entry = {"name": name, "url": url}
if branch:
entry["branch"] = branch
if token_env:
entry["token_env"] = token_env
if compose_file:
entry["compose_file"] = compose_file
append_entry(repos, entry)
save_config_rt(data)
console.print(f"added [cyan]{name}[/cyan] to {CONFIG_PATH}; the watcher deploys it on its next round")
if token_env and not os.environ.get(token_env):
console.print(f"[yellow]note: {token_env} isn't set here. Add it to .env, then recreate the container (docker compose up -d) so the watcher sees it[/yellow]")
@app.command()
def remove(
name: str,
yes: bool = typer.Option(False, "--yes", "-y", help="Don't ask for confirmation."),
):
"""Remove a repo from repos.yml."""
data = load_config_rt()
repos = data["repos"]
idx = find_index(repos, name)
if idx is None:
fail(f"no repo named '{name}' in {CONFIG_PATH}")
console.print(
f"this removes [cyan]{name}[/cyan] from {CONFIG_PATH}. On its next round the watcher "
f"runs `docker compose down` for it.\n[dim]its folder and volumes are kept[/dim]"
)
if not yes and not typer.confirm("continue?"):
raise typer.Exit(code=1)
delete_entry(repos, idx)
save_config_rt(data)
console.print(f"removed [cyan]{name}[/cyan]")
if __name__ == "__main__":
app()
+859
View File
@@ -0,0 +1,859 @@
import base64
import json
import os
import re
import shlex
import shutil
import socket
import subprocess
import time
import signal
import threading
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"))
# 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
DEPLOY_TIMEOUT = int(os.environ.get("DEPLOY_TIMEOUT", "1800")) # build / pull
COMPOSE_TIMEOUT = 120 # up / down / restart
# after a failed deploy, wait CHECK_INTERVAL, then 2x, 4x... up to this before retrying the same commit
MAX_BACKOFF = int(os.environ.get("MAX_BACKOFF", "3600"))
# docker compose project names: lowercase letters, digits, '-' and '_'
NAME_RE = re.compile(r"^[a-z0-9][a-z0-9_-]*$")
# fail instead of waiting for a username/password prompt
os.environ["GIT_TERMINAL_PROMPT"] = "0"
STOP = threading.Event()
# --- helpers ---
def log(name: str, msg: str) -> None:
timestamp = f"{datetime.now():%Y-%m-%d %H:%M:%S}"
print(f"[{timestamp}] [{name}] {msg}", flush=True)
def handle_stop(signum, frame) -> None:
log("watcher", "stop requested, finishing current repo...")
STOP.set()
def run(
cmd: list[str],
cwd: Path | None = None,
timeout: float = 10,
env: dict | None = None,
) -> str:
if env:
env = {**os.environ, **env}
try:
result = subprocess.run(
cmd, cwd=cwd, capture_output=True, text=True, timeout=timeout, env=env
)
except subprocess.TimeoutExpired:
msg = f"{' '.join(cmd)} timed out after {timeout}s"
raise RuntimeError(redact(msg)) from None
if result.returncode != 0:
msg = f"{' '.join(cmd)} failed:\n{result.stderr.strip()}"
raise RuntimeError(redact(msg))
return result.stdout.strip()
def redact(text: str) -> str:
return re.sub(r"https://[^@/\s]+@", "https://***@", text)
# --- git ---
def git_auth_env(repo: dict) -> dict | None:
"""Env vars that make git send the token as an auth header.
Keeps the token out of the command line (visible in `ps`) and out of .git/config.
"""
token_env = repo.get("token_env")
if not token_env:
return None
token = os.environ.get(token_env)
if not token:
raise RuntimeError(f"env var {token_env} is not set")
if not repo["url"].startswith("https://"):
raise RuntimeError("token auth only works with https:// URLs")
# same scheme GitHub Actions uses; Gitea accepts it too
basic = base64.b64encode(f"x-access-token:{token}".encode()).decode()
return {
"GIT_CONFIG_COUNT": "1",
"GIT_CONFIG_KEY_0": "http.extraHeader",
"GIT_CONFIG_VALUE_0": f"Authorization: Basic {basic}",
}
def remote_hash(url: str, branch: str, env: dict | None = None) -> str:
out = run(["git", "ls-remote", url, f"refs/heads/{branch}"], env=env)
if not out:
raise RuntimeError(f"branch '{branch}' not found")
return out.split()[0]
def local_hash(path: Path) -> str:
return run(["git", "rev-parse", "HEAD"], cwd=path)
def clone(url: str, path: Path, branch: str, env: dict | None = None) -> None:
run(
["git", "clone", "--branch", branch, "--depth", "1", url, str(path)],
timeout=GIT_TIMEOUT,
env=env,
)
def update(path: Path, branch: str, env: dict | None = None) -> None:
# explicit refspec so origin/<branch> exists even if the branch changed since the clone
refspec = f"+refs/heads/{branch}:refs/remotes/origin/{branch}"
run(
["git", "fetch", "--depth", "1", "origin", refspec],
cwd=path,
timeout=GIT_TIMEOUT,
env=env,
)
run(["git", "reset", "--hard", f"origin/{branch}"], cwd=path)
# --- 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 <name> [-f <file> [-f <override>]]"""
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,
path: Path | None = None,
compose_file: str | None = None,
timeout: float = COMPOSE_TIMEOUT,
):
"""Build and run: docker compose -p <name> [-f <file>] <args...>"""
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/<name>/* 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(
name,
"up",
"-d",
"--build",
"--remove-orphans",
path=path,
compose_file=compose_file,
timeout=DEPLOY_TIMEOUT,
)
log(name, "deployed ✓")
def stop(name, path, compose_file):
log(name, "stopping...")
compose(name, "down", path=path, compose_file=compose_file)
log(name, "stopped")
def pull_image(name, path, compose_file):
return compose(
name,
"pull",
"--ignore-buildable",
path=path,
compose_file=compose_file,
timeout=DEPLOY_TIMEOUT,
)
def status(name, path, compose_file):
out = compose(
name, "ps", "--all", "--format", "json", path=path, compose_file=compose_file
)
if not out:
return []
if out.startswith("["):
return json.loads(out)
return [json.loads(line) for line in out.splitlines()]
def logs(name, path, compose_file, tail: int = 50):
return compose(
name, "logs", "--tail", str(tail), path=path, compose_file=compose_file
)
def restart(name, path, compose_file):
compose(name, "restart", path=path, compose_file=compose_file)
log(name, "restarted")
# -- core logic ---
class DeployFailed(Exception):
"""Syncing or deploying a specific commit failed; retried with backoff."""
def __init__(self, commit: str, cause: Exception):
super().__init__(str(cause))
self.commit = commit
def check_repo(repo, state: dict) -> dict:
"""Sync one repo. Returns {"commit", "deployed", "skipped"}; errors propagate to the caller."""
name = repo["name"]
path = STACKS_DIR / name
url = repo["url"]
branch = repo["branch"]
compose_file = repo["compose_file"]
current = state.get(name, {})
env = git_auth_env(repo)
remote = remote_hash(url, branch, env)
if current.get("failed_commit") == remote and time.time() < current.get(
"retry_at", 0
):
return {"commit": current.get("commit"), "deployed": False, "skipped": True}
cloned = (path / ".git").exists()
if cloned:
# keep origin in sync with the config; also strips tokens left in old clones' URLs
run(["git", "remote", "set-url", "origin", url], cwd=path)
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(
name, "up", "-d", "--remove-orphans", path=path, compose_file=compose_file
)
return {"commit": remote, "deployed": False, "skipped": False}
try:
if not cloned:
log(name, "not cloned yet, cloning...")
shutil.rmtree(path, ignore_errors=True)
clone(url, path, branch, env)
else:
local = local_hash(path)
if local != remote:
log(name, f"update found {local[:7]} -> {remote[:7]}")
update(path, branch, env)
deploy(name, path, compose_file, repo["pull_image"])
except Exception as e:
raise DeployFailed(remote, e) from e
return {"commit": local_hash(path), "deployed": True, "skipped": False}
def remove_stack(name: str, state: dict) -> bool:
"""Stop a stack that was removed from the config. Returns True once it's gone.
The stack's folder is left on disk, since it may hold bind-mounted data.
"""
path = STACKS_DIR / name
if path.exists():
try:
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:
return yaml.safe_load(f) or {}
def normalize(raw, defaults: dict) -> dict:
if not isinstance(raw, dict):
raise ValueError(f"repo entry is not a mapping: {raw!r}")
repo = {**defaults, **raw}
for key in ("name", "url"):
if not repo.get(key):
raise ValueError(f"repo entry missing '{key}': {raw}")
if not NAME_RE.match(str(repo["name"])):
raise ValueError(
f"invalid name '{repo['name']}': use lowercase letters, digits, '-' and '_'"
)
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():
return {}
try:
with open(STATE_PATH) as f:
return json.load(f)
except (json.JSONDecodeError, OSError) as e:
log("watcher", f"state file unreadable, starting fresh: {e}")
return {}
def save_state(state: dict) -> None:
# write to a temp file then rename, so a crash mid-write can't corrupt it
tmp = STATE_PATH.with_suffix(".tmp")
tmp.write_text(json.dumps(state, indent=2))
tmp.replace(STATE_PATH)
def record(state: dict, name: str, **fields) -> None:
# in memory only; main() saves once per loop
state.setdefault(name, {}).update(fields)
# --- requests (from cli.py and the website) ---
#
# A request is a JSON file in REQUEST_DIR: {"action": ..., "repo": <name>, ...}
# 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)
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 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
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 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:
"""Sleep until the next round, waking early on stop or a check request."""
deadline = time.time() + seconds
while not STOP.is_set() and time.time() < deadline:
if has_requests():
return
STOP.wait(min(1, max(0, deadline - time.time())))
# --- 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()
process_requests(state)
checked = deployed = errors = 0
try:
config = load_config()
except Exception as e:
log("watcher", f"can't read config: {e}")
wait_for_next_round(CHECK_INTERVAL)
continue
defaults = config.get("defaults") or {}
entries = config.get("repos") or []
seen: set[str] = set()
config_ok = True
for i, raw in enumerate(entries):
if STOP.is_set(): # don't start another repo
break
label = (
raw.get("name")
if isinstance(raw, dict) and raw.get("name")
else f"repos[{i}]"
)
try:
repo = normalize(raw, defaults)
except ValueError as e:
log(str(label), f"invalid entry, skipped: {e}")
config_ok = False
continue
name = repo["name"]
if name in seen:
log(name, f"duplicate name, repos[{i}] skipped")
config_ok = False
continue
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)
record(state, name, last_check=now)
if result["skipped"]:
continue
record(
state,
name,
status="ok",
error=None,
commit=result["commit"],
compose_file=repo["compose_file"],
failed_commit=None,
failures=0,
retry_at=None,
)
if result["deployed"]:
record(state, name, last_deploy=now)
deployed += 1
except DeployFailed as e:
errors += 1
prev = state.get(name, {})
failures = (
prev.get("failures", 0) + 1
if prev.get("failed_commit") == e.commit
else 1
)
delay = min(CHECK_INTERVAL * 2 ** (failures - 1), MAX_BACKOFF)
log(
name,
f"deploy of {e.commit[:7]} failed ({failures}x), retrying in {delay}s: {e}",
)
record(
state,
name,
last_check=now,
status="error",
error=str(e),
failed_commit=e.commit,
failures=failures,
retry_at=time.time() + delay,
)
except Exception as e:
errors += 1
log(name, f"error: {e}")
record(state, name, last_check=now, status="error", error=str(e))
# stop stacks removed from the config. Skipped when the config has a bad
# 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 and n != SELF.get("project")]:
if remove_stack(old, state):
log(old, "removed from config, stack stopped")
del state[old]
elif not config_ok:
removed = [n for n in state if n not in seen]
if removed:
log(
"watcher",
f"config has invalid entries, not stopping: {', '.join(removed)}",
)
elapsed = time.time() - round_start
if deployed or errors:
log(
"watcher",
f"round done: {checked} repos, {deployed} deployed, "
f"{errors} errors ({elapsed:.1f}s)",
)
if not STOP.is_set():
check_self()
try:
save_state(state)
except OSError as e:
log("watcher", f"can't save state: {e}")
wait_for_next_round(max(0, CHECK_INTERVAL - elapsed))
log("watcher", "stopped")
if __name__ == "__main__":
main()
+470
View File
@@ -0,0 +1,470 @@
#!/usr/bin/env python3
"""
gitops-watcher web UI.
Runs as its own container. It never touches Docker: it only
- READS repos.yml, state.json and the clones (to show status + git files)
- WRITES request files (data/requests/) -> the watcher acts on them
- WRITES local files (data/local/<repo>) -> .env, overrides, etc.
"""
import hashlib
import hmac
import json
import os
import re
import secrets
import sys
from datetime import datetime
from pathlib import Path
import yaml
from flask import (Flask, abort, flash, jsonify, redirect, render_template,
request, session, url_for)
# 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 ----------
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
MAX_FILE = 256 * 1024 # biggest file the editor will open/save
SAFE_REPO = re.compile(r"^[a-z0-9][a-z0-9_-]{0,62}$") # compose project names are lowercase
SAFE_FILE = re.compile(r"^[A-Za-z0-9._-]{1,100}$") # no slashes = no ../ tricks
SAFE_BRANCH = re.compile(r"^[A-Za-z0-9._/-]{1,100}$")
SAFE_URL = re.compile(r"^https?://[^\s@]+$") # no "@" = no tokens pasted into URLs
app = Flask(__name__)
app.secret_key = os.environ.get("SECRET_KEY") or secrets.token_hex(32)
app.config["MAX_CONTENT_LENGTH"] = MAX_FILE + 64 * 1024
# ---------- reading data ----------
def load_json(path: Path, default):
try:
return json.loads(path.read_text())
except (OSError, ValueError):
return default
def load_repos() -> list[dict]:
"""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):
return []
defaults = config.get("defaults") or {}
repos = []
for raw in config.get("repos") or []:
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:
return repo
abort(404, f"no repo named {name!r}")
def pending_requests() -> dict[str, str]:
"""{repo name: action} for requests the watcher hasn't processed yet."""
pending = {}
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", "?"))
return pending
# ---------- writing requests ----------
def write_atomic(path: Path, text: str, mode: int | None = None) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_name(path.name + ".tmp")
tmp.write_text(text)
if mode is not None:
os.chmod(tmp, mode)
os.replace(tmp, path)
# ---------- files ----------
def safe_path(base: Path, filename: str) -> Path:
"""Join base + filename, refusing anything that could escape base."""
if not SAFE_FILE.match(filename) or filename in (".", ".."):
abort(400, "bad file name")
path = (base / filename).resolve()
if path.parent != base.resolve():
abort(400, "bad file name")
return path
def is_secret(filename: str) -> bool:
return filename == ".env" or filename.endswith(".env")
def mask(text: str) -> str:
lines = []
for line in text.splitlines():
i = line.find("=")
if i > 0 and not line.lstrip().startswith("#"):
line = line[: i + 1] + "••••••••"
lines.append(line)
return "\n".join(lines) + ("\n" if text.endswith("\n") else "")
def env_keys(text: str) -> set[str]:
keys = set()
for line in text.splitlines():
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
if line.startswith("export "):
line = line[len("export "):]
key = line.split("=", 1)[0].strip()
if key:
keys.add(key)
return keys
def missing_env(name: str) -> list[str]:
example = STACKS_DIR / name / ".env.example"
env = LOCAL_DIR / name / ".env"
if not example.is_file() or not env.is_file():
return []
return sorted(env_keys(example.read_text()) - env_keys(env.read_text()))
def local_files(name: str) -> list[str]:
folder = LOCAL_DIR / name
if not folder.is_dir():
return []
return sorted(p.name for p in folder.iterdir() if p.is_file() and SAFE_FILE.match(p.name))
def git_files(repo: dict) -> list[str]:
"""Readable text files in the root of the clone (not the copied-in local ones)."""
root = STACKS_DIR / repo["name"]
if not root.is_dir():
return []
skip = set(local_files(repo["name"]))
names = []
for p in root.iterdir():
if (p.is_file() and p.name not in skip and SAFE_FILE.match(p.name)
and (not p.name.startswith(".") or p.name == ".env.example")
and p.stat().st_size <= MAX_FILE):
names.append(p.name)
compose = compose_file_of(repo)
return sorted(names, key=lambda n: (n != compose, n.lower()))
def read_text(path: Path) -> str:
try:
return path.read_text(encoding="utf-8")
except UnicodeDecodeError:
abort(415, "not a text file")
# ---------- CSRF (stops other websites from clicking your buttons) ----------
def csrf_token() -> str:
if "csrf" not in session:
session["csrf"] = secrets.token_hex(16)
return session["csrf"]
app.jinja_env.globals["csrf_token"] = csrf_token
@app.before_request
def check_csrf():
# webhooks can't send our token; they're checked by their HMAC signature instead
if request.method == "POST" and not request.path.startswith("/webhook/"):
sent = request.form.get("csrf") or request.headers.get("X-CSRF-Token") or ""
expected = session.get("csrf", "")
if not expected or not secrets.compare_digest(sent, expected): # no session = no token = reject
abort(400, "invalid or missing CSRF token: reload the page and try again")
@app.errorhandler(400)
@app.errorhandler(403)
@app.errorhandler(404)
@app.errorhandler(413)
@app.errorhandler(415)
def api_errors(e):
if request.path.startswith(("/api/", "/webhook/")):
return jsonify(error=e.description), e.code
return e
# ---------- template helpers ----------
@app.template_filter("ago")
def ago(iso: str | None) -> str:
if not iso:
return "-"
try:
secs = int((datetime.now() - datetime.fromisoformat(iso)).total_seconds())
except ValueError:
return iso
if secs < 10:
return "just now"
for unit, size in (("d", 86400), ("h", 3600), ("m", 60)):
if secs >= size:
return f"{secs // size}{unit} ago"
return f"{secs}s ago"
@app.template_filter("pretty")
def pretty(iso: str | None) -> str:
return iso.replace("T", " ") if iso else ""
# ---------- pages ----------
ORDER = {"error": 0, "setup": 1, "ok": 2, "new": 3, "paused": 4}
@app.get("/")
def index():
repos = load_repos()
state = load_json(STATE_PATH, {})
pending = pending_requests()
rows = []
for repo in repos:
name = repo["name"]
info = state.get(name, {})
status = "paused" if repo["paused"] else info.get("status", "new")
if status not in ORDER:
status = "error"
rows.append({
"name": name,
"status": status,
"commit": (info.get("commit") or "")[:7],
"last_check": info.get("last_check"),
"last_deploy": info.get("last_deploy"),
"error": info.get("error") if status == "error" else None,
"missing_env": missing_env(name),
"busy": pending.get(name),
})
# repos that are queued to be added but not in repos.yml yet
known = {r["name"] for r in rows}
for name, action in pending.items():
if action == "add" and name not in known:
rows.append({"name": name, "status": "new", "commit": "", "last_check": None,
"last_deploy": None, "error": None, "missing_env": [], "busy": "add"})
rows.sort(key=lambda r: (ORDER[r["status"]], r["name"]))
counts = {s: sum(1 for r in rows if r["status"] == s) for s in ORDER}
checks = [r["last_check"] for r in rows if r["last_check"]]
last_round = max(checks) if checks else None
next_in, stale = None, False
if last_round:
since = (datetime.now() - datetime.fromisoformat(last_round)).total_seconds()
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),
next_in=next_in, stale=stale, last_round=last_round,
interval=CHECK_INTERVAL, token_envs=TOKEN_ENVS)
# ---------- actions (all become request files) ----------
@app.post("/repos/<name>/<action>")
def repo_action(name: str, action: str):
if action not in ("deploy", "stop", "start"):
abort(404)
get_repo(name)
queue_request(action, name)
flash(f"queued: {action} {name} · runs on the watcher's next round")
return redirect(url_for("index"))
@app.post("/repos/<name>/remove")
def remove_repo(name: str):
get_repo(name)
if request.form.get("confirm", "") != name:
flash("the name didn't match, so nothing was removed", "error")
return redirect(url_for("index"))
wipe = request.form.get("wipe") == "on"
queue_request("remove", name, wipe_volumes=wipe)
flash(f"queued: remove {name}" + (" + delete its data" if wipe else ""))
return redirect(url_for("index"))
@app.post("/repos")
def add_repo():
f = request.form
name = f.get("name", "").strip()
url = f.get("url", "").strip()
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 = []
if not SAFE_REPO.match(name):
problems.append("name: lowercase letters, numbers, - and _ only")
elif any(r["name"] == name for r in load_repos()) or pending_requests().get(name) == "add":
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 branch and not SAFE_BRANCH.match(branch):
problems.append("branch name has invalid characters")
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")
if problems:
for p in problems:
flash(p, "error")
return redirect(url_for("index"))
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_image") != "on":
entry["pull_image"] = False # the watcher's default is True
if f.get("deploy_now") != "on":
entry["paused"] = True
queue_request("add", name, entry=entry)
flash(f"queued: add {name}")
return redirect(url_for("index"))
# ---------- 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=compose_file_of(repo),
missing_env=missing_env(name))
@app.get("/api/repos/<name>/files/<kind>/<filename>")
def read_file(name: str, kind: str, filename: str):
repo = get_repo(name)
if kind == "local":
base = LOCAL_DIR / name
elif kind == "git":
if filename not in git_files(repo):
abort(404, "not a viewable repo file")
base = STACKS_DIR / name
else:
abort(404)
path = safe_path(base, filename)
if not path.is_file():
abort(404, "file not found")
text = read_text(path)
secret = is_secret(filename)
reveal = request.args.get("reveal") == "1"
return jsonify(content=mask(text) if secret and not reveal else text,
secret=secret, masked=secret and not reveal)
@app.post("/api/repos/<name>/files/<filename>")
def save_file(name: str, filename: str):
repo = get_repo(name)
data = request.get_json(silent=True) or {}
content = data.get("content")
if not isinstance(content, str):
abort(400, "missing content")
if len(content.encode()) > MAX_FILE:
abort(413, "file too large")
if filename.endswith((".yml", ".yaml")):
if "\t" in content:
return jsonify(error="YAML can't use tabs for indentation"), 400
try:
yaml.safe_load(content)
except yaml.YAMLError as e:
return jsonify(error=f"invalid YAML: {e}"), 400
path = safe_path(LOCAL_DIR / name, filename)
is_new = not path.exists()
shadows = is_new and filename in git_files(repo) # check BEFORE writing: git_files hides local names
write_atomic(path, content, mode=0o600 if is_secret(filename) else 0o644)
if data.get("redeploy"):
queue_request("deploy", name)
return jsonify(ok=True, missing_env=missing_env(name), shadows_git=shadows)
# ---------- webhooks (GitHub / Gitea call this on every push) ----------
def valid_signature(body: bytes) -> bool:
"""GitHub sends X-Hub-Signature-256: sha256=<hex>, Gitea sends X-Gitea-Signature: <hex>."""
if not WEBHOOK_SECRET:
return False
expected = hmac.new(WEBHOOK_SECRET.encode(), body, hashlib.sha256).hexdigest()
sent = (request.headers.get("X-Hub-Signature-256", "").removeprefix("sha256=")
or request.headers.get("X-Gitea-Signature", ""))
return bool(sent) and hmac.compare_digest(sent, expected)
@app.post("/webhook/<name>")
def webhook(name: str):
if not valid_signature(request.get_data()): # before get_repo, so strangers can't probe repo names
abort(403, "bad or missing signature")
repo = get_repo(name)
event = request.headers.get("X-GitHub-Event") or request.headers.get("X-Gitea-Event")
if event == "ping":
return jsonify(ok=True, msg="pong")
if event != "push":
return jsonify(ok=True, ignored=f"event {event}")
ref = (request.get_json(silent=True) or {}).get("ref", "")
if ref != f"refs/heads/{repo['branch']}":
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 check
queue_request("check", name) # deploys if the branch has a new commit
return jsonify(ok=True, queued="check"), 202
if __name__ == "__main__":
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", "5000")))
+387
View File
@@ -0,0 +1,387 @@
/* gitops-watcher web UI
- buttons that change things are plain <form method="post">, so they work without JS
- this file adds: dialogs, the file editor, toasts, auto-refresh, countdown, rain */
const $ = s => document.querySelector(s);
const $$ = s => document.querySelectorAll(s);
const CSRF = document.querySelector('meta[name="csrf-token"]').content;
const esc = s => String(s).replace(/[&<>"']/g, c =>
({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
/* ---------- toasts ---------- */
function toast(html, kind = "") {
const t = document.createElement("div");
t.className = `toast ${kind}`;
t.innerHTML = html;
$("#toasts").appendChild(t);
setTimeout(() => t.remove(), 4000);
}
$$("#toasts .toast").forEach(t => setTimeout(() => t.remove(), 4500)); // flashed from Flask
/* ---------- dialogs ---------- */
let lastFocus = null;
function openModal(sel, focusSel) {
lastFocus = document.activeElement;
$(sel).classList.add("open");
if (focusSel) setTimeout(() => $(focusSel)?.focus(), 0);
}
function closeModals() {
if ($("#files-drawer").classList.contains("open") && isDirty() &&
!confirm("discard unsaved changes?")) return;
$$(".backdrop.open").forEach(m => m.classList.remove("open"));
lastFocus?.focus();
}
const anyOpen = () => !!document.querySelector(".backdrop.open");
document.addEventListener("click", e => {
const opener = e.target.closest("[data-open]");
if (opener) { openModal(opener.dataset.open, opener.dataset.focus); return; }
if (e.target.closest("[data-close]")) { closeModals(); return; }
if (e.target.classList.contains("backdrop")) { closeModals(); return; }
const rm = e.target.closest("[data-remove]");
if (rm) { openRemove(rm.dataset.remove); return; }
const files = e.target.closest("[data-files]");
if (files) { openFiles(files.dataset.files); return; }
});
document.addEventListener("keydown", e => { if (e.key === "Escape" && anyOpen()) closeModals(); });
/* ---------- remove: type the name to enable the button ---------- */
let removing = null;
function openRemove(name) {
removing = name;
$$(".rm-name").forEach(el => el.textContent = name);
$("#remove-form").action = `/repos/${encodeURIComponent(name)}/remove`;
$("#rm-confirm").value = "";
$("#rm-wipe").checked = false;
$("#rm-submit").disabled = true;
$("#rm-submit").textContent = "remove";
openModal("#remove-modal", "#rm-confirm");
}
$("#rm-confirm")?.addEventListener("input", e => { $("#rm-submit").disabled = e.target.value !== removing; });
$("#rm-wipe")?.addEventListener("change", e => {
$("#rm-submit").textContent = e.target.checked ? "remove + delete data" : "remove";
});
/* =========================================================
FILE EDITOR
========================================================= */
let fd = { repo: null, kind: null, file: null, original: "", secret: false, revealed: false,
list: { local: [], git: [], missing_env: [] } };
const isSecret = f => f === ".env" || f.endsWith(".env");
const api = (path, opts = {}) => fetch(path, {
...opts,
headers: { "X-CSRF-Token": CSRF, "Content-Type": "application/json", ...(opts.headers || {}) },
}).then(async res => {
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || `request failed (${res.status})`);
return data;
});
const repoUrl = () => `/api/repos/${encodeURIComponent(fd.repo)}/files`;
async function openFiles(name) {
fd = { repo: name, kind: null, file: null, original: "", secret: false, revealed: false,
list: { local: [], git: [], missing_env: [] } };
$("#fd-repo").textContent = name;
$("#fd-text").value = "";
openModal("#files-drawer");
await refreshList();
if (fd.list.local.includes(".env")) selectFile("local", ".env");
else if (fd.list.git.length) selectFile("git", fd.list.git[0]);
else showEmpty();
}
async function refreshList() {
try { fd.list = await api(repoUrl()); }
catch (err) { toast(esc(err.message), "error"); }
renderList();
}
function renderList() {
const { local, git, missing_env } = fd.list;
const btn = (kind, file) => {
const active = fd.kind === kind && fd.file === file ? "active" : "";
let tag = "";
if (active && isDirty()) tag = `<span class="dirty">●</span>`;
else if (kind === "local" && file === ".env" && missing_env.length) tag = `<span class="warnmark">⚠ ${missing_env.length} missing</span>`;
else if (kind === "git") tag = `<span class="lock">read-only</span>`;
return `<button class="file ${active}" data-kind="${kind}" data-file="${esc(file)}" title="${esc(file)}"><span class="fn">${esc(file)}</span>${tag}</button>`;
};
const hasEnv = local.includes(".env");
const hasExample = git.includes(".env.example");
const hasOverride = local.includes("docker-compose.override.yml");
$("#fd-list").innerHTML = `
<div class="file-group">LOCAL<small>yours · kept across pulls</small></div>
${local.map(f => btn("local", f)).join("")}
${!hasEnv && hasExample ? `<button class="file ghost" data-new=".env" data-from-example>+ .env from example</button>` : ""}
${!hasEnv && !hasExample ? `<button class="file ghost" data-new=".env">+ .env</button>` : ""}
${hasOverride ? "" : `<button class="file ghost" data-new="docker-compose.override.yml">+ compose override</button>`}
<button class="file ghost" data-new="?">+ new file</button>
<div class="file-group">FROM GIT<small>overwritten on every pull</small></div>
${git.length ? git.map(f => btn("git", f)).join("") : `<div class="file-group"><small>not cloned yet</small></div>`}
`;
}
function showEmpty() {
Object.assign(fd, { kind: null, file: null, original: "" });
$("#fd-fname").textContent = "";
$("#fd-badges").innerHTML = "";
$("#fd-banner").innerHTML = `<div class="editor-loading">no files yet · create one from the list</div>`;
$("#fd-warn").innerHTML = "";
$("#fd-text").value = "";
$("#fd-text").readOnly = true;
updateGutter(); updateFoot(); renderList();
}
async function selectFile(kind, file, { reveal = false } = {}) {
if (isDirty() && !confirm("discard unsaved changes?")) return;
let data;
try {
data = await api(`${repoUrl()}/${kind}/${encodeURIComponent(file)}${reveal ? "?reveal=1" : ""}`);
} catch (err) { toast(esc(err.message), "error"); return; }
Object.assign(fd, { kind, file, original: data.content, secret: data.secret, revealed: !data.masked });
$("#fd-fname").textContent = file;
$("#fd-badges").innerHTML =
(kind === "git" ? `<span class="badge git">from git</span>` : `<span class="badge local">local</span>`) +
(data.secret ? ` <span class="badge secret">secrets</span>` : "");
const ta = $("#fd-text");
ta.value = data.content;
ta.readOnly = kind === "git" || data.masked;
if (kind === "git") {
const isCompose = file === fd.list.compose_file || /^docker-compose.*\.ya?ml$|^compose.*\.ya?ml$/.test(file);
$("#fd-banner").innerHTML = `
<div class="banner info">
<span>this file comes from the repo. edits here would be wiped by the next pull.
change it in git, or override it locally.</span>
${isCompose ? `<button class="btn icon" data-new="docker-compose.override.yml">+ create override</button>` : ""}
</div>`;
} else if (data.masked) {
$("#fd-banner").innerHTML = `
<div class="banner secret">
<span>values are hidden. only reveal them on a screen nobody else can see.</span>
<button class="btn icon" id="fd-reveal">reveal + edit</button>
</div>`;
$("#fd-reveal").addEventListener("click", () => selectFile(kind, file, { reveal: true }).then(() => ta.focus()));
} else if (data.secret) {
$("#fd-banner").innerHTML = `
<div class="banner secret"><span>values visible · editing</span>
<button class="btn icon" id="fd-hide">hide</button></div>`;
$("#fd-hide").addEventListener("click", () => selectFile(kind, file));
} else {
$("#fd-banner").innerHTML = "";
}
updateGutter(); updateFoot(); renderList(); renderWarn();
}
/* ---------- missing .env keys (names only, never values) ---------- */
function envKeys(text) {
const keys = [];
for (let line of text.split("\n")) {
line = line.trim();
if (!line || line.startsWith("#") || !line.includes("=")) continue;
keys.push(line.replace(/^export\s+/, "").split("=")[0].trim());
}
return keys;
}
let exampleCache = { repo: null, text: null };
async function exampleText() {
if (exampleCache.repo === fd.repo) return exampleCache.text;
let text = null;
if (fd.list.git.includes(".env.example")) {
try { text = (await api(`${repoUrl()}/git/.env.example`)).content; } catch { /* ignore */ }
}
exampleCache = { repo: fd.repo, text };
return text;
}
async function renderWarn() {
const box = $("#fd-warn");
if (fd.kind !== "local" || fd.file !== ".env") { box.innerHTML = ""; return; }
const example = await exampleText();
if (!example) { box.innerHTML = ""; return; }
const have = new Set(envKeys(fd.revealed ? $("#fd-text").value : fd.original));
const miss = envKeys(example).filter(k => !have.has(k));
box.innerHTML = miss.length ? `
<div class="banner warn">
<span>missing from .env (found in .env.example): ${miss.map(k => `<code>${esc(k)}</code>`).join(", ")}</span>
<button class="btn icon" id="fd-add-missing">+ add missing keys</button>
</div>` : "";
if (miss.length) $("#fd-add-missing").addEventListener("click", () => addMissing(miss, example));
}
async function addMissing(miss, example) {
if (!fd.revealed) await selectFile("local", ".env", { reveal: true });
const want = new Set(miss);
const lines = example.split("\n").filter(l => {
const t = l.trim();
return t && !t.startsWith("#") && t.includes("=") && want.has(t.replace(/^export\s+/, "").split("=")[0].trim());
});
const ta = $("#fd-text");
ta.value = ta.value.replace(/\n*$/, "\n") + `\n# added from .env.example: fill these in\n${lines.join("\n")}\n`;
ta.focus(); ta.scrollTop = ta.scrollHeight;
updateGutter(); updateFoot(); renderList(); renderWarn();
toast(`added ${miss.length} key${miss.length > 1 ? "s" : ""} with example values <span class="muted">· fill in, then save</span>`);
}
/* ---------- editor state ---------- */
function isDirty() {
if (!fd.file || fd.kind === "git" || !fd.revealed) return false;
return $("#fd-text").value !== fd.original;
}
function updateGutter() {
const n = $("#fd-text").value.split("\n").length;
$("#fd-gutter").textContent = Array.from({ length: n }, (_, i) => i + 1).join("\n");
}
function updateFoot() {
const dirty = isDirty();
$("#fd-btns").style.display = fd.kind === "local" ? "" : "none";
$("#fd-state").className = "state" + (dirty ? " dirty" : "");
$("#fd-state").textContent =
!fd.file ? "" :
fd.kind === "git" ? "read-only · edit this in the repo" :
!fd.revealed ? "hidden · reveal to edit" :
dirty ? "● unsaved changes" : "no changes";
["#fd-discard", "#fd-save", "#fd-save-deploy"].forEach(s => $(s).disabled = !dirty);
}
const ta = $("#fd-text");
if (ta) {
ta.addEventListener("scroll", () => { $("#fd-gutter").scrollTop = ta.scrollTop; });
ta.addEventListener("input", () => { updateGutter(); updateFoot(); renderList(); renderWarn(); });
ta.addEventListener("keydown", e => {
if (e.key === "Tab" && !ta.readOnly) {
e.preventDefault();
ta.setRangeText(" ", ta.selectionStart, ta.selectionEnd, "end");
updateFoot();
}
if ((e.ctrlKey || e.metaKey) && e.key === "s") { e.preventDefault(); if (isDirty()) save(false); }
});
}
async function save(redeploy) {
const content = $("#fd-text").value;
try {
const res = await api(`${repoUrl()}/${encodeURIComponent(fd.file)}`, {
method: "POST", body: JSON.stringify({ content, redeploy }),
});
fd.original = content;
fd.list.missing_env = res.missing_env;
toast(redeploy
? `saved ${esc(fd.file)} <span class="muted">· redeploy queued</span>`
: `saved ${esc(fd.file)} <span class="muted">· takes effect on next deploy</span>`, "ok");
updateFoot(); renderList(); renderWarn();
} catch (err) { toast(esc(err.message), "error"); }
}
$("#fd-save")?.addEventListener("click", () => save(false));
$("#fd-save-deploy")?.addEventListener("click", () => save(true));
$("#fd-discard")?.addEventListener("click", () => {
$("#fd-text").value = fd.original;
updateGutter(); updateFoot(); renderList(); renderWarn();
});
/* ---------- file list clicks + creating files ---------- */
const OVERRIDE_TEMPLATE = `# merged on top of the repo's compose file
# only list what you want to change, for example:
services:
web:
ports:
- "8080:80"
`;
document.addEventListener("click", async e => {
const f = e.target.closest(".file[data-kind]");
if (f) { selectFile(f.dataset.kind, f.dataset.file); return; }
const n = e.target.closest("[data-new]");
if (!n) return;
let file = n.dataset.new;
if (file === "?") {
file = (prompt("file name (e.g. app.env, nginx.conf)") || "").trim();
if (!file) return;
}
if (!/^[A-Za-z0-9._-]{1,100}$/.test(file) || file === "." || file === "..") {
toast("use letters, numbers, dot, dash or underscore only", "error"); return;
}
if (fd.list.local.includes(file)) { selectFile("local", file); return; }
let content = "";
if (file === "docker-compose.override.yml") content = OVERRIDE_TEMPLATE;
if ("fromExample" in n.dataset) content = (await exampleText()) || "";
try {
const res = await api(`${repoUrl()}/${encodeURIComponent(file)}`, {
method: "POST", body: JSON.stringify({ content }),
});
toast(`created ${esc(file)} <span class="muted">· local</span>` +
(res.shadows_git ? `<br><span class="muted">this replaces the repo's ${esc(file)} on every deploy</span>` : ""), "ok");
await refreshList();
exampleCache = { repo: null, text: null };
selectFile("local", file, { reveal: isSecret(file) });
} catch (err) { toast(esc(err.message), "error"); }
});
/* ---------- 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 () {
const el = $("#countdown");
if (!el) return;
let secs = parseInt(el.dataset.seconds, 10) || 0;
const show = () => {
el.textContent = secs > 0 ? `${Math.floor(secs / 60)}:${String(secs % 60).padStart(2, "0")}` : "any moment";
};
show();
setInterval(() => { if (secs > 0) secs--; show(); }, 1000);
})();
/* ---------- rain ---------- */
(function () {
if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
const canvas = $("#rain"), ctx = canvas.getContext("2d");
let drops = [];
function resize() {
canvas.width = innerWidth * devicePixelRatio;
canvas.height = innerHeight * devicePixelRatio;
ctx.setTransform(devicePixelRatio, 0, 0, devicePixelRatio, 0, 0);
drops = Array.from({ length: Math.floor(innerWidth / 9) }, () => ({
x: Math.random() * innerWidth, y: Math.random() * innerHeight,
len: 8 + Math.random() * 14, speed: 2.5 + Math.random() * 4, alpha: 0.04 + Math.random() * 0.09,
}));
}
function tick() {
ctx.clearRect(0, 0, innerWidth, innerHeight);
for (const d of drops) {
ctx.strokeStyle = `rgba(124,183,232,${d.alpha})`;
ctx.beginPath(); ctx.moveTo(d.x, d.y); ctx.lineTo(d.x - 1, d.y + d.len); ctx.stroke();
d.y += d.speed;
if (d.y > innerHeight) { d.y = -d.len; d.x = Math.random() * innerWidth; }
}
requestAnimationFrame(tick);
}
addEventListener("resize", resize);
resize(); tick();
})();
+333
View File
@@ -0,0 +1,333 @@
/* gitops-watcher web UI */
:root {
--bg: #0b1017;
--surface: #111925;
--surface-2: #16202e;
--border: #1f2b3b;
--text: #d3dae3;
--muted: #6b7a8d;
--accent: #7cb7e8;
--accent-bg: #142536;
--ok: #6fcf97;
--error: #e07a7a;
--error-bg: #2a1619;
--warn: #e5b567;
--paused: #8796a8;
--radius: 6px;
--font: "JetBrains Mono", ui-monospace, SFMono-Regular, Menlo, monospace;
}
* { box-sizing: border-box; }
body {
margin: 0;
min-height: 100vh;
background: var(--bg);
color: var(--text);
font-family: var(--font);
font-size: 14px;
line-height: 1.5;
}
#rain { position: fixed; inset: 0; width: 100%; height: 100%; pointer-events: none; z-index: 0; }
.wrap { position: relative; z-index: 1; max-width: 1140px; margin: 0 auto; padding: 24px 16px 64px; }
/* ---------- buttons ---------- */
.btn {
font: inherit;
font-size: 13px;
color: var(--text);
background: var(--surface);
border: 1px solid var(--border);
border-radius: 4px;
padding: 6px 12px;
cursor: pointer;
transition: border-color .15s, color .15s, background .15s;
white-space: nowrap;
}
.btn:hover:not(:disabled) { border-color: var(--accent); color: var(--accent); }
.btn:disabled { opacity: .4; cursor: not-allowed; }
.btn.primary { background: var(--accent-bg); border-color: var(--accent); color: var(--accent); }
.btn.primary:hover:not(:disabled) { background: #1a3046; }
.btn.danger { color: var(--error); }
.btn.danger:hover:not(:disabled) { border-color: var(--error); color: var(--error); background: var(--error-bg); }
.btn.danger.solid { background: var(--error-bg); border-color: var(--error); }
.btn.icon { padding: 4px 9px; font-size: 12px; }
/* ---------- top bar ---------- */
.topbar {
display: flex; align-items: center; justify-content: space-between;
gap: 16px; flex-wrap: wrap;
padding-bottom: 16px; border-bottom: 1px solid var(--border);
}
.brand { font-weight: 700; font-size: 16px; color: var(--accent); letter-spacing: .02em; }
.brand span { color: var(--muted); font-weight: 400; }
.top-right { display: flex; align-items: center; gap: 16px; flex-wrap: wrap; }
.heartbeat { display: flex; align-items: center; gap: 8px; color: var(--muted); font-size: 13px; }
.heartbeat b { color: var(--text); font-weight: 500; }
.dot { width: 8px; height: 8px; border-radius: 50%; display: inline-block; flex: none; }
.dot.ok { background: var(--ok); box-shadow: 0 0 8px var(--ok); }
.dot.error { background: var(--error); box-shadow: 0 0 8px var(--error); }
.dot.warn { background: var(--warn); box-shadow: 0 0 8px var(--warn); }
.dot.paused { background: transparent; border: 1.5px solid var(--paused); }
.dot.busy { background: var(--accent); box-shadow: 0 0 8px var(--accent); animation: pulse 1s ease-in-out infinite; }
.heartbeat .dot { animation: pulse 2s ease-in-out infinite; }
@keyframes pulse { 50% { opacity: .3; } }
/* ---------- summary ---------- */
.summary { display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; margin: 20px 0; }
.stat { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); padding: 14px 16px; }
.stat .label { color: var(--muted); font-size: 12px; }
.stat .value { font-size: 22px; font-weight: 700; margin-top: 2px; }
.stat .value.ok { color: var(--ok); }
.stat .value.error { color: var(--error); }
.stat .value.paused { color: var(--paused); }
.stat.dim { opacity: .5; }
/* ---------- table ---------- */
.panel { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); overflow: hidden; }
table { width: 100%; border-collapse: collapse; }
th {
text-align: left; font-weight: 500; font-size: 12px; color: var(--muted);
padding: 12px 16px; border-bottom: 1px solid var(--border); white-space: nowrap;
}
th.actions-h { text-align: right; }
td { padding: 12px 16px; border-bottom: 1px solid var(--border); white-space: nowrap; vertical-align: middle; }
tr.repo { transition: background .15s, opacity .4s; }
tr.repo:hover { background: var(--surface-2); }
tr.repo.has-error { background: var(--error-bg); }
tr.repo.has-warn + tr.warn-row { box-shadow: inset 3px 0 0 var(--warn); }
tr.repo.has-error:hover { background: #321a1e; }
tr.repo.is-paused .name, tr.repo.is-paused .commit, tr.repo.is-paused .time { opacity: .5; }
tr.repo.leaving { opacity: 0; }
.name { font-weight: 500; }
.status { display: inline-flex; align-items: center; gap: 8px; }
.status.ok { color: var(--ok); }
.status.error { color: var(--error); }
.status.paused { color: var(--paused); }
.status.busy { color: var(--accent); }
.commit { color: var(--accent); text-decoration: none; }
.commit:hover { text-decoration: underline dotted; }
.time { color: var(--muted); }
.actions { display: flex; gap: 6px; justify-content: flex-end; }
tr.error-row td {
padding: 0 16px 14px 40px; background: var(--error-bg);
white-space: pre-wrap; word-break: break-word; color: var(--error); font-size: 12.5px;
}
tr.error-row .tree { color: var(--muted); }
.footer {
display: flex; justify-content: space-between; flex-wrap: wrap; gap: 8px;
margin-top: 12px; color: var(--muted); font-size: 12px;
}
/* ---------- modals ---------- */
.backdrop {
position: fixed; inset: 0; z-index: 10;
background: rgba(5, 8, 12, .72);
display: none; align-items: center; justify-content: center;
padding: 16px;
}
.backdrop.open { display: flex; }
.modal {
width: 100%; max-width: 480px;
background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius);
box-shadow: 0 20px 60px rgba(0,0,0,.5);
}
.modal.danger { border-color: #4a2328; }
.modal-head { padding: 16px 20px; border-bottom: 1px solid var(--border); font-weight: 700; }
.modal.danger .modal-head { color: var(--error); }
.modal-body { padding: 18px 20px; display: grid; gap: 14px; }
.modal-foot { padding: 14px 20px; border-top: 1px solid var(--border); display: flex; justify-content: flex-end; gap: 8px; }
.field { display: grid; gap: 6px; }
.field label { font-size: 12px; color: var(--muted); }
.field .hint { font-size: 11.5px; color: var(--muted); }
.row2 { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
input[type=text], select {
font: inherit; font-size: 13px; color: var(--text);
background: var(--bg); border: 1px solid var(--border); border-radius: 4px;
padding: 8px 10px; width: 100%;
}
input[type=text]:focus, select:focus { outline: none; border-color: var(--accent); }
input.invalid { border-color: var(--error); }
.check { display: flex; align-items: flex-start; gap: 10px; font-size: 13px; cursor: pointer; }
.check input { margin-top: 3px; accent-color: var(--accent); }
.check .sub { display: block; color: var(--muted); font-size: 11.5px; }
.check.danger input { accent-color: var(--error); }
.check.danger .warn-text { color: var(--error); }
.note { color: var(--muted); font-size: 12.5px; }
.note code { color: var(--text); }
.confirm-name { color: var(--text); font-weight: 700; }
/* ---------- toasts ---------- */
.toasts { position: fixed; right: 16px; bottom: 16px; z-index: 20; display: grid; gap: 8px; max-width: calc(100vw - 32px); }
.toast {
background: var(--surface-2); border: 1px solid var(--border); border-left: 3px solid var(--accent);
border-radius: 4px; padding: 10px 14px; font-size: 12.5px;
box-shadow: 0 8px 24px rgba(0,0,0,.4);
animation: in .2s ease-out;
}
.toast.ok { border-left-color: var(--ok); }
.toast.error { border-left-color: var(--error); }
.toast .muted { color: var(--muted); }
@keyframes in { from { transform: translateY(8px); opacity: 0; } }
/* ---------- clickable repo name ---------- */
.linkish {
font: inherit; color: inherit; background: none; border: 0; padding: 0;
cursor: pointer; text-align: left;
}
.linkish:hover .name { color: var(--accent); }
/* ---------- file drawer ---------- */
.backdrop.drawer-bd { justify-content: flex-end; align-items: stretch; padding: 0; }
.drawer {
width: 100%; max-width: 900px; height: 100%;
background: var(--surface); border-left: 1px solid var(--border);
display: flex; flex-direction: column;
animation: slide .2s ease-out;
}
@keyframes slide { from { transform: translateX(24px); opacity: 0; } }
.drawer-head {
display: flex; align-items: center; justify-content: space-between; gap: 12px;
padding: 16px 20px; border-bottom: 1px solid var(--border);
}
.drawer-head .title { font-weight: 700; }
.drawer-head .title span { color: var(--muted); font-weight: 400; }
.drawer-main { flex: 1; display: grid; grid-template-columns: 280px 1fr; min-height: 0; }
.file .fn { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.file .lock { white-space: nowrap; }
.file-list { border-right: 1px solid var(--border); padding: 14px 0; overflow-y: auto; }
.file-group { padding: 0 16px 6px; margin-top: 10px; font-size: 11px; color: var(--muted); letter-spacing: .04em; }
.file-group:first-child { margin-top: 0; }
.file-group small { display: block; letter-spacing: 0; font-size: 11px; opacity: .8; }
.file {
display: flex; align-items: center; gap: 8px; width: 100%;
font: inherit; font-size: 13px; color: var(--text); text-align: left;
background: none; border: 0; border-left: 2px solid transparent;
padding: 7px 16px; cursor: pointer;
}
.file:hover { background: var(--surface-2); }
.file.active { background: var(--accent-bg); border-left-color: var(--accent); color: var(--accent); }
.file .lock { color: var(--muted); font-size: 11px; margin-left: auto; }
.file .dirty { color: var(--warn); margin-left: auto; }
.file.ghost { color: var(--muted); }
.file.ghost:hover { color: var(--accent); }
.editor-pane { display: flex; flex-direction: column; min-width: 0; min-height: 0; }
.editor-bar {
display: flex; align-items: center; justify-content: space-between; gap: 10px; flex-wrap: wrap;
padding: 10px 16px; border-bottom: 1px solid var(--border);
}
.editor-bar .fname { font-weight: 500; }
.badge {
font-size: 11px; padding: 2px 7px; border-radius: 3px; border: 1px solid var(--border); color: var(--muted);
}
.badge.local { color: var(--ok); border-color: #24452f; }
.badge.git { color: var(--muted); }
.badge.secret { color: var(--warn); border-color: #4a3a1f; }
.banner {
padding: 10px 16px; font-size: 12.5px; border-bottom: 1px solid var(--border);
display: flex; gap: 12px; align-items: center; justify-content: space-between; flex-wrap: wrap;
}
.banner.info { background: #121c28; color: var(--muted); }
.banner.warn { background: #211b10; color: var(--warn); border-left: 3px solid var(--warn); }
.banner.warn code { color: var(--text); }
/* missing .env keys on the dashboard */
.warn-pill {
font-size: 11px; color: var(--warn); border: 1px solid #4a3a1f; border-radius: 3px;
padding: 1px 6px; margin-left: 8px;
}
tr.repo.has-warn { box-shadow: inset 3px 0 0 var(--warn); }
tr.warn-row td {
padding: 0 16px 12px 40px; color: var(--warn); font-size: 12.5px;
white-space: normal; border-bottom: 1px solid var(--border);
}
tr.warn-row .tree { color: var(--muted); }
tr.warn-row code { color: var(--text); }
tr.warn-row .fix {
font: inherit; color: var(--accent); background: none; border: 0; padding: 0; margin-left: 6px;
cursor: pointer; text-decoration: underline dotted;
}
.file .warnmark { color: var(--warn); margin-left: auto; font-size: 11px; }
.banner.secret { background: #211b10; color: var(--warn); }
.code {
flex: 1; display: flex; min-height: 0; overflow: hidden; background: var(--bg);
}
.gutter {
padding: 12px 10px 12px 14px; text-align: right; color: #3b4a5c;
font-size: 13px; line-height: 1.6; user-select: none; overflow: hidden; white-space: pre;
}
.code textarea {
flex: 1; resize: none; border: 0; outline: none;
background: transparent; color: var(--text);
font: inherit; font-size: 13px; line-height: 1.6;
padding: 12px 16px 12px 6px; white-space: pre; overflow: auto; tab-size: 2;
}
.code textarea[readonly] { color: #9aa7b6; }
.drawer-foot {
display: flex; align-items: center; justify-content: space-between; gap: 10px; flex-wrap: wrap;
padding: 12px 16px; border-top: 1px solid var(--border);
}
.drawer-foot .state { font-size: 12px; color: var(--muted); }
.drawer-foot .state.dirty { color: var(--warn); }
.drawer-foot .btns { display: flex; gap: 8px; flex-wrap: wrap; }
/* ---------- phones ---------- */
@media (max-width: 760px) {
.drawer-main { grid-template-columns: 1fr; grid-template-rows: auto 1fr; }
.file-list { border-right: 0; border-bottom: 1px solid var(--border); padding: 8px 0; max-height: 34vh; }
.gutter { display: none; }
.code textarea { padding-left: 14px; }
.summary { grid-template-columns: repeat(2, 1fr); }
thead { display: none; }
table, tbody, tr, td { display: block; width: 100%; }
tr.repo { padding: 12px 16px; border-bottom: 1px solid var(--border); }
tr.repo td { border: 0; padding: 2px 0; display: flex; justify-content: space-between; gap: 12px; }
tr.repo td::before { content: attr(data-label); color: var(--muted); font-size: 12px; }
tr.repo td.name-cell::before, tr.repo td.actions-cell::before { content: none; }
tr.repo td.name-cell { font-size: 15px; padding-bottom: 6px; }
tr.repo td.actions-cell { padding-top: 10px; }
.actions { justify-content: flex-start; flex-wrap: wrap; }
tr.error-row td { padding: 0 16px 14px; border-bottom: 1px solid var(--border); }
.row2 { grid-template-columns: 1fr; }
}
@media (prefers-reduced-motion: reduce) {
.heartbeat .dot, .dot.busy { animation: none; }
.toast { animation: none; }
#rain { display: none; }
}
/* ---------- additions for the Flask version ---------- */
.actions form { display: contents; }
.status.new { color: var(--muted); }
.dot.new { background: transparent; border: 1.5px dashed var(--muted); }
span.commit { cursor: default; }
span.commit:hover { text-decoration: none; }
.empty-state { text-align: center; padding: 64px 16px; color: var(--muted); }
.empty-state .big { color: var(--text); font-size: 16px; margin-bottom: 6px; }
.cursor { animation: blink 1s steps(1) infinite; color: var(--accent); }
@keyframes blink { 50% { opacity: 0; } }
.editor-loading { padding: 16px; color: var(--muted); }
@media (prefers-reduced-motion: reduce) { .cursor { animation: none; } }
+30
View File
@@ -0,0 +1,30 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{% block title %}gitops-watcher{% endblock %}</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<canvas id="rain" aria-hidden="true"></canvas>
<div class="wrap">
{% block content %}{% endblock %}
</div>
{% block overlays %}{% endblock %}
<div class="toasts" id="toasts" aria-live="polite">
{% for kind, msg in get_flashed_messages(with_categories=true) %}
<div class="toast {{ 'error' if kind == 'error' else '' }}">{{ msg }}</div>
{% endfor %}
</div>
<script src="{{ url_for('static', filename='app.js') }}"></script>
</body>
</html>
+215
View File
@@ -0,0 +1,215 @@
{% extends "base.html" %}
{% block title %}{% if counts.error %}({{ counts.error }}) {% endif %}gitops-watcher{% endblock %}
{% block content %}
<header class="topbar">
<div class="brand">☂ gitops-watcher <span>/ stacks</span></div>
<div class="top-right">
<div class="heartbeat">
{% if not last_round %}
<span class="dot warn"></span><span>waiting for the watcher's first round…</span>
{% elif stale %}
<span class="dot warn"></span>
<span style="color:var(--warn)">watcher may be stuck · last check <b style="color:var(--warn)" title="{{ last_round|pretty }}">{{ last_round|ago }}</b></span>
{% else %}
<span class="dot ok"></span>
<span>watcher up · next check in <b id="countdown" data-seconds="{{ next_in }}">…</b></span>
{% endif %}
</div>
<button class="btn primary" data-open="#add-modal" data-focus="#f-name">+ add repo</button>
</div>
</header>
<section class="summary">
<div class="stat"><div class="label">repos</div><div class="value">{{ total }}</div></div>
<div class="stat"><div class="label">ok</div><div class="value ok">{{ counts.ok }}</div></div>
<div class="stat {{ 'dim' if not counts.error }}"><div class="label">error</div><div class="value error">{{ counts.error }}</div></div>
<div class="stat {{ 'dim' if not counts.paused }}"><div class="label">paused</div><div class="value paused">{{ counts.paused }}</div></div>
</section>
<section class="panel">
{% if rows %}
<table>
<thead>
<tr>
<th>repo</th><th>status</th><th>commit</th><th>last check</th><th>last deploy</th>
<th class="actions-h">actions</th>
</tr>
</thead>
<tbody>
{% for r in rows %}
{% 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 }}">
<td class="name-cell">
<button class="linkish" data-files="{{ r.name }}" title="view & edit files"><span class="name">{{ r.name }}</span></button>
</td>
<td data-label="status"><span>
{% if r.busy %}
<span class="status busy"><span class="dot busy"></span>queued · {{ r.busy }}</span>
{% elif r.status == 'new' %}
<span class="status new"><span class="dot new"></span>waiting</span>
{% else %}
<span class="status {{ r.status }}"><span class="dot {{ r.status }}"></span>{{ r.status }}</span>
{% endif %}
{% if warn %}<span class="warn-pill" title=".env is missing keys">⚠ .env</span>{% endif %}
</span></td>
<td data-label="commit">{% if r.commit %}<span class="commit">{{ r.commit }}</span>{% else %}<span class="time">-</span>{% endif %}</td>
<td data-label="last check"><span class="time" title="{{ r.last_check|pretty }}">{{ r.last_check|ago }}</span></td>
<td data-label="last deploy"><span class="time" title="{{ r.last_deploy|pretty }}">{{ r.last_deploy|ago }}</span></td>
<td class="actions-cell">
{% if r.busy != 'add' %}
<div class="actions">
<button class="btn icon" data-files="{{ r.name }}" title="view & edit files">✎ files</button>
{% if r.status != 'paused' %}
<form method="post" action="{{ url_for('repo_action', name=r.name, action='deploy') }}">
<input type="hidden" name="csrf" value="{{ csrf_token() }}">
<button class="btn icon" {{ 'disabled' if r.busy }} title="redeploy now">↻ deploy</button>
</form>
<form method="post" action="{{ url_for('repo_action', name=r.name, action='stop') }}">
<input type="hidden" name="csrf" value="{{ csrf_token() }}">
<button class="btn icon" {{ 'disabled' if r.busy }} title="stop and pause">■ stop</button>
</form>
{% else %}
<form method="post" action="{{ url_for('repo_action', name=r.name, action='start') }}">
<input type="hidden" name="csrf" value="{{ csrf_token() }}">
<button class="btn icon" {{ 'disabled' if r.busy }} title="start">▶ start</button>
</form>
{% endif %}
<button class="btn icon danger" data-remove="{{ r.name }}" {{ 'disabled' if r.busy }} title="remove">✕</button>
</div>
{% endif %}
</td>
</tr>
{% if r.status == 'error' and r.error and not r.busy %}
<tr class="error-row"><td colspan="6"><span class="tree">└─ </span>{{ r.error }}</td></tr>
{% endif %}
{% if warn %}
<tr class="warn-row"><td colspan="6"><span class="tree">└─ </span>.env is missing {{ r.missing_env|length }} key{{ 's' if r.missing_env|length > 1 }} from .env.example:
{% for k in r.missing_env %}<code>{{ k }}</code>{{ ", " if not loop.last }}{% endfor %}
<button class="fix" data-files="{{ r.name }}">fix in .env →</button></td></tr>
{% endif %}
{% endfor %}
</tbody>
</table>
{% else %}
<div class="empty-state">
<div class="big">no repos yet<span class="cursor">_</span></div>
<div>add one with <b>+ add repo</b>, or edit repos.yml</div>
</div>
{% endif %}
</section>
<div class="footer">
<span>actions are queued and run on the watcher's next round</span>
<span>polling every {{ interval }}s · auto-refresh 30s</span>
</div>
{% endblock %}
{% block overlays %}
<!-- ADD REPO -->
<div class="backdrop" id="add-modal" role="dialog" aria-modal="true" aria-labelledby="add-title">
<form class="modal" method="post" action="{{ url_for('add_repo') }}" autocomplete="off">
<input type="hidden" name="csrf" value="{{ csrf_token() }}">
<div class="modal-head" id="add-title">add repo</div>
<div class="modal-body">
<div class="field">
<label for="f-name">name</label>
<input type="text" id="f-name" name="name" placeholder="my-app" required pattern="[a-z0-9][a-z0-9_\-]*">
<span class="hint">lowercase · used as the compose project name and clone folder</span>
</div>
<div class="field">
<label for="f-url">git url</label>
<input type="text" id="f-url" name="url" placeholder="https://gitea.yourdomain.com/you/my-app.git" required>
<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" 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>
<select id="f-token" name="token_env">
<option value="">none (public repo)</option>
{% for t in token_envs %}<option value="{{ t }}">{{ t }}</option>{% endfor %}
</select>
<span class="hint">only the env var name is saved, never the token itself</span>
</div>
<label class="check">
<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">
<input type="checkbox" name="deploy_now" checked>
<span>deploy now<span class="sub">clone and start on the next round (otherwise add as paused)</span></span>
</label>
</div>
<div class="modal-foot">
<button type="button" class="btn" data-close>cancel</button>
<button type="submit" class="btn primary">add repo</button>
</div>
</form>
</div>
<!-- REMOVE -->
<div class="backdrop" id="remove-modal" role="dialog" aria-modal="true" aria-labelledby="rm-title">
<form class="modal danger" method="post" id="remove-form" autocomplete="off">
<input type="hidden" name="csrf" value="{{ csrf_token() }}">
<div class="modal-head" id="rm-title">remove <span class="rm-name"></span></div>
<div class="modal-body">
<p class="note" style="margin:0">
this stops the stack (<code>docker compose down</code>), deletes its entry from
<code>repos.yml</code>, and deletes the clone folder.
</p>
<label class="check danger">
<input type="checkbox" name="wipe" id="rm-wipe">
<span>also delete volumes + local files
<span class="sub warn-text">permanently wipes this stack's data, including databases and its .env</span>
</span>
</label>
<div class="field">
<label for="rm-confirm">type <span class="confirm-name rm-name"></span> to confirm</label>
<input type="text" name="confirm" id="rm-confirm">
</div>
</div>
<div class="modal-foot">
<button type="button" class="btn" data-close>cancel</button>
<button type="submit" class="btn danger solid" id="rm-submit" disabled>remove</button>
</div>
</form>
</div>
<!-- FILE DRAWER -->
<div class="backdrop drawer-bd" id="files-drawer" role="dialog" aria-modal="true" aria-labelledby="fd-title">
<div class="drawer">
<div class="drawer-head">
<div class="title" id="fd-title"><span id="fd-repo"></span> <span>/ files</span></div>
<button class="btn icon" data-close aria-label="close">✕ close</button>
</div>
<div class="drawer-main">
<nav class="file-list" id="fd-list"></nav>
<section class="editor-pane">
<div class="editor-bar">
<span class="fname" id="fd-fname"></span>
<span id="fd-badges"></span>
</div>
<div id="fd-banner"></div>
<div id="fd-warn"></div>
<div class="code">
<div class="gutter" id="fd-gutter">1</div>
<textarea id="fd-text" spellcheck="false" aria-label="file contents"></textarea>
</div>
<div class="drawer-foot">
<span class="state" id="fd-state"></span>
<div class="btns" id="fd-btns">
<button class="btn" id="fd-discard" disabled>discard</button>
<button class="btn" id="fd-save" disabled>save</button>
<button class="btn primary" id="fd-save-deploy" disabled>save + redeploy</button>
</div>
</div>
</section>
</div>
</div>
</div>
{% endblock %}
+58
View File
@@ -0,0 +1,58 @@
# Layout on the host (next to this file):
# config/repos.yml which repos to deploy (created empty on first start)
# data/state.json what the watcher last did
# data/requests/ buttons / webhooks / `cli.py check` drop files here
# data/local/<repo>/ files edited in the website (.env, overrides), copied into the clone
# /opt/gitops/<repo> the clones the stacks run from
x-paths: &paths
STACKS_DIR: /opt/gitops
CONFIG_PATH: /config/repos.yml
STATE_PATH: /data/state.json
REQUEST_DIR: /data/requests
LOCAL_DIR: /data/local
CHECK_INTERVAL: 60
services:
gitops-watcher:
build: .
image: gitops-watcher
container_name: gitops-watcher
restart: unless-stopped
stop_grace_period: 5m # let a running deploy finish on `docker stop`
env_file: .env
environment:
<<: *paths
# pull + rebuild this stack when its own branch gets a new commit
# (only when the checkout is clean; see check_self() in app/watcher.py)
SELF_UPDATE: "true"
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- .:/self:ro # this checkout, to compare its commit with the remote
# a folder, not the single file: Docker would create a *directory* named
# repos.yml if the file didn't exist yet
- ./config:/config
- ./data:/data
- /opt/gitops:/opt/gitops
gitops-web:
image: gitops-watcher # same image, built by the service above
container_name: gitops-web
depends_on: [gitops-watcher]
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 (e.g. an NPM access list)
environment:
<<: *paths
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 # reads state.json...
- ./data/local:/data/local # ...but only writes local files
- ./data/requests:/data/requests # ...and requests
- /opt/gitops:/opt/gitops:ro # reads the clones to show repo files
+6
View File
@@ -0,0 +1,6 @@
pyyaml
ruamel.yaml
typer
rich
flask
gunicorn
-191
View File
@@ -1,191 +0,0 @@
import json
import os
import shutil
import subprocess
import time
from datetime import datetime
from pathlib import Path
import yaml
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"))
# --- helpers ---
def log(name: str, msg: str) -> None:
timestamp = f"{datetime.now():%Y-%m-%d %H:%M:%S}"
print(f"[{timestamp}] [{name}] {msg}", flush=True)
def run(cmd: list[str], cwd: Path | None = None) -> str:
result = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True)
if result.returncode != 0:
raise RuntimeError(f"{' '.join(cmd)} failed:\n{result.stderr.strip()}")
return result.stdout.strip()
# --- git ---
def remote_hash(url: str, branch: str) -> str:
out = run(["git", "ls-remote", url, f"refs/heads/{branch}"])
if not out:
raise RuntimeError(f"branch '{branch}' not found")
return out.split()[0]
def local_hash(path: Path) -> str:
return run(["git", "rev-parse", "HEAD"], cwd=path)
def clone(url: str, path: Path, branch: str) -> None:
run(["git", "clone", "--branch", branch, "--depth", "1", url, str(path)])
def update(path: Path, branch: str) -> None:
# explicit refspec so origin/<branch> exists even if the branch changed since the clone
refspec = f"+refs/heads/{branch}:refs/remotes/origin/{branch}"
run(["git", "fetch", "--depth", "1", "origin", refspec], cwd=path)
run(["git", "reset", "--hard", f"origin/{branch}"], cwd=path)
# --- docker ---
def compose(name, *args, path: Path | None = None, compose_file: str | None = None):
"""Build and run: docker compose -p <name> [-f <file>] <args...>"""
cmd = ["docker", "compose", "-p", name]
if compose_file:
cmd += ["-f", compose_file]
return run(cmd + list(args), cwd=path)
def deploy(name, path, compose_file):
log(name, "deploying...")
pull_image(name, path, compose_file)
compose(
name,
"up",
"-d",
"--build",
"--remove-orphans",
path=path,
compose_file=compose_file,
)
log(name, "deployed ✓")
def stop(name, path, compose_file):
log(name, "stopping...")
compose(name, "down", path=path, compose_file=compose_file)
log(name, "stopped")
def pull_image(name, path, compose_file):
return compose(
name, "pull", "--ignore-buildable", path=path, compose_file=compose_file
)
def status(name, path, compose_file):
out = compose(
name, "ps", "--all", "--format", "json", path=path, compose_file=compose_file
)
if not out:
return []
if out.startswith("["):
return json.loads(out)
return [json.loads(line) for line in out.splitlines()]
def logs(name, path, compose_file, tail: int = 50):
return compose(
name, "logs", "--tail", str(tail), path=path, compose_file=compose_file
)
def restart(name, path, compose_file):
compose(name, "restart", path=path, compose_file=compose_file)
log(name, "restarted")
# -- core logic ---
# commit hash last deployed per repo, so a failed deploy is retried next check
deployed: dict[str, str] = {}
def check_repo(repo):
name = repo["name"]
path = STACKS_DIR / name
url = repo["url"]
branch = repo.get("branch", "main")
compose_file = repo.get("compose_file")
try:
remote = remote_hash(url, branch)
if deployed.get(name) == remote:
return
if not (path / ".git").exists():
log(name, "not cloned yet, cloning...")
shutil.rmtree(path, ignore_errors=True)
clone(url, path, branch)
else:
local = local_hash(path)
if local != remote:
log(name, f"update found {local[:7]} -> {remote[:7]}")
update(path, branch)
deploy(name, path, compose_file)
deployed[name] = local_hash(path)
except Exception as e:
log(name, f"error: {e}")
# --- config ---
def load_config() -> dict:
with CONFIG_PATH.open() as f:
return yaml.safe_load(f) or {}
def normalize(raw: dict, defaults: dict) -> dict:
repo = {**defaults, **raw}
for key in ("name", "url"):
if not repo.get(key):
raise ValueError(f"repo entry missing '{key}': {raw}")
repo.setdefault("branch", "main")
repo.setdefault("compose_file", None)
return repo
# --- main loop ---
def main() -> None:
STACKS_DIR.mkdir(parents=True, exist_ok=True)
log("watcher", f"started, checking every {CHECK_INTERVAL}s")
while True:
try:
config = load_config()
except Exception as e:
log("watcher", f"can't read config: {e}")
time.sleep(CHECK_INTERVAL)
continue
defaults = config.get("defaults") or {}
for raw in config.get("repos") or []:
name = raw.get("name", "?")
try:
repo = normalize(raw, defaults)
check_repo(repo)
except Exception as e:
log(name, f"error: {e}")
time.sleep(CHECK_INTERVAL)
if __name__ == "__main__":
main()