181 lines
6.4 KiB
Python
181 lines
6.4 KiB
Python
#!/usr/bin/env python3
|
|
"""Wake dockur guest runners only while matching Gitea jobs are queued/running."""
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import logging
|
|
import os
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
from pathlib import Path
|
|
|
|
API_URL = os.environ.get(
|
|
"GITEA_ACTIONS_JOBS_URL",
|
|
"https://git.faumaray.com/api/v1/user/actions/jobs",
|
|
)
|
|
POLL_SECONDS = int(os.environ.get("GITEA_VM_POLL_SECONDS", "15"))
|
|
IDLE_SECONDS = int(os.environ.get("GITEA_VM_IDLE_SECONDS", "90"))
|
|
PAGE_SIZE = 50
|
|
MAX_PAGES = 100
|
|
|
|
GUESTS = {
|
|
"windows-x64": "gitea-vm-windows.service",
|
|
"macos-x64": "gitea-vm-macos.service",
|
|
}
|
|
KEEP_AWAKE_DIR = Path("/var/lib/gitea-vm-runners/keep-awake")
|
|
ACTIVE_STATUSES = ("queued", "pending", "in_progress")
|
|
|
|
logging.basicConfig(
|
|
level=logging.INFO,
|
|
format="%(asctime)s %(levelname)s gitea-vm-dispatcher: %(message)s",
|
|
)
|
|
|
|
|
|
def read_token(path: str) -> str:
|
|
"""Read either the repository's TOKEN=value secret format or a raw token."""
|
|
for raw_line in Path(path).read_text(encoding="utf-8").splitlines():
|
|
line = raw_line.strip()
|
|
if not line or line.startswith("#"):
|
|
continue
|
|
if line.startswith("TOKEN="):
|
|
return line.split("=", 1)[1].strip().strip("\"'")
|
|
return line
|
|
raise RuntimeError(f"No token found in {path}")
|
|
|
|
|
|
def api_get(token: str, status: str, page: int) -> dict:
|
|
query = urllib.parse.urlencode({"status": status, "page": page, "limit": PAGE_SIZE, "sort": "id", "order": "desc"})
|
|
request = urllib.request.Request(
|
|
f"{API_URL}?{query}",
|
|
headers={"Authorization": f"token {token}", "Accept": "application/json", "User-Agent": "nixos-gitea-vm-dispatcher/1"},
|
|
method="GET",
|
|
)
|
|
with urllib.request.urlopen(request, timeout=12) as response:
|
|
if response.status != 200:
|
|
raise RuntimeError(f"Gitea API returned HTTP {response.status}")
|
|
return json.loads(response.read().decode("utf-8"))
|
|
|
|
|
|
def get_jobs(token: str) -> list[dict]:
|
|
jobs_by_id: dict[int, dict] = {}
|
|
for status in ACTIVE_STATUSES:
|
|
for page in range(1, MAX_PAGES + 1):
|
|
payload = api_get(token, status, page)
|
|
jobs = payload.get("jobs", [])
|
|
for job in jobs:
|
|
if isinstance(job, dict) and isinstance(job.get("id"), int):
|
|
jobs_by_id[job["id"]] = job
|
|
total = int(payload.get("total_count", len(jobs)))
|
|
if not jobs or page * PAGE_SIZE >= total:
|
|
break
|
|
else:
|
|
raise RuntimeError(f"Gitea returned more than {MAX_PAGES * PAGE_SIZE} {status} jobs; refusing incomplete reconciliation")
|
|
return list(jobs_by_id.values())
|
|
|
|
|
|
def needed_guests(jobs: list[dict]) -> set[str]:
|
|
needed: set[str] = set()
|
|
for job in jobs:
|
|
labels = job.get("labels") or []
|
|
if not isinstance(labels, list):
|
|
continue
|
|
labels = {str(label) for label in labels}
|
|
for label in GUESTS:
|
|
if label in labels:
|
|
needed.add(label)
|
|
return needed
|
|
|
|
|
|
def active(unit: str) -> bool:
|
|
result = subprocess.run(
|
|
["/run/current-system/sw/bin/systemctl", "is-active", "--quiet", unit],
|
|
stdout=subprocess.DEVNULL,
|
|
stderr=subprocess.DEVNULL,
|
|
check=False,
|
|
)
|
|
return result.returncode == 0
|
|
|
|
|
|
def systemctl(action: str, unit: str) -> bool:
|
|
result = subprocess.run(
|
|
["/run/current-system/sw/bin/systemctl", action, unit],
|
|
stdout=subprocess.PIPE,
|
|
stderr=subprocess.STDOUT,
|
|
text=True,
|
|
check=False,
|
|
)
|
|
if result.returncode != 0:
|
|
logging.error("systemctl %s %s failed (exit %s): %s", action, unit, result.returncode, result.stdout.strip())
|
|
return False
|
|
return True
|
|
|
|
|
|
def main() -> int:
|
|
if len(sys.argv) != 2:
|
|
print(f"usage: {sys.argv[0]} /path/to/agenix-api-token", file=sys.stderr)
|
|
return 2
|
|
|
|
token = read_token(sys.argv[1])
|
|
last_needed: dict[str, float | None] = {key: None for key in GUESTS}
|
|
logging.info("polling %s every %ss; idle shutdown grace=%ss", API_URL, POLL_SECONDS, IDLE_SECONDS)
|
|
|
|
while True:
|
|
now = time.monotonic()
|
|
try:
|
|
jobs = get_jobs(token)
|
|
needed = needed_guests(jobs)
|
|
except (OSError, ValueError, KeyError, RuntimeError, urllib.error.URLError, TimeoutError) as exc:
|
|
# Fail closed: if Gitea cannot be queried, never shut down a possibly busy guest.
|
|
logging.warning("cannot reconcile Gitea jobs (%s); keeping active guests awake", exc)
|
|
pinned = {label for label in GUESTS if (KEEP_AWAKE_DIR / label).exists()}
|
|
for label, unit in GUESTS.items():
|
|
if label in pinned and not active(unit):
|
|
logging.info("manual keep-awake pin for %s; starting %s despite API failure", label, unit)
|
|
systemctl("reset-failed", unit)
|
|
systemctl("start", unit)
|
|
if active(unit):
|
|
last_needed[label] = now
|
|
time.sleep(POLL_SECONDS)
|
|
continue
|
|
|
|
pinned = {label for label in GUESTS if (KEEP_AWAKE_DIR / label).exists()}
|
|
needed |= pinned
|
|
logging.debug("active guest labels from jobs or keep-awake pins: %s", sorted(needed))
|
|
for label, unit in GUESTS.items():
|
|
if label in needed:
|
|
last_needed[label] = None
|
|
if not active(unit):
|
|
reason = "manual keep-awake pin" if label in pinned else "queued/running job"
|
|
logging.info("%s needs %s; starting %s", reason, label, unit)
|
|
systemctl("reset-failed", unit)
|
|
systemctl("start", unit)
|
|
continue
|
|
|
|
if not active(unit):
|
|
last_needed[label] = None
|
|
continue
|
|
|
|
if last_needed[label] is None:
|
|
last_needed[label] = now
|
|
logging.info("%s is no longer needed; starting %ss idle grace period", unit, IDLE_SECONDS)
|
|
continue
|
|
|
|
idle_for = now - float(last_needed[label])
|
|
if idle_for >= IDLE_SECONDS:
|
|
logging.info("%s idle for %.0fs; stopping guest to release RAM", unit, idle_for)
|
|
if systemctl("stop", unit):
|
|
last_needed[label] = None
|
|
|
|
time.sleep(POLL_SECONDS)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
raise SystemExit(main())
|
|
except KeyboardInterrupt:
|
|
raise SystemExit(0)
|