finish the ain watcher command and finish the cli, modify the requirement and started a web template, modify the docker file

This commit is contained in:
rainyy21
2026-11-11 00:16:45 -05:00
parent ddef48ad6b
commit 92aba3bf38
9 changed files with 691 additions and 57 deletions
+391
View File
@@ -0,0 +1,391 @@
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 ruamel.yaml import YAML
from ruamel.yaml.error import CommentMark
from ruamel.yaml.tokens import CommentToken
from watcher import (
CONFIG_PATH,
NAME_RE,
STACKS_DIR,
load_config,
load_state,
normalize,
redact,
request_check,
)
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}")
# round-trip YAML keeps comments and layout when add/remove edit repos.yml
rt_yaml = YAML()
rt_yaml.indent(mapping=2, sequence=4, offset=2)
rt_yaml.preserve_quotes = True
def load_config_rt():
try:
with CONFIG_PATH.open() as f:
return rt_yaml.load(f) or {}
except FileNotFoundError:
return {}
def save_config_rt(data) -> None:
# write in place (no temp file + rename): repos.yml is a single-file bind
# mount in docker, and replacing the file would detach it from the container
with CONFIG_PATH.open("w") as f:
rt_yaml.dump(data, f)
# ruamel stores the blank lines/comments *after* a list entry on that entry's
# last key, so they have to be moved by hand when entries are added or removed
def _trailing(entry):
tok = entry.ca.items.get(list(entry.keys())[-1])
return tok[2] if tok and len(tok) > 2 else None
def _set_trailing(entry, token) -> None:
tok = entry.ca.items.setdefault(list(entry.keys())[-1], [None, None, None, None])
tok[2] = token
def append_entry(repos, entry: dict) -> None:
"""Append with a blank line before it, like the hand-written entries."""
if repos and _trailing(repos[-1]) is None:
_set_trailing(repos[-1], CommentToken("\n\n", CommentMark(0), None))
repos.append(entry)
def delete_entry(repos, idx: int) -> None:
"""Delete an entry, keeping the comment that sits above the entry after it."""
after = _trailing(repos[idx])
if idx > 0:
_set_trailing(repos[idx - 1], after)
elif after is not None:
text = "\n".join(
l.strip().lstrip("#").strip() for l in after.value.splitlines() if l.strip()
)
if text:
repos.yaml_set_start_comment(text, indent=2)
del repos[idx]
def config_names() -> list[str] | None:
"""Repo names from repos.yml, or None if it can't be read."""
try:
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 = ["docker", "compose", "-p", name]
if compose_file:
cmd += ["-f", compose_file]
cmd += ["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."""
find_repo(name) # exits if it isn't in repos.yml
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.get("repos")
if repos is 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}")
# 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.get("repos") or []
idx = next(
(i for i, r in enumerate(repos) if isinstance(r, dict) and r.get("name") == name),
None,
)
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()
+294 -55
View File
@@ -1,9 +1,12 @@
import base64
import json
import os
import re
import shutil
import subprocess
import time
import signal
import threading
from datetime import datetime
from pathlib import Path
@@ -13,6 +16,24 @@ CONFIG_PATH = Path(os.environ.get("CONFIG_PATH", "repos.yml"))
STACKS_DIR = Path(os.environ.get("STACKS_DIR", "stacks"))
CHECK_INTERVAL = int(os.environ.get("CHECK_INTERVAL", "60"))
STATE_PATH = Path(os.environ.get("STATE_PATH", STACKS_DIR / ".state.json"))
# `cli.py check` drops a file here to make the watcher check a repo right away
REQUEST_DIR = Path(os.environ.get("REQUEST_DIR", STACKS_DIR / ".requests"))
# 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 ---
@@ -21,8 +42,26 @@ def log(name: str, msg: str) -> None:
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)
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))
@@ -36,22 +75,31 @@ def redact(text: str) -> str:
# --- git ---
def auth_url(repo: dict) -> str | None:
url = repo["url"]
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 url.startswith("https://"):
if not repo["url"].startswith("https://"):
raise RuntimeError("token auth only works with https:// URLs")
return url.replace("https://", f"https://{token}@", 1)
# 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) -> str:
out = run(["git", "ls-remote", url, f"refs/heads/{branch}"])
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")
@@ -62,28 +110,41 @@ 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 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(url: str, path: Path, branch: str) -> None:
# keep origin in sync with the config, e.g. after a token rotation
run(["git", "remote", "set-url", "origin", url], cwd=path)
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)
run(
["git", "fetch", "--depth", "1", "origin", refspec],
cwd=path,
timeout=GIT_TIMEOUT,
env=env,
)
run(["git", "reset", "--hard", f"origin/{branch}"], cwd=path)
# --- docker ---
def compose(name, *args, path: Path | None = None, compose_file: str | None = None):
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...>"""
cmd = ["docker", "compose", "-p", name]
if compose_file:
cmd += ["-f", compose_file]
return run(cmd + list(args), cwd=path)
return run(cmd + list(args), cwd=path, timeout=timeout)
def deploy(name, path, compose_file, pull: bool = True):
@@ -98,6 +159,7 @@ def deploy(name, path, compose_file, pull: bool = True):
"--remove-orphans",
path=path,
compose_file=compose_file,
timeout=DEPLOY_TIMEOUT,
)
log(name, "deployed ✓")
@@ -110,7 +172,12 @@ def stop(name, path, compose_file):
def pull_image(name, path, compose_file):
return compose(
name, "pull", "--ignore-buildable", path=path, compose_file=compose_file
name,
"pull",
"--ignore-buildable",
path=path,
compose_file=compose_file,
timeout=DEPLOY_TIMEOUT,
)
@@ -139,49 +206,76 @@ def restart(name, path, compose_file):
# -- core logic ---
def check_repo(repo, state: dict):
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.
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:
url = auth_url(repo) or repo["url"]
remote = remote_hash(url, branch)
if current.get("commit") == remote and (path / ".git").exists():
# no new commit: refresh images / restart stopped containers.
# `up -d` only recreates containers whose image or config changed.
if repo["pull_image"]:
pull_image(name, path, compose_file)
compose(name, "up", "-d", "--remove-orphans", path=path, compose_file=compose_file)
if current.get("status") != "ok":
record(state, name, status="ok", error=None)
return
if not (path / ".git").exists():
if not cloned:
log(name, "not cloned yet, cloning...")
shutil.rmtree(path, ignore_errors=True)
clone(url, path, branch)
clone(url, path, branch, env)
else:
local = local_hash(path)
if local != remote:
log(name, f"update found {local[:7]} -> {remote[:7]}")
update(url, path, branch)
update(path, branch, env)
deploy(name, path, compose_file, repo["pull_image"])
record(
state,
name,
commit=local_hash(path),
deployed_at=f"{datetime.now():%Y-%m-%d %H:%M:%S}",
status="ok",
error=None,
)
except Exception as e:
log(name, f"error: {e}")
record(state, name, status="error", error=str(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[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
# --- config ---
@@ -190,12 +284,18 @@ def load_config() -> dict:
return yaml.safe_load(f) or {}
def normalize(raw: dict, defaults: dict) -> dict:
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)
@@ -223,11 +323,45 @@ def save_state(state: dict) -> None:
def record(state: dict, name: str, **fields) -> None:
# in memory only; main() saves once per loop
state.setdefault(name, {}).update(fields)
try:
save_state(state)
except OSError as e:
log("watcher", f"can't save state: {e}")
# --- check requests (from cli.py) ---
def request_check(name: str, force: bool = False) -> None:
REQUEST_DIR.mkdir(parents=True, exist_ok=True)
(REQUEST_DIR / f"{name}.json").write_text(json.dumps({"force": force}))
def has_requests() -> bool:
return REQUEST_DIR.is_dir() and any(REQUEST_DIR.glob("*.json"))
def apply_requests(state: dict) -> None:
"""Clear backoff for requested repos (and the deployed commit, if forced)."""
if not REQUEST_DIR.is_dir():
return
for f in REQUEST_DIR.glob("*.json"):
name = f.stem
try:
force = json.loads(f.read_text() or "{}").get("force", False)
except (json.JSONDecodeError, OSError):
force = False
f.unlink(missing_ok=True)
log(name, "check requested" + (" (forced redeploy)" if force else ""))
if name in state:
record(state, name, failed_commit=None, retry_at=None)
if force:
state[name].pop("commit", None)
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 ---
@@ -236,22 +370,127 @@ def main() -> None:
state = load_state()
log("watcher", f"started, checking every {CHECK_INTERVAL}s")
while True:
signal.signal(signal.SIGTERM, handle_stop)
signal.signal(signal.SIGINT, handle_stop)
while not STOP.is_set():
round_start = time.time()
apply_requests(state)
checked = deployed = errors = 0
try:
config = load_config()
except Exception as e:
log("watcher", f"can't read config: {e}")
time.sleep(CHECK_INTERVAL)
wait_for_next_round(CHECK_INTERVAL)
continue
defaults = config.get("defaults") or {}
for raw in config.get("repos") or []:
name = raw.get("name", "?")
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)
check_repo(repo, state)
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")
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}")
time.sleep(CHECK_INTERVAL)
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]:
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)",
)
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__":
View File
View File
View File
View File