248 lines
11 KiB
Python
Executable File
248 lines
11 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Kaskada zależności między repozytoriami w Gitei.
|
|
|
|
Dla każdej krawędzi (repo nadrzędne -> przypięcie w repo zależnym):
|
|
1. bierze HEAD gałęzi main repo nadrzędnego (gdy jego CI jeszcze trwa, czeka na wynik);
|
|
2. idzie dalej tylko, gdy CI tego commitu jest zielone (albo commit nie ma żadnych sprawdzeń);
|
|
3. jeśli repo zależne przypina inny commit, a nowy jest jego potomkiem, otwiera PR z podbiciem
|
|
i ustawia scalenie po zielonym CI tego PR-a (wymagane sprawdzenia: ochrona gałęzi main).
|
|
Jeden przebieg przechodzi przez wszystkie piętra: zanim ruszy piętro wyżej, czeka na scalenie PR-a
|
|
i zielone CI nowego main. Gdy CI PR-a padnie, staje tam, a PR zostaje otwarty dla człowieka.
|
|
Nic tu nie wdraża: wdrożenie Atrium zostaje ręczne.
|
|
|
|
Środowisko: GITEA_URL, CASCADE_TOKEN (konto ci-bot). --dry-run: tylko pokazuje, co by zrobił.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import base64
|
|
import json
|
|
import os
|
|
import re
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import time
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
|
|
GITEA = os.environ.get("GITEA_URL", "http://77.216.148.202:3000").rstrip("/")
|
|
TOKEN = os.environ["CASCADE_TOKEN"]
|
|
DRY = "--dry-run" in sys.argv
|
|
BOT = ("ci-bot", "ci-bot@noreply.gitea")
|
|
|
|
MODULES = { # katalog w Atrium/deploy/modules -> repo w Haski
|
|
"agora": "Agora", "arbiter": "Arbiter", "counsel": "CounselScorecard", "galena": "Galena",
|
|
"insider": "Insider", "lexicon": "Lexicon", "parafa": "Parafa", "scribe": "Scribe",
|
|
"sygna": "Sygna", "workflow": "Workflow",
|
|
}
|
|
EDGES = [
|
|
{"up": "Alpaq/ReaderJS", "down": "Haski/Galena", "kind": "line",
|
|
"path": "backend/scripts/fetch_vendor.py",
|
|
"pattern": r'^READERJS_SHA = "([0-9a-f]{40})"$', "template": 'READERJS_SHA = "{sha}"'},
|
|
] + [
|
|
{"up": f"Haski/{repo}", "down": "Haski/Atrium", "kind": "gitlink",
|
|
"path": f"deploy/modules/{d}"} for d, repo in MODULES.items()
|
|
]
|
|
|
|
|
|
def api(method: str, path: str, body: dict | None = None):
|
|
req = urllib.request.Request(f"{GITEA}/api/v1{path}", method=method,
|
|
data=None if body is None else json.dumps(body).encode(),
|
|
headers={"Authorization": f"token {TOKEN}",
|
|
"Content-Type": "application/json"})
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=60) as r:
|
|
raw = r.read()
|
|
return json.loads(raw) if raw.strip() else None
|
|
except urllib.error.HTTPError as e:
|
|
if e.code == 404:
|
|
return None
|
|
raise RuntimeError(f"{method} {path}: HTTP {e.code} {e.read()[:300]!r}") from None
|
|
|
|
|
|
def git(*args: str, cwd: str | None = None) -> str:
|
|
env = dict(os.environ, GIT_AUTHOR_NAME=BOT[0], GIT_AUTHOR_EMAIL=BOT[1],
|
|
GIT_COMMITTER_NAME=BOT[0], GIT_COMMITTER_EMAIL=BOT[1], GIT_TERMINAL_PROMPT="0")
|
|
auth = base64.b64encode(f"ci-bot:{TOKEN}".encode()).decode()
|
|
return subprocess.run(["git", "-c", f"http.extraHeader=Authorization: Basic {auth}", *args],
|
|
cwd=cwd, env=env, check=True, capture_output=True, text=True).stdout.strip()
|
|
|
|
|
|
def head(repo: str) -> str:
|
|
return api("GET", f"/repos/{repo}/branches/main")["commit"]["id"]
|
|
|
|
|
|
def ci_state(repo: str, sha: str) -> str:
|
|
"""CI state of a commit. A commit with no checks at all (e.g. "[skip ci]") takes the state of its
|
|
nearest first-parent ancestor that has some, so a CI-less commit never jumps a red or running one."""
|
|
for _ in range(30):
|
|
st = api("GET", f"/repos/{repo}/commits/{sha}/status") or {}
|
|
if st.get("statuses"):
|
|
return st.get("state") or "pending"
|
|
commit = api("GET", f"/repos/{repo}/git/commits/{sha}") or {}
|
|
parents = commit.get("parents") or []
|
|
if not parents:
|
|
return "none"
|
|
sha = parents[0]["sha"]
|
|
return "none"
|
|
|
|
|
|
def current_pin(edge: dict) -> str | None:
|
|
down, path = edge["down"], edge["path"]
|
|
if edge["kind"] == "gitlink":
|
|
c = api("GET", f"/repos/{down}/contents/{urllib.parse.quote(path)}?ref=main")
|
|
return c and c.get("sha")
|
|
c = api("GET", f"/repos/{down}/contents/{urllib.parse.quote(path)}?ref=main")
|
|
text = base64.b64decode(c["content"]).decode()
|
|
m = re.search(edge["pattern"], text, re.M)
|
|
return m and m.group(1)
|
|
|
|
|
|
def is_descendant(repo: str, old: str, new: str) -> bool:
|
|
"""new zawiera old w historii (nigdy nie cofamy przypięcia). Sam git: klon bez treści plików."""
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
git("clone", "-q", "--bare", "--filter=blob:none", f"{GITEA}/{repo}.git", tmp)
|
|
try:
|
|
git("merge-base", "--is-ancestor", old, new, cwd=tmp)
|
|
return True
|
|
except subprocess.CalledProcessError:
|
|
return False
|
|
|
|
|
|
def open_cascade_prs(down: str, prefix: str) -> list[dict]:
|
|
prs = api("GET", f"/repos/{down}/pulls?state=open&limit=50") or []
|
|
return [p for p in prs if p["head"]["ref"].startswith(prefix)]
|
|
|
|
|
|
def bump(edge: dict, old: str, new: str) -> int | None:
|
|
up, down, path = edge["up"], edge["down"], edge["path"]
|
|
up_name = up.split("/")[1]
|
|
prefix = f"cascade/{up_name.lower()}-"
|
|
branch = f"{prefix}{new[:7]}"
|
|
for pr in open_cascade_prs(down, prefix):
|
|
if pr["head"]["ref"] == branch:
|
|
print(f" PR #{pr['number']} already open for {new[:7]}")
|
|
return pr["number"]
|
|
print(f" closing superseded PR #{pr['number']} ({pr['head']['ref']})")
|
|
if not DRY:
|
|
api("PATCH", f"/repos/{down}/pulls/{pr['number']}", {"state": "closed"})
|
|
log = api("GET", f"/repos/{up}/compare/{old}...{new}") or {}
|
|
lines = [f"- {c['sha'][:7]} {c['commit']['message'].splitlines()[0]}" for c in log.get("commits", [])][-20:]
|
|
title = f"{up_name}: {old[:7]} -> {new[:7]}"
|
|
body = (f"Kaskada: `{up}` main ma zielone CI na `{new[:7]}`, więc `{path}` przechodzi z "
|
|
f"`{old[:7]}` na `{new[:7]}`.\n\nNowe commity w {up_name}:\n" + "\n".join(lines) +
|
|
"\n\nScali się sam, gdy CI tego PR-a będzie zielone. Nic nie wdraża.")
|
|
if DRY:
|
|
print(f" [dry-run] would open PR '{title}' on {down} from {branch}")
|
|
return None
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
git("clone", "-q", "--depth", "1", "--branch", "main", f"{GITEA}/{down}.git", tmp)
|
|
git("checkout", "-q", "-b", branch, cwd=tmp)
|
|
if edge["kind"] == "gitlink":
|
|
git("update-index", "--cacheinfo", f"160000,{new},{path}", cwd=tmp)
|
|
else:
|
|
f = os.path.join(tmp, path)
|
|
text = open(f, encoding="utf-8", newline="").read()
|
|
text, n = re.subn(edge["pattern"], edge["template"].format(sha=new), text, count=1, flags=re.M)
|
|
if n != 1:
|
|
raise RuntimeError(f"{down}:{path}: pin pattern not found")
|
|
open(f, "w", encoding="utf-8", newline="").write(text)
|
|
git("add", path, cwd=tmp)
|
|
git("commit", "-q", "-m", f"{title}\n\nKaskada: {up} main green on {new}.", cwd=tmp)
|
|
git("push", "-q", "origin", f"{branch}:{branch}", cwd=tmp)
|
|
pr = api("POST", f"/repos/{down}/pulls", {"head": branch, "base": "main", "title": title, "body": body})
|
|
api("POST", f"/repos/{down}/pulls/{pr['number']}/merge",
|
|
# rebase: a PR made on top of main lands as the SAME commit, whose CI is already green, so the
|
|
# next level does not wait for main's CI again (if main moved meanwhile, it simply does wait)
|
|
{"Do": "rebase", "merge_when_checks_succeed": True, "delete_branch_after_merge": True})
|
|
print(f" opened PR #{pr['number']} '{title}' (auto-merge when CI is green)")
|
|
return pr["number"]
|
|
|
|
|
|
POLL = 20 # s między sprawdzeniami
|
|
WAIT_LIMIT = 3600 # najdłużej tyle czekamy na jedno piętro (CI Atrium trwa ~5 min)
|
|
|
|
|
|
def wait_until_done(repo: str, sha: str) -> str:
|
|
"""Czeka, aż CI commitu się skończy: 'success'/'none', 'failure'/'error' albo 'timeout'."""
|
|
deadline = time.time() + WAIT_LIMIT
|
|
while time.time() < deadline:
|
|
state = ci_state(repo, sha)
|
|
if state in ("success", "none", "failure", "error"):
|
|
return state
|
|
time.sleep(POLL)
|
|
return "timeout"
|
|
|
|
|
|
def wait_for_merge(down: str, number: int) -> str | None:
|
|
"""Czeka na scalenie PR-a; zwraca nowy HEAD main albo None (CI PR-a padło, PR zamknięty, czas)."""
|
|
deadline = time.time() + WAIT_LIMIT
|
|
while time.time() < deadline:
|
|
pr = api("GET", f"/repos/{down}/pulls/{number}")
|
|
if pr.get("merged"):
|
|
return head(down)
|
|
if pr["state"] == "closed":
|
|
print(f" PR #{number} closed without merging")
|
|
return None
|
|
if ci_state(down, pr["head"]["sha"]) in ("failure", "error"):
|
|
print(f" PR #{number}: CI failed - stopping here; the PR stays open for a person")
|
|
return None
|
|
time.sleep(POLL)
|
|
print(f" PR #{number}: not merged within {WAIT_LIMIT // 3600} h")
|
|
return None
|
|
|
|
|
|
def step(edge: dict) -> int | None:
|
|
"""Jedna krawędź. Zwraca numer PR-a z podbiciem (nowego albo już otwartego) albo None."""
|
|
up, down, path = edge["up"], edge["down"], edge["path"]
|
|
new = head(up)
|
|
state = ci_state(up, new)
|
|
old = current_pin(edge)
|
|
print(f"{up}@{new[:7]} CI={state} -> {down}:{path} pins {old and old[:7]}")
|
|
if old == new:
|
|
return None
|
|
if state == "pending" and not DRY:
|
|
print(f" {up} main CI still running - waiting for it")
|
|
state = wait_until_done(up, new)
|
|
if state not in ("success", "none"):
|
|
print(f" not bumping: {up} main CI is {state}")
|
|
return None
|
|
if old and not is_descendant(up, old, new):
|
|
print(f" skipped: {new[:7]} does not descend from {old[:7]} (never moving a pin backwards)")
|
|
return None
|
|
return bump(edge, old, new)
|
|
|
|
|
|
def main() -> int:
|
|
failures = 0
|
|
# Jeden przebieg przechodzi przez wszystkie piętra: ReaderJS -> Galena; jeśli Galena dostała PR,
|
|
# czekamy, aż się scali i nowy main Galeny przejdzie CI, i dopiero wtedy moduły -> Atrium.
|
|
levels = [[e for e in EDGES if e["down"] != "Haski/Atrium"],
|
|
[e for e in EDGES if e["down"] == "Haski/Atrium"]]
|
|
for n, level in enumerate(levels):
|
|
opened = []
|
|
for edge in level:
|
|
try:
|
|
pr = step(edge)
|
|
if pr:
|
|
opened.append((edge, pr))
|
|
except Exception as e: # jedna krawędź nie blokuje innych
|
|
failures += 1
|
|
print(f" ERROR: {e}")
|
|
if n + 1 == len(levels):
|
|
break
|
|
if DRY: # plan for every level, no waiting
|
|
continue
|
|
for edge, pr in opened:
|
|
down = edge["down"]
|
|
print(f"--- next level waits for {down} PR #{pr} to merge and main CI to pass")
|
|
new_head = wait_for_merge(down, pr)
|
|
if new_head:
|
|
print(f" {down} main {new_head[:7]} CI: {wait_until_done(down, new_head)}")
|
|
return 1 if failures else 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|