|
| 1 | +"""Org health check: the newest run of every workflow, plus the public endpoints. |
| 2 | +
|
| 3 | +Why this exists: automations here fail quietly. A job that hits GitHub's 6-hour |
| 4 | +ceiling is reported as *cancelled*, not failed; a workflow that does all its |
| 5 | +work and dies at `git push` looks like nothing happened; a Pages deploy blocked |
| 6 | +by an environment rule leaves no log at all. Each of those went unnoticed for |
| 7 | +days. This treats anything other than success/skipped as a problem. |
| 8 | +
|
| 9 | +Run with: python -m machine.health [--issue] |
| 10 | +""" |
| 11 | + |
| 12 | +from __future__ import annotations |
| 13 | + |
| 14 | +import argparse |
| 15 | +import json |
| 16 | +import os |
| 17 | +import sys |
| 18 | +import urllib.error |
| 19 | +import urllib.request |
| 20 | +from dataclasses import dataclass |
| 21 | +from pathlib import Path |
| 22 | +from typing import Any |
| 23 | + |
| 24 | +API = "https://api.github.com" |
| 25 | +CONFIG = Path(__file__).with_name("repos.json") |
| 26 | +ISSUE_TITLE = "Org health report" |
| 27 | + |
| 28 | +# Conclusions that mean the run did its job. Everything else is surfaced — |
| 29 | +# `cancelled` and `timed_out` included, because that is how silent failures look. |
| 30 | +HEALTHY = {"success", "skipped", "neutral"} |
| 31 | + |
| 32 | + |
| 33 | +@dataclass |
| 34 | +class Finding: |
| 35 | + where: str |
| 36 | + what: str |
| 37 | + url: str = "" |
| 38 | + |
| 39 | + |
| 40 | +def _get(url: str, token: str | None) -> Any: |
| 41 | + request = urllib.request.Request(url, headers={"Accept": "application/vnd.github+json"}) |
| 42 | + if token and url.startswith(API): |
| 43 | + request.add_header("Authorization", f"Bearer {token}") |
| 44 | + with urllib.request.urlopen(request, timeout=30) as response: |
| 45 | + return json.loads(response.read().decode("utf-8")) |
| 46 | + |
| 47 | + |
| 48 | +def latest_runs(runs: list[dict[str, Any]]) -> dict[str, dict[str, Any]]: |
| 49 | + """Newest completed run per workflow name. `runs` arrive newest first.""" |
| 50 | + newest: dict[str, dict[str, Any]] = {} |
| 51 | + for run in runs: |
| 52 | + if run.get("status") != "completed": |
| 53 | + continue |
| 54 | + newest.setdefault(run["name"], run) |
| 55 | + return newest |
| 56 | + |
| 57 | + |
| 58 | +def run_findings(repo: str, branch: str, runs: list[dict[str, Any]]) -> list[Finding]: |
| 59 | + return [ |
| 60 | + Finding(f"{repo}@{branch} · {name}", run.get("conclusion") or "unknown", run.get("html_url", "")) |
| 61 | + for name, run in sorted(latest_runs(runs).items()) |
| 62 | + if run.get("conclusion") not in HEALTHY |
| 63 | + ] |
| 64 | + |
| 65 | + |
| 66 | +def endpoint_finding(name: str, url: str, expect: str, body: Any) -> Finding | None: |
| 67 | + if not isinstance(body, dict) or expect not in body: |
| 68 | + return Finding(name, f"response has no `{expect}` field", url) |
| 69 | + return None |
| 70 | + |
| 71 | + |
| 72 | +def check(config: dict[str, Any], token: str | None) -> list[Finding]: |
| 73 | + findings: list[Finding] = [] |
| 74 | + for repo in config["repos"]: |
| 75 | + name = repo["name"] |
| 76 | + try: |
| 77 | + workflows = _get(f"{API}/repos/{name}/actions/workflows?per_page=100", token) |
| 78 | + except urllib.error.URLError as exc: |
| 79 | + findings.append(Finding(name, f"could not list workflows: {exc}")) |
| 80 | + continue |
| 81 | + for branch in repo["branches"]: |
| 82 | + # One query per workflow, not "the last N runs": a weekly job would |
| 83 | + # scroll out of any fixed window behind the daily ones, and weekly |
| 84 | + # jobs are exactly the ones that fail unnoticed. |
| 85 | + runs: list[dict[str, Any]] = [] |
| 86 | + for workflow in workflows.get("workflows", []): |
| 87 | + if workflow.get("state") != "active": |
| 88 | + continue |
| 89 | + url = (f"{API}/repos/{name}/actions/workflows/{workflow['id']}/runs" |
| 90 | + f"?branch={branch}&status=completed&per_page=1") |
| 91 | + try: |
| 92 | + runs.extend(_get(url, token).get("workflow_runs", [])) |
| 93 | + except urllib.error.URLError as exc: |
| 94 | + findings.append(Finding(f"{name} · {workflow['name']}", f"could not read runs: {exc}")) |
| 95 | + findings.extend(run_findings(name, branch, runs)) |
| 96 | + |
| 97 | + for endpoint in config["endpoints"]: |
| 98 | + try: |
| 99 | + body = _get(endpoint["url"], None) |
| 100 | + except (urllib.error.URLError, json.JSONDecodeError) as exc: |
| 101 | + findings.append(Finding(endpoint["name"], f"unreachable: {exc}", endpoint["url"])) |
| 102 | + continue |
| 103 | + finding = endpoint_finding(endpoint["name"], endpoint["url"], endpoint["expect"], body) |
| 104 | + if finding: |
| 105 | + findings.append(finding) |
| 106 | + return findings |
| 107 | + |
| 108 | + |
| 109 | +def render(findings: list[Finding], config: dict[str, Any]) -> str: |
| 110 | + checked = ", ".join(repo["name"].split("/")[1] for repo in config["repos"]) |
| 111 | + if not findings: |
| 112 | + return f"## Org health: all clear\n\nChecked {checked} and {len(config['endpoints'])} public endpoints.\n" |
| 113 | + lines = [ |
| 114 | + f"## Org health: {len(findings)} problem(s)", |
| 115 | + "", |
| 116 | + f"Checked {checked} and {len(config['endpoints'])} public endpoints. " |
| 117 | + "`cancelled` and `timed_out` are listed on purpose: that is how a job " |
| 118 | + "killed at a time limit reports itself.", |
| 119 | + "", |
| 120 | + "| Where | Result |", |
| 121 | + "|---|---|", |
| 122 | + ] |
| 123 | + for f in findings: |
| 124 | + where = f"[{f.where}]({f.url})" if f.url else f.where |
| 125 | + lines.append(f"| {where} | {f.what} |") |
| 126 | + return "\n".join(lines) + "\n" |
| 127 | + |
| 128 | + |
| 129 | +def publish(body: str, token: str, repo: str) -> None: |
| 130 | + """Keep one open issue up to date instead of opening one per run.""" |
| 131 | + def call(method: str, path: str, payload: dict[str, Any] | None = None) -> Any: |
| 132 | + data = json.dumps(payload).encode("utf-8") if payload is not None else None |
| 133 | + request = urllib.request.Request(f"{API}{path}", data=data, method=method, headers={ |
| 134 | + "Accept": "application/vnd.github+json", |
| 135 | + "Authorization": f"Bearer {token}", |
| 136 | + "Content-Type": "application/json", |
| 137 | + }) |
| 138 | + with urllib.request.urlopen(request, timeout=30) as response: |
| 139 | + return json.loads(response.read().decode("utf-8") or "null") |
| 140 | + |
| 141 | + issues = call("GET", f"/repos/{repo}/issues?state=open&per_page=100") |
| 142 | + existing = next((i for i in issues if i.get("title") == ISSUE_TITLE), None) |
| 143 | + if existing: |
| 144 | + call("PATCH", f"/repos/{repo}/issues/{existing['number']}", {"body": body}) |
| 145 | + else: |
| 146 | + call("POST", f"/repos/{repo}/issues", {"title": ISSUE_TITLE, "body": body}) |
| 147 | + |
| 148 | + |
| 149 | +def main() -> int: |
| 150 | + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) |
| 151 | + parser.add_argument("--issue", action="store_true", help="update the health issue") |
| 152 | + args = parser.parse_args() |
| 153 | + |
| 154 | + config = json.loads(CONFIG.read_text(encoding="utf-8")) |
| 155 | + token = os.environ.get("GITHUB_TOKEN") |
| 156 | + findings = check(config, token) |
| 157 | + report = render(findings, config) |
| 158 | + print(report) |
| 159 | + |
| 160 | + summary = os.environ.get("GITHUB_STEP_SUMMARY") |
| 161 | + if summary: |
| 162 | + Path(summary).write_text(report, encoding="utf-8") |
| 163 | + if args.issue and token: |
| 164 | + publish(report, token, os.environ.get("GITHUB_REPOSITORY", "GetTechAPI/TechMachine")) |
| 165 | + # The report is the output; a red run would only add a second alert. |
| 166 | + return 0 |
| 167 | + |
| 168 | + |
| 169 | +if __name__ == "__main__": |
| 170 | + sys.exit(main()) |
0 commit comments