Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/actions/install-apt-deps/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,15 @@ inputs:
the retry delays plus up to 20s of SIGKILL grace per attempt, and the
per-command floors make values below retries*80 inert. This, plus
pull-timeout, plus any ccache-setup in the same job, has to fit the
caller's timeout-minutes - the defaults need ~16 minutes.
caller's timeout-minutes; check-workflows.py checks it.
required: false
default: '600'
pull-timeout:
description: >
Deadline for the ghcr bundle pull. Counts against the same
timeout-minutes as budget-seconds.
required: false
default: '300'
default: '120'
retry-delay:
description: 'Initial delay between retries (seconds, doubles each attempt)'
required: false
Expand Down
22 changes: 22 additions & 0 deletions .github/scripts/check-ci-deps.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,24 @@ def check_call(self, where: str, tag: str, packages: str,
f"{tag}.txt (or point this call at a bundle "
f"that has it).")

def check_runners(self, where: str, label: str, pairs: list,
called: set) -> None:
"""Check each runner of the job against the tag it runs with."""
for runner, tag in dict.fromkeys(pairs):
if (runner, tag) not in called and series(runner) \
and series(tag) and series(runner) != series(tag):
self.error(where, f"{label}: runs-on '{runner}' does not "
f"match ghcr-debs-tag '{tag}': the "
f"bundle holds .debs for {series(tag)}")
for runner, tag in dict.fromkeys(pairs):
if runner.startswith("ubuntu-latest") and series(tag):
self.error(where, f"{label}: runs-on '{runner}' with "
f"ghcr-debs-tag '{tag}': ubuntu-latest "
f"moves to new releases, so the bundle "
f"stops matching and every run falls back "
f"to the apt mirror. Pin runs-on to "
f"{series(tag)}.")

def check_ccache(self, label: str, tags: list, job: dict) -> None:
"""ccache-setup installs ccache from whatever bundle the job unpacked.

Expand Down Expand Up @@ -254,6 +272,10 @@ def check_step(self, path: pathlib.Path, job_id: str, job: dict,
tags = resolve(tag_raw, job)
packages = resolve(with_.get("packages"), job)
runners = resolve(job.get("runs-on"), job) or [""]
pairs = [(runner, tag) for runner in runners for tag in tags]
Comment thread
Frauschi marked this conversation as resolved.
Resolved
called = {(runners[0], tag) for tag in tags} if packages else set()
if not job_container(job):
self.check_runners(where, label, pairs, called)
if not tags or not packages:
self.unchecked.append(f"{label}: {tag_raw} / "
f"{with_.get('packages')}")
Expand Down
171 changes: 169 additions & 2 deletions .github/scripts/check-workflows.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,17 @@
# * every `run:` step is under the hard cap (error) and under the soft
# warning threshold (warning, so a growing list is noticed with
# runway left rather than at the cliff)
# * a job's worst-case apt setup fits in its timeout-minutes, and every
# parallel-make-check.py call has a --deadline that fits after it
#
# Findings are emitted as GitHub workflow commands (::error / ::warning)
# so they surface as annotations on the run, and as plain text so the log
# is readable when run locally.

import argparse
import functools
import pathlib
import re
import sys

import yaml
Expand All @@ -41,6 +45,24 @@
# offending content out of the workflow before it becomes a failure.
SOFT_LIMIT = 18000

# Seconds of timeout-minutes left for checkout and the build after setup.
SETUP_MARGIN = 120

# Seconds left around a parallel-make-check --deadline for the steps before
# it (setup-python, brew) and after it (logs, cache save).
DEADLINE_MARGIN = 300

# apt-install.sh's split_budget() limits and kill grace.
UPDATE_MIN, UPDATE_MAX, INSTALL_MIN, KILL_GRACE = 20, 90, 40, 10

# The apt-install.sh limits ccache-setup falls back to.
CCACHE_APT = {"tries": 2, "update": 60, "install": 90}

ACTIONS = pathlib.Path(__file__).resolve().parent.parent / "actions"
PMC_OPTION = re.compile(r"--(timeout|deadline)[= ]\s*['\"]?([^\s'\"\\]+)")
APT_OPTION = re.compile(r"--(tries|budget|delay|update-timeout|"
r"install-timeout)[= ]\s*['\"]?([^\s'\"\\]+)")


def iter_run_steps(doc: object) -> list[tuple[str, str]]:
"""Yield (location, script) for every `run:` step in a parsed file.
Expand Down Expand Up @@ -80,6 +102,149 @@ def scan_steps(steps: object, where: str) -> None:
return found


@functools.cache
def apt_defaults() -> dict:
"""The install-apt-deps input defaults, read from the action itself."""
doc = yaml.safe_load((ACTIONS / "install-apt-deps" / "action.yml")
.read_text())
return {k: v.get("default", "") for k, v in doc["inputs"].items()}


def apt_install_worst(tries: int, budget: int = 0, delay: int = 5,
update: int = 90, install: int = 300) -> int:
"""Worst-case seconds of apt-install.sh, replaying its budget split."""
spent = 0
for n in range(1, tries + 1):
up, inst = update, install
if budget:
per = int((budget - spent) / (tries - n + 1))
up = min(UPDATE_MAX, max(UPDATE_MIN, int(per / 2)))
inst = max(INSTALL_MIN, per - up)
spent += up + inst + 2 * KILL_GRACE
if n < tries:
spent += delay
delay *= 2
return spent


def apt_worst(inputs: dict) -> int:
"""Worst-case seconds of one install-apt-deps step, or -1 if unknown."""
try:
pull = int(inputs["pull-timeout"]) + KILL_GRACE
worst = apt_install_worst(int(inputs["retries"]),
int(inputs["budget-seconds"]),
int(inputs["retry-delay"]))
except (KeyError, TypeError, ValueError):
return -1
return worst + (pull if inputs.get("ghcr-debs-tag") else 0)
Comment thread
Frauschi marked this conversation as resolved.
Resolved


def invocations(run: object, name: str) -> list:
"""The rest of the command line after each mention of name in a script."""
script = "\n".join(line for line in str(run or "").splitlines()
if not line.lstrip().startswith("#"))
return [re.split(r"(?<!\\)\n", part, maxsplit=1)[0]
Comment thread
philljj marked this conversation as resolved.
Resolved
for part in script.split(name)[1:]]


def check_timeouts(path: pathlib.Path, doc: object, defaults: dict) -> int:
"""Check each job's apt setup and run deadlines against timeout-minutes."""
errors = 0
jobs = doc.get("jobs") if isinstance(doc, dict) else None
if not isinstance(jobs, dict):
return 0

def error(where: str, msg: str) -> None:
nonlocal errors
print(f"::error file={path}::{where}: {msg}")
errors += 1

for job_id, job in jobs.items():
if not isinstance(job, dict) or not isinstance(job.get("steps"), list):
continue
always = 0
# install-apt-deps steps behind different if: texts are taken as
# alternatives; steps behind the same one add up.
branches: dict[str, int] = {}
runs = []
for i, step in enumerate(job["steps"]):
if not isinstance(step, dict):
continue
where = f"jobs.{job_id} / {step.get('name') or f'step {i + 1}'}"
run = step.get("run")
for cmd in invocations(run, "parallel-make-check.py"):
runs.append((where, dict(PMC_OPTION.findall(cmd))))
for cmd in invocations(run, "apt-install.sh"):
opts = dict(APT_OPTION.findall(cmd))
try:
always += apt_install_worst(
int(opts.pop("tries", 3)),
**{k.split("-")[0]: int(v) for k, v in opts.items()})
except ValueError:
error(where, "give apt-install.sh's options literal "
"numbers so the setup budget can be checked")
uses = str(step.get("uses") or "")
if uses.endswith("/install-apt-deps"):
Comment thread
Frauschi marked this conversation as resolved.
Resolved
with_ = step.get("with")
cost = apt_worst({**defaults,
**(with_ if isinstance(with_, dict)
else {})})
if cost < 0:
error(where, "give retries, retry-delay, budget-seconds "
"and pull-timeout literal numbers so the "
"setup budget can be checked")
elif "if" in step:
cond = str(step["if"])
branches[cond] = branches.get(cond, 0) + cost
else:
always += cost
elif uses.endswith("/ccache-setup") \
and "macos" not in str(job.get("runs-on", "")):
always += apt_install_worst(**CCACHE_APT)
setup = always + max(branches.values(), default=0)

limit = job.get("timeout-minutes", 360)
fixed = isinstance(limit, (int, float))
if fixed and setup and setup + SETUP_MARGIN > limit * 60:
need = -(-(setup + SETUP_MARGIN) // 60)
error(f"jobs.{job_id}",
f"apt setup can take {setup}s against a slow or dead "
f"mirror, which leaves no room in timeout-minutes: {limit}. "
f"The job is then cancelled instead of failing with the "
f"apt error. Raise timeout-minutes to at least {need}, or "
f"lower budget-seconds / pull-timeout.")

deadlines = 0.0
for where, opts in runs:
traw, draw = opts.get("timeout", ""), opts.get("deadline", "")
if "$" in traw + draw:
print(f"::warning file={path}::{where}: --timeout/--deadline "
f"is not a literal, so it is not checked")
continue
try:
timeout, deadline = float(traw), float(draw)
except ValueError:
timeout = deadline = -1.0
if timeout <= 0 or deadline <= 0 or timeout > deadline:
error(where, f"parallel-make-check.py needs --timeout and "
f"--deadline above 0 with --timeout no larger, "
f"got --timeout='{traw}' --deadline='{draw}'. "
f"Without them a wedged config runs into "
f"timeout-minutes, which cancels the job and "
f"loses every config's log.")
continue
deadlines += deadline
need = -(-(setup + deadlines * 60 + DEADLINE_MARGIN) // 60)
if fixed and need > limit:
error(where, f"--deadline={draw} plus {setup}s of worst-case "
f"apt setup does not fit timeout-minutes: "
f"{limit}, so the job can be cancelled before "
f"the deadline fires. Raise timeout-minutes to "
f"at least {int(need)}, or lower --deadline.")

return errors


def check_file(path: pathlib.Path) -> tuple[int, int, int]:
"""Lint one file. Returns (errors, warnings, largest run: step)."""
errors = 0
Expand Down Expand Up @@ -113,13 +278,15 @@ def check_file(path: pathlib.Path) -> tuple[int, int, int]:
f"limit the whole file stops loading.")
warnings += 1

errors += check_timeouts(path, doc, apt_defaults())

return (errors, warnings, biggest)


def main() -> int:
p = argparse.ArgumentParser(
description="Lint GitHub Actions workflow files for the 21000 "
"character per-run-step limit.")
"character per-run-step limit and job time budgets.")
p.add_argument("paths", nargs="*", metavar="FILE",
help="files to check (default: all workflows and "
"composite actions under .github/)")
Expand Down Expand Up @@ -151,7 +318,7 @@ def main() -> int:
print(f"checked {len(paths)} files; largest run: step is {biggest} "
f"characters (limit {HARD_LIMIT})")
if errors:
print(f"FAILED: {errors} step(s) over the limit")
print(f"FAILED: {errors} error(s)")
return 1
if warnings:
print(f"{warnings} step(s) approaching the limit")
Expand Down
Loading
Loading