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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
rainyy21
2026-11-11 16:17:05 -05:00
parent 999f852805
commit 5f70813202
13 changed files with 533 additions and 386 deletions
+3 -3
View File
@@ -1,7 +1,7 @@
.env .env
stacks/ stacks/
__pycache__/ __pycache__/
.venv/ .venv/
repos.yml repos.yml
config/
data/
+2 -1
View File
@@ -8,7 +8,8 @@ COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt RUN pip install --no-cache-dir -r requirements.txt
COPY app/watcher.py app/cli.py ./ # watcher.py + cli.py, and web/ for the gitops-web service (same image)
COPY app/ ./
ENV PYTHONUNBUFFERED=1 ENV PYTHONUNBUFFERED=1
+13 -72
View File
@@ -7,19 +7,21 @@ import typer
from rich.console import Console from rich.console import Console
from rich.markup import escape from rich.markup import escape
from rich.table import Table from rich.table import Table
from ruamel.yaml import YAML
from ruamel.yaml.error import CommentMark
from ruamel.yaml.tokens import CommentToken
from watcher import ( from watcher import (
CONFIG_PATH, CONFIG_PATH,
NAME_RE, NAME_RE,
STACKS_DIR, STACKS_DIR,
append_entry,
compose_cmd,
delete_entry,
find_index,
load_config, load_config,
load_config_rt,
load_state, load_state,
normalize, normalize,
redact, redact,
request_check, request_check,
save_config_rt,
) )
app = typer.Typer(help="control the gitops-watcher.") app = typer.Typer(help="control the gitops-watcher.")
@@ -74,60 +76,6 @@ def find_repo(name: str, quiet: bool = False) -> dict | None:
fail(f"no repo named '{name}' in {CONFIG_PATH}") fail(f"no repo named '{name}' in {CONFIG_PATH}")
# round-trip YAML keeps comments and layout when add/remove edit repos.yml
rt_yaml = YAML()
rt_yaml.indent(mapping=2, sequence=4, offset=2)
rt_yaml.preserve_quotes = True
def load_config_rt():
try:
with CONFIG_PATH.open() as f:
return rt_yaml.load(f) or {}
except FileNotFoundError:
return {}
def save_config_rt(data) -> None:
# write in place (no temp file + rename): repos.yml is a single-file bind
# mount in docker, and replacing the file would detach it from the container
with CONFIG_PATH.open("w") as f:
rt_yaml.dump(data, f)
# ruamel stores the blank lines/comments *after* a list entry on that entry's
# last key, so they have to be moved by hand when entries are added or removed
def _trailing(entry):
tok = entry.ca.items.get(list(entry.keys())[-1])
return tok[2] if tok and len(tok) > 2 else None
def _set_trailing(entry, token) -> None:
tok = entry.ca.items.setdefault(list(entry.keys())[-1], [None, None, None, None])
tok[2] = token
def append_entry(repos, entry: dict) -> None:
"""Append with a blank line before it, like the hand-written entries."""
if repos and _trailing(repos[-1]) is None:
_set_trailing(repos[-1], CommentToken("\n\n", CommentMark(0), None))
repos.append(entry)
def delete_entry(repos, idx: int) -> None:
"""Delete an entry, keeping the comment that sits above the entry after it."""
after = _trailing(repos[idx])
if idx > 0:
_set_trailing(repos[idx - 1], after)
elif after is not None:
text = "\n".join(
l.strip().lstrip("#").strip() for l in after.value.splitlines() if l.strip()
)
if text:
repos.yaml_set_start_comment(text, indent=2)
del repos[idx]
def config_names() -> list[str] | None: def config_names() -> list[str] | None:
"""Repo names from repos.yml, or None if it can't be read.""" """Repo names from repos.yml, or None if it can't be read."""
try: try:
@@ -277,10 +225,7 @@ def logs(
else: else:
compose_file = load_state().get(name, {}).get("compose_file") compose_file = load_state().get(name, {}).get("compose_file")
cmd = ["docker", "compose", "-p", name] cmd = compose_cmd(name, path, compose_file) + ["logs", "--tail", str(tail)]
if compose_file:
cmd += ["-f", compose_file]
cmd += ["logs", "--tail", str(tail)]
if follow: if follow:
cmd.append("--follow") cmd.append("--follow")
# not captured: output streams straight to the terminal # not captured: output streams straight to the terminal
@@ -298,7 +243,8 @@ def check(
wait: bool = typer.Option(False, "--wait", help="Wait for the result."), wait: bool = typer.Option(False, "--wait", help="Wait for the result."),
): ):
"""Ask the watcher to check a repo now.""" """Ask the watcher to check a repo now."""
find_repo(name) # exits if it isn't in repos.yml if find_repo(name)["paused"]: # find_repo exits if it isn't in repos.yml
fail(f"'{name}' is paused in {CONFIG_PATH}; unpause it first (or use Start in the website)")
before = load_state().get(name, {}).get("last_check") before = load_state().get(name, {}).get("last_check")
request_check(name, force) request_check(name, force)
console.print(f"requested a check of [cyan]{name}[/cyan]" + (" (forced redeploy)" if force else "")) console.print(f"requested a check of [cyan]{name}[/cyan]" + (" (forced redeploy)" if force else ""))
@@ -338,10 +284,8 @@ def add(
fail("token auth only works with https:// URLs") fail("token auth only works with https:// URLs")
data = load_config_rt() data = load_config_rt()
repos = data.get("repos") repos = data["repos"]
if repos is None: if find_index(repos, name) is not None:
repos = data["repos"] = []
if any(isinstance(r, dict) and r.get("name") == name for r in repos):
fail(f"'{name}' is already in {CONFIG_PATH}") fail(f"'{name}' is already in {CONFIG_PATH}")
# only write what was given, so the entry inherits from `defaults` # only write what was given, so the entry inherits from `defaults`
@@ -367,11 +311,8 @@ def remove(
): ):
"""Remove a repo from repos.yml.""" """Remove a repo from repos.yml."""
data = load_config_rt() data = load_config_rt()
repos = data.get("repos") or [] repos = data["repos"]
idx = next( idx = find_index(repos, name)
(i for i, r in enumerate(repos) if isinstance(r, dict) and r.get("name") == name),
None,
)
if idx is None: if idx is None:
fail(f"no repo named '{name}' in {CONFIG_PATH}") fail(f"no repo named '{name}' in {CONFIG_PATH}")
+386 -24
View File
@@ -2,7 +2,9 @@ import base64
import json import json
import os import os
import re import re
import shlex
import shutil import shutil
import socket
import subprocess import subprocess
import time import time
import signal import signal
@@ -11,13 +13,19 @@ from datetime import datetime
from pathlib import Path from pathlib import Path
import yaml 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")) CONFIG_PATH = Path(os.environ.get("CONFIG_PATH", "repos.yml"))
STACKS_DIR = Path(os.environ.get("STACKS_DIR", "stacks")) STACKS_DIR = Path(os.environ.get("STACKS_DIR", "stacks"))
CHECK_INTERVAL = int(os.environ.get("CHECK_INTERVAL", "60")) CHECK_INTERVAL = int(os.environ.get("CHECK_INTERVAL", "60"))
STATE_PATH = Path(os.environ.get("STATE_PATH", STACKS_DIR / ".state.json")) STATE_PATH = Path(os.environ.get("STATE_PATH", STACKS_DIR / ".state.json"))
# `cli.py check` drops a file here to make the watcher check a repo right away # the CLI and the website drop request files here (check / deploy / stop / ...);
# the watcher wakes up, handles them, and deletes them
REQUEST_DIR = Path(os.environ.get("REQUEST_DIR", STACKS_DIR / ".requests")) 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 # seconds before a command is killed
GIT_TIMEOUT = int(os.environ.get("GIT_TIMEOUT", "300")) # clone / fetch GIT_TIMEOUT = int(os.environ.get("GIT_TIMEOUT", "300")) # clone / fetch
@@ -133,6 +141,23 @@ def update(path: Path, branch: str, env: dict | None = None) -> None:
# --- docker --- # --- 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( def compose(
name, name,
*args, *args,
@@ -141,14 +166,22 @@ def compose(
timeout: float = COMPOSE_TIMEOUT, timeout: float = COMPOSE_TIMEOUT,
): ):
"""Build and run: docker compose -p <name> [-f <file>] <args...>""" """Build and run: docker compose -p <name> [-f <file>] <args...>"""
cmd = ["docker", "compose", "-p", name] return run(compose_cmd(name, path, compose_file) + list(args), cwd=path, timeout=timeout)
if compose_file:
cmd += ["-f", compose_file]
return run(cmd + 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): def deploy(name, path, compose_file, pull: bool = True):
log(name, "deploying...") log(name, "deploying...")
sync_local_files(name, path)
if pull: if pull:
pull_image(name, path, compose_file) pull_image(name, path, compose_file)
compose( compose(
@@ -239,6 +272,7 @@ def check_repo(repo, state: dict) -> dict:
if current.get("commit") == remote and cloned: if current.get("commit") == remote and cloned:
# no new commit: refresh images / restart stopped containers. # no new commit: refresh images / restart stopped containers.
# `up -d` only recreates containers whose image or config changed. # `up -d` only recreates containers whose image or config changed.
sync_local_files(name, path)
if repo["pull_image"]: if repo["pull_image"]:
pull_image(name, path, compose_file) pull_image(name, path, compose_file)
compose( compose(
@@ -271,13 +305,127 @@ def remove_stack(name: str, state: dict) -> bool:
path = STACKS_DIR / name path = STACKS_DIR / name
if path.exists(): if path.exists():
try: try:
stop(name, path, state[name].get("compose_file")) stop(name, path, state.get(name, {}).get("compose_file"))
except Exception as e: except Exception as e:
log(name, f"removed from config but can't stop it, will retry: {e}") log(name, f"removed from config but can't stop it, will retry: {e}")
return False return False
return True 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 --- # --- config ---
def load_config() -> dict: def load_config() -> dict:
with CONFIG_PATH.open() as f: with CONFIG_PATH.open() as f:
@@ -300,9 +448,90 @@ def normalize(raw, defaults: dict) -> dict:
repo.setdefault("branch", "main") repo.setdefault("branch", "main")
repo.setdefault("compose_file", None) repo.setdefault("compose_file", None)
repo.setdefault("pull_image", True) repo.setdefault("pull_image", True)
repo.setdefault("paused", False)
return repo 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 --- # --- state ---
def load_state() -> dict: def load_state() -> dict:
if not STATE_PATH.exists(): if not STATE_PATH.exists():
@@ -327,32 +556,133 @@ def record(state: dict, name: str, **fields) -> None:
state.setdefault(name, {}).update(fields) state.setdefault(name, {}).update(fields)
# --- check requests (from cli.py) --- # --- requests (from cli.py and the website) ---
def request_check(name: str, force: bool = False) -> None: #
# 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) REQUEST_DIR.mkdir(parents=True, exist_ok=True)
(REQUEST_DIR / f"{name}.json").write_text(json.dumps({"force": force})) path = REQUEST_DIR / f"{time.time_ns()}-{action}-{repo}.json"
# write then rename, so the watcher never reads a half-written file
tmp = path.with_name(path.name + ".tmp")
tmp.write_text(json.dumps(req, indent=2))
tmp.replace(path)
def request_check(name: str, force: bool = False) -> None:
queue_request("deploy" if force else "check", name)
def has_requests() -> bool: def has_requests() -> bool:
return REQUEST_DIR.is_dir() and any(REQUEST_DIR.glob("*.json")) return REQUEST_DIR.is_dir() and any(REQUEST_DIR.glob("*.json"))
def apply_requests(state: dict) -> None: def set_paused(name: str, paused: bool) -> None:
"""Clear backoff for requested repos (and the deployed commit, if forced).""" data = load_config_rt()
if not REQUEST_DIR.is_dir(): 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 return
for f in REQUEST_DIR.glob("*.json"):
name = f.stem config = load_config()
try: raw = next((r for r in config.get("repos") or []
force = json.loads(f.read_text() or "{}").get("force", False) if isinstance(r, dict) and r.get("name") == name), None)
except (json.JSONDecodeError, OSError): if raw is None:
force = False raise RuntimeError(f"no repo named {name!r} in {CONFIG_PATH}")
f.unlink(missing_ok=True) repo = normalize(raw, config.get("defaults") or {})
log(name, "check requested" + (" (forced redeploy)" if force else "")) path = STACKS_DIR / name
if action in ("check", "deploy", "start"):
if action == "start":
set_paused(name, False)
if name in state: if name in state:
record(state, name, failed_commit=None, retry_at=None) record(state, name, failed_commit=None, retry_at=None)
if force: if action == "deploy":
state[name].pop("commit", None) 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: def wait_for_next_round(seconds: float) -> None:
@@ -367,15 +697,23 @@ def wait_for_next_round(seconds: float) -> None:
# --- main loop --- # --- main loop ---
def main() -> None: def main() -> None:
STACKS_DIR.mkdir(parents=True, exist_ok=True) 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() state = load_state()
log("watcher", f"started, checking every {CHECK_INTERVAL}s") 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.SIGTERM, handle_stop)
signal.signal(signal.SIGINT, handle_stop) signal.signal(signal.SIGINT, handle_stop)
while not STOP.is_set(): while not STOP.is_set():
round_start = time.time() round_start = time.time()
apply_requests(state) process_requests(state)
checked = deployed = errors = 0 checked = deployed = errors = 0
try: try:
config = load_config() config = load_config()
@@ -411,6 +749,27 @@ def main() -> None:
seen.add(name) seen.add(name)
now = datetime.now().isoformat(timespec="seconds") 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 checked += 1
try: try:
result = check_repo(repo, state) result = check_repo(repo, state)
@@ -463,7 +822,7 @@ def main() -> None:
# entry (a typo can't take a stack down) or when stopping mid-loop # entry (a typo can't take a stack down) or when stopping mid-loop
# (`seen` would be incomplete). # (`seen` would be incomplete).
if config_ok and not STOP.is_set(): if config_ok and not STOP.is_set():
for old in [n for n in state if n not in seen]: for old in [n for n in state if n not in seen and n != SELF.get("project")]:
if remove_stack(old, state): if remove_stack(old, state):
log(old, "removed from config, stack stopped") log(old, "removed from config, stack stopped")
del state[old] del state[old]
@@ -483,6 +842,9 @@ def main() -> None:
f"{errors} errors ({elapsed:.1f}s)", f"{errors} errors ({elapsed:.1f}s)",
) )
if not STOP.is_set():
check_self()
try: try:
save_state(state) save_state(state)
except OSError as e: except OSError as e:
+55 -35
View File
@@ -14,7 +14,7 @@ import json
import os import os
import re import re
import secrets import secrets
import time import sys
from datetime import datetime from datetime import datetime
from pathlib import Path from pathlib import Path
@@ -22,14 +22,13 @@ import yaml
from flask import (Flask, abort, flash, jsonify, redirect, render_template, from flask import (Flask, abort, flash, jsonify, redirect, render_template,
request, session, url_for) request, session, url_for)
# ---------- settings (same env vars as the watcher) ---------- # share settings and rules with the watcher (app/watcher.py, one folder up)
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from watcher import (CHECK_INTERVAL, CONFIG_PATH, LOCAL_DIR, # noqa: E402
REQUEST_DIR, STACKS_DIR, STATE_PATH, normalize, queue_request)
# ---------- settings ----------
STATE_PATH = Path(os.environ.get("STATE_PATH", "data/state.json"))
CONFIG_PATH = Path(os.environ.get("CONFIG_PATH", "repos.yml"))
STACKS_DIR = Path(os.environ.get("STACKS_DIR", "stacks"))
LOCAL_DIR = Path(os.environ.get("LOCAL_DIR", "data/local"))
REQUESTS_DIR = Path(os.environ.get("REQUESTS_DIR", "data/requests"))
CHECK_INTERVAL = int(os.environ.get("CHECK_INTERVAL", "300"))
TOKEN_ENVS = [t for t in os.environ.get("TOKEN_ENVS", "GITEA_TOKEN,GITHUB_TOKEN").split(",") if t] 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 WEBHOOK_SECRET = os.environ.get("WEBHOOK_SECRET", "") # empty = webhooks turned off
@@ -54,7 +53,7 @@ def load_json(path: Path, default):
def load_repos() -> list[dict]: def load_repos() -> list[dict]:
"""repos.yml entries with defaults filled in (same rules as the watcher's normalize).""" """repos.yml entries with defaults filled in, by the watcher's own normalize()."""
try: try:
config = yaml.safe_load(CONFIG_PATH.read_text()) or {} config = yaml.safe_load(CONFIG_PATH.read_text()) or {}
except (OSError, yaml.YAMLError): except (OSError, yaml.YAMLError):
@@ -62,14 +61,24 @@ def load_repos() -> list[dict]:
defaults = config.get("defaults") or {} defaults = config.get("defaults") or {}
repos = [] repos = []
for raw in config.get("repos") or []: for raw in config.get("repos") or []:
if not isinstance(raw, dict) or not raw.get("name"): try:
continue repos.append(normalize(raw, defaults))
repo = {"branch": "main", "compose_file": "docker-compose.yml", except ValueError:
"pull_images": False, "paused": False, **defaults, **raw} continue # the watcher skips (and logs) invalid entries too
repos.append(repo)
return repos 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: def get_repo(name: str) -> dict:
for repo in load_repos(): for repo in load_repos():
if repo["name"] == name: if repo["name"] == name:
@@ -80,8 +89,8 @@ def get_repo(name: str) -> dict:
def pending_requests() -> dict[str, str]: def pending_requests() -> dict[str, str]:
"""{repo name: action} for requests the watcher hasn't processed yet.""" """{repo name: action} for requests the watcher hasn't processed yet."""
pending = {} pending = {}
if REQUESTS_DIR.is_dir(): if REQUEST_DIR.is_dir():
for f in sorted(REQUESTS_DIR.glob("*.json")): for f in sorted(REQUEST_DIR.glob("*.json")):
req = load_json(f, None) req = load_json(f, None)
if isinstance(req, dict) and req.get("repo"): if isinstance(req, dict) and req.get("repo"):
pending.setdefault(req["repo"], req.get("action", "?")) pending.setdefault(req["repo"], req.get("action", "?"))
@@ -99,13 +108,6 @@ def write_atomic(path: Path, text: str, mode: int | None = None) -> None:
os.replace(tmp, path) os.replace(tmp, path)
def queue_request(action: str, repo: str, **extra) -> None:
req = {"action": action, "repo": repo,
"created": datetime.now().isoformat(timespec="seconds"), **extra}
name = f"{time.time_ns()}-{action}-{repo}.json"
write_atomic(REQUESTS_DIR / name, json.dumps(req, indent=2))
# ---------- files ---------- # ---------- files ----------
def safe_path(base: Path, filename: str) -> Path: def safe_path(base: Path, filename: str) -> Path:
@@ -173,7 +175,7 @@ def git_files(repo: dict) -> list[str]:
and (not p.name.startswith(".") or p.name == ".env.example") and (not p.name.startswith(".") or p.name == ".env.example")
and p.stat().st_size <= MAX_FILE): and p.stat().st_size <= MAX_FILE):
names.append(p.name) names.append(p.name)
compose = repo["compose_file"] compose = compose_file_of(repo)
return sorted(names, key=lambda n: (n != compose, n.lower())) return sorted(names, key=lambda n: (n != compose, n.lower()))
@@ -320,8 +322,8 @@ def add_repo():
f = request.form f = request.form
name = f.get("name", "").strip() name = f.get("name", "").strip()
url = f.get("url", "").strip() url = f.get("url", "").strip()
branch = f.get("branch", "").strip() or "main" branch = f.get("branch", "").strip() # empty = repos.yml default
compose_file = f.get("compose_file", "").strip() or "docker-compose.yml" compose_file = f.get("compose_file", "").strip() # empty = let compose find it
token_env = f.get("token_env", "").strip() token_env = f.get("token_env", "").strip()
problems = [] problems = []
@@ -331,9 +333,9 @@ def add_repo():
problems.append(f"a repo named {name} already exists") problems.append(f"a repo named {name} already exists")
if not SAFE_URL.match(url): if not SAFE_URL.match(url):
problems.append("url: must be http(s) with no username or token in it") problems.append("url: must be http(s) with no username or token in it")
if not SAFE_BRANCH.match(branch): if branch and not SAFE_BRANCH.match(branch):
problems.append("branch name has invalid characters") problems.append("branch name has invalid characters")
if not SAFE_FILE.match(compose_file): if compose_file and not SAFE_FILE.match(compose_file):
problems.append("compose file must be a plain file name") problems.append("compose file must be a plain file name")
if token_env and token_env not in TOKEN_ENVS: if token_env and token_env not in TOKEN_ENVS:
problems.append("unknown token") problems.append("unknown token")
@@ -342,11 +344,15 @@ def add_repo():
flash(p, "error") flash(p, "error")
return redirect(url_for("index")) return redirect(url_for("index"))
entry = {"name": name, "url": url, "branch": branch, "compose_file": compose_file} entry = {"name": name, "url": url}
if branch:
entry["branch"] = branch
if compose_file:
entry["compose_file"] = compose_file
if token_env: if token_env:
entry["token_env"] = token_env entry["token_env"] = token_env
if f.get("pull_images") == "on": if f.get("pull_image") != "on":
entry["pull_images"] = True entry["pull_image"] = False # the watcher's default is True
if f.get("deploy_now") != "on": if f.get("deploy_now") != "on":
entry["paused"] = True entry["paused"] = True
@@ -357,11 +363,25 @@ def add_repo():
# ---------- file editor API (used by app.js) ---------- # ---------- 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") @app.get("/api/repos/<name>/files")
def list_files(name: str): def list_files(name: str):
repo = get_repo(name) repo = get_repo(name)
local = local_files(name) local = local_files(name)
return jsonify(local=local, git=git_files(repo), compose_file=repo["compose_file"], return jsonify(local=local, git=git_files(repo), compose_file=compose_file_of(repo),
missing_env=missing_env(name)) missing_env=missing_env(name))
@@ -441,9 +461,9 @@ def webhook(name: str):
return jsonify(ok=True, ignored=f"push to {ref}") return jsonify(ok=True, ignored=f"push to {ref}")
if repo["paused"]: if repo["paused"]:
return jsonify(ok=True, ignored="paused") return jsonify(ok=True, ignored="paused")
if name not in pending_requests(): # 5 quick pushes = 1 deploy if name not in pending_requests(): # 5 quick pushes = 1 check
queue_request("deploy", name) queue_request("check", name) # deploys if the branch has a new commit
return jsonify(ok=True, queued="deploy"), 202 return jsonify(ok=True, queued="check"), 202
if __name__ == "__main__": if __name__ == "__main__":
-48
View File
@@ -1,48 +0,0 @@
services:
gitops-watcher:
build: .
container_name: gitops-watcher
restart: unless-stopped
stop_grace_period: 2m
environment:
CHECK_INTERVAL: 300
STACKS_DIR: /opt/gitops
CONFIG_PATH: /config/repos.yml
STATE_PATH: /data/state.json
LOCAL_DIR: /data/local
REQUESTS_DIR: /data/requests
GITEA_TOKEN: ${GITEA_TOKEN}
GITHUB_TOKEN: ${GITHUB_TOKEN}
volumes:
- /var/run/docker.sock:/var/run/docker.sock
# the watcher now WRITES repos.yml (add / stop / start / remove), so no :ro.
# mount the folder, not the file: os.replace() can't swap a single-file bind mount
- ./config:/config
- ./data:/data
- /opt/gitops:/opt/gitops
gitops-web:
build: .
container_name: gitops-web
restart: unless-stopped
command: ["gunicorn", "--workers", "1", "--threads", "4", "--bind", "0.0.0.0:5000",
"--chdir", "/app/web", "app:app"]
ports:
- "8088:5000" # LAN only until there's a login in front (NPM access list)
environment:
CHECK_INTERVAL: 300
STACKS_DIR: /opt/gitops
CONFIG_PATH: /config/repos.yml
STATE_PATH: /data/state.json
LOCAL_DIR: /data/local
REQUESTS_DIR: /data/requests
TOKEN_ENVS: GITEA_TOKEN,GITHUB_TOKEN # names only, for the add-repo dropdown
SECRET_KEY: ${WEB_SECRET_KEY}
WEBHOOK_SECRET: ${WEBHOOK_SECRET} # same value goes in the GitHub/Gitea webhook settings
volumes:
# NO docker socket: the website can't run containers, only ask the watcher
- ./config:/config:ro
- ./data:/data:ro # can read state.json...
- ./data/local:/data/local # ...but only write local files
- ./data/requests:/data/requests # ...and requests
- /opt/gitops:/opt/gitops:ro # read the clones to show repo files
@@ -323,8 +323,28 @@ document.addEventListener("click", async e => {
} catch (err) { toast(esc(err.message), "error"); } } catch (err) { toast(esc(err.message), "error"); }
}); });
/* ---------- auto-refresh (skipped while a dialog or the editor is open) ---------- */ /* ---------- live refresh (skipped while a dialog or the editor is open) ----------
setInterval(() => { if (!anyOpen()) location.reload(); }, 30000); 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 ---------- */ /* ---------- countdown ---------- */
(function () { (function () {
@@ -125,8 +125,8 @@
<span class="hint">never paste a token into the url, pick one below instead</span> <span class="hint">never paste a token into the url, pick one below instead</span>
</div> </div>
<div class="row2"> <div class="row2">
<div class="field"><label for="f-branch">branch</label><input type="text" id="f-branch" name="branch" value="main"></div> <div class="field"><label for="f-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" value="docker-compose.yml"></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>
<div class="field"> <div class="field">
<label for="f-token">token</label> <label for="f-token">token</label>
@@ -137,7 +137,7 @@
<span class="hint">only the env var name is saved, never the token itself</span> <span class="hint">only the env var name is saved, never the token itself</span>
</div> </div>
<label class="check"> <label class="check">
<input type="checkbox" name="pull_images"> <input type="checkbox" name="pull_image" checked>
<span>auto-update images<span class="sub">pull newer versions of <code>image:</code> services each round</span></span> <span>auto-update images<span class="sub">pull newer versions of <code>image:</code> services each round</span></span>
</label> </label>
<label class="check"> <label class="check">
-194
View File
@@ -1,194 +0,0 @@
"""
WATCHER SIDE: paste these into watcher.py so the website's buttons do something.
The website only writes request files and local files. These functions make
the watcher:
- copy data/local/<repo>/ into the clone before every deploy
- add docker-compose.override.yml when it exists
- skip paused repos
- process request files (deploy / stop / start / remove / add)
Each block says where it goes. Function names match the ones you already have:
run, log, compose, deploy, check_repo, local_hash, load_config, normalize,
record, STACKS_DIR, LOCAL_DIR, CONFIG_PATH.
"""
# =====================================================================
# 1. TOP OF FILE: new import + constant
# =====================================================================
import shutil # add next to your other imports
REQUESTS_DIR = Path(os.environ.get("REQUESTS_DIR", "data/requests"))
# =====================================================================
# 2. CONFIG SECTION: save_config (repos.yml is now written by the watcher)
# Note: yaml.safe_dump does NOT keep comments in repos.yml.
# =====================================================================
def save_config(config: dict) -> None:
tmp = CONFIG_PATH.with_name(CONFIG_PATH.name + ".tmp")
with open(tmp, "w") as f:
yaml.safe_dump(config, f, sort_keys=False, default_flow_style=False)
os.replace(tmp, CONFIG_PATH)
# and in normalize(), add one more fallback:
# repo.setdefault("paused", False)
# =====================================================================
# 3. DOCKER SECTION: replace compose() and deploy() with these
# =====================================================================
OVERRIDE = "docker-compose.override.yml"
def compose(name: str, *args: str, path: Path | None = None,
compose_file: str | None = None, timeout: int = DEFAULT_TIMEOUT) -> str:
cmd = ["docker", "compose", "-p", name]
if compose_file:
cmd += ["-f", compose_file]
# Compose only auto-loads an override when no -f is given, so add it ourselves
if path is not None and (path / OVERRIDE).is_file():
cmd += ["-f", OVERRIDE]
return run(cmd + list(args), cwd=path, timeout=timeout)
def sync_local_files(name: str, path: Path) -> None:
"""Copy data/local/<name>/* into the clone, so compose sees .env, overrides, etc."""
local = LOCAL_DIR / name
if not local.is_dir():
return
for f in local.iterdir():
if f.is_file():
shutil.copy2(f, path / f.name)
def deploy(repo: dict, path: Path) -> None:
name = repo["name"]
log(name, "deploying...")
sync_local_files(name, path) # NEW: before anything reads the files
if repo["pull_images"]:
pull_images(name, path, repo["compose_file"])
compose(name, "up", "-d", "--build", "--remove-orphans",
path=path, compose_file=repo["compose_file"], timeout=BUILD_TIMEOUT)
log(name, "deployed ✓")
# (DEFAULT_TIMEOUT / BUILD_TIMEOUT are the timeout constants from the timeouts step.
# If you named them differently, use your names.)
# =====================================================================
# 4. NEW SECTION "requests" (put it before main)
# =====================================================================
def find_entry(config: dict, name: str) -> dict | None:
for entry in config.get("repos") or []:
if isinstance(entry, dict) and entry.get("name") == name:
return entry
return None
def handle_request(req: dict, state: dict) -> None:
action = req.get("action")
name = req.get("repo", "")
config = load_config()
config["repos"] = config.get("repos") or []
now = datetime.now().isoformat(timespec="seconds")
if action == "add":
if find_entry(config, name):
raise RuntimeError(f"{name} already exists")
config["repos"].append(req["entry"])
save_config(config)
log(name, "added from web UI")
return # the normal round clones + deploys it
entry = find_entry(config, name)
if entry is None:
raise RuntimeError(f"no repo named {name!r}")
repo = normalize(entry, config.get("defaults") or {})
path = STACKS_DIR / name
if action in ("deploy", "start"):
if action == "start":
entry["paused"] = False
save_config(config)
repo["paused"] = False
if (path / ".git").exists():
deploy(repo, path)
commit = local_hash(path)
else:
commit = check_repo(repo)["commit"] # clones + deploys
record(state, name, status="ok", error=None, commit=commit,
last_check=now, last_deploy=now)
elif action == "stop":
entry["paused"] = True
save_config(config)
if path.exists():
compose(name, "down", "--remove-orphans")
log(name, "stopped (paused)")
elif action == "remove":
wipe = bool(req.get("wipe_volumes"))
if path.exists():
compose(name, "down", "--remove-orphans", *(["-v"] if wipe else []))
config["repos"] = [e for e in config["repos"]
if not (isinstance(e, dict) and e.get("name") == name)]
save_config(config)
shutil.rmtree(path, ignore_errors=True)
if wipe:
shutil.rmtree(LOCAL_DIR / name, ignore_errors=True)
state.pop(name, None)
log(name, "removed" + (" (volumes + local files deleted)" if wipe else ""))
else:
raise RuntimeError(f"unknown action {action!r}")
def process_requests(state: dict) -> None:
"""Run every queued request, oldest first. Each file is deleted once handled."""
REQUESTS_DIR.mkdir(parents=True, exist_ok=True)
for f in sorted(REQUESTS_DIR.glob("*.json")):
req = {}
try:
req = json.loads(f.read_text())
log(req.get("repo", "?"), f"request: {req.get('action')}")
handle_request(req, state)
except Exception as e:
name = req.get("repo", "?") if isinstance(req, dict) else "?"
log(name, f"request failed: {e}")
record(state, name, status="error", error=f"request failed: {e}",
last_check=datetime.now().isoformat(timespec="seconds"))
finally:
f.unlink(missing_ok=True)
save_state(state)
# =====================================================================
# 5. main(): three small changes
# =====================================================================
#
# a) at the START of each round, before load_config():
#
# process_requests(state)
#
# b) in the per-repo loop, right after `repo = normalize(raw, defaults)`:
#
# if repo["paused"]:
# continue
#
# c) so the website and webhooks react fast: wait_for_next_round() already
# wakes up early via has_requests(), but only for the CLI's REQUEST_DIR.
# Make it look at the website's folder too:
#
# def has_requests() -> bool:
# return any(d.is_dir() and any(d.glob("*.json"))
# for d in (REQUEST_DIR, REQUESTS_DIR))
#
# Only do this together with (a): if nothing deletes the files in
# REQUESTS_DIR, the watcher would wake up every second forever.
# (a full round then runs: requests first, then the normal checks)
+47 -4
View File
@@ -1,15 +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: services:
gitops-watcher: gitops-watcher:
build: . build: .
image: gitops-watcher
container_name: gitops-watcher container_name: gitops-watcher
restart: unless-stopped restart: unless-stopped
stop_grace_period: 5m # let a running deploy finish on `docker stop` stop_grace_period: 5m # let a running deploy finish on `docker stop`
env_file: .env env_file: .env
environment: environment:
CHECK_INTERVAL: 30 <<: *paths
STACKS_DIR: /opt/gitops # pull + rebuild this stack when its own branch gets a new commit
CONFIG_PATH: /config/repos.yml # (only when the checkout is clean; see check_self() in app/watcher.py)
SELF_UPDATE: "true"
volumes: volumes:
- /var/run/docker.sock:/var/run/docker.sock - /var/run/docker.sock:/var/run/docker.sock
- ./repos.yml:/config/repos.yml # writable, for `cli.py add/remove` - .:/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 - /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
+2
View File
@@ -2,3 +2,5 @@ pyyaml
ruamel.yaml ruamel.yaml
typer typer
rich rich
flask
gunicorn