diff --git a/cli/administration/deploy/ci/gh.py b/cli/administration/deploy/ci/gh.py index 1d94b9e80f..7620d7b682 100644 --- a/cli/administration/deploy/ci/gh.py +++ b/cli/administration/deploy/ci/gh.py @@ -60,21 +60,31 @@ def resolve_repo() -> str: return slug_from_url(_run(["git", "remote", "get-url", _branch_remote()])) -def _gh(args: list[str], repo: str | None = None, check: bool = True) -> str: +def _gh( + args: list[str], repo: str | None = None, errors: list[str] | None = None +) -> str: """Run ``gh`` and return its stdout. Args: args: the ``gh`` arguments, without the ``gh`` itself. repo: appended as ``--repo`` when given. - check: abort the command on a non-zero exit. Pass ``False`` for calls - whose failure the caller handles, which then yields ``""``. + errors: when given, a non-zero exit appends gh's last stderr line to it + and yields ``""`` instead of aborting the command. URL query strings + are cut from that line: job logs redirect to signed blob URLs whose + query string is the signature. """ cmd = ["gh", *args] if repo: cmd += ["--repo", repo] proc = subprocess.run(cmd, check=False, capture_output=True, text=True) if proc.returncode != 0: - if not check: + if errors is not None: + lines = proc.stderr.strip().splitlines() + errors.append( + re.sub(r"\?\S*", "", lines[-1]) + if lines + else f"gh exited {proc.returncode}" + ) return "" sys.stderr.write( proc.stderr or f"gh exited {proc.returncode}: {' '.join(cmd)}\n" diff --git a/cli/administration/deploy/ci/runs.py b/cli/administration/deploy/ci/runs.py index 1c859acd4a..9540352edc 100644 --- a/cli/administration/deploy/ci/runs.py +++ b/cli/administration/deploy/ci/runs.py @@ -242,7 +242,9 @@ def _parse_inputs(log: str) -> dict[str, str]: return inputs -def inputs_from_jobs(jobs: list[dict], repo: str) -> dict[str, str]: +def inputs_from_jobs( + jobs: list[dict], repo: str, errors: list[str] | None = None +) -> dict[str, str]: """The dispatch inputs a called job's log records verbatim. GitHub cuts ``display_title`` at 512 UTF-8 bytes (measured on two runs, @@ -265,11 +267,14 @@ def inputs_from_jobs(jobs: list[dict], repo: str) -> dict[str, str]: Args: jobs: the run's jobs, as ``gh run view --json jobs`` returns them. repo: ``owner/repo`` the run lives in. + errors: collects gh's error line of every log read that failed. Returns: input name -> value, empty when no job of the run records an ``Inputs`` block -- including when the logs have expired. """ + if errors is None: + errors = [] candidates = sorted( ( job @@ -288,7 +293,7 @@ def inputs_from_jobs(jobs: list[dict], repo: str) -> dict[str, str]: "--allow-escape-sequences", f"repos/{repo}/actions/jobs/{job['databaseId']}/logs", ], - check=False, + errors=errors, ) ) if inputs: @@ -308,12 +313,18 @@ def dispatched_priority(source: dict, repo: str) -> str: source: the run as :func:`fetch_run` returns it. repo: ``owner/repo`` the run lives in. """ - priority = inputs_from_jobs(source["jobs"], repo).get("priority", "") + errors: list[str] = [] + priority = inputs_from_jobs(source["jobs"], repo, errors).get("priority", "") if not priority and run_name.value_from_title(source["displayTitle"], "priority"): raise SystemExit( "Source run has a priority line but its job log records no inputs; " "the Inputs block moved or the log expired. Retriggering now would " "silently drop every priority role." + + ( + f" {len(errors)} log read(s) failed, the last with: {errors[-1]}" + if errors + else " No log read failed; none of the logs held an Inputs block." + ) ) return priority diff --git a/tests/unit/python/cli/administration/deploy/ci/test_runs.py b/tests/unit/python/cli/administration/deploy/ci/test_runs.py index 2d0763a123..eb03d0eedc 100644 --- a/tests/unit/python/cli/administration/deploy/ci/test_runs.py +++ b/tests/unit/python/cli/administration/deploy/ci/test_runs.py @@ -1,6 +1,8 @@ from __future__ import annotations +import subprocess import unittest +import unittest.mock as mock from typing import ClassVar from cli.administration.deploy.ci import gh, runs @@ -237,8 +239,13 @@ class TestInputsFromJobs(unittest.TestCase): ] ) + NOT_FOUND: ClassVar[str] = "gh: Not Found (HTTP 404)" + def _read( - self, jobs: list[dict], logs: dict[int, str] + self, + jobs: list[dict], + logs: dict[int, str], + errors: list[str] | None = None, ) -> tuple[dict[str, str], list[int]]: """Read *jobs* against a fake ``gh`` serving *logs* by job id. @@ -246,6 +253,7 @@ class TestInputsFromJobs(unittest.TestCase): jobs: the run's jobs. logs: job id -> log body. A missing id stands for a job whose log blob does not exist, which ``gh`` reports as a bare HTTP 404. + errors: passed through to the reader. Returns: the parsed inputs and the job ids the reader asked for, in order. @@ -253,18 +261,21 @@ class TestInputsFromJobs(unittest.TestCase): asked: list[int] = [] def fake_gh( - args: list[str], repo: str | None = None, check: bool = True + args: list[str], repo: str | None = None, errors: list[str] | None = None ) -> str: self.assertIn("--allow-escape-sequences", args) - self.assertFalse(check) + self.assertIsNotNone(errors) job_id = int(args[-1].split("/")[-2]) asked.append(job_id) - return logs.get(job_id, "") + if job_id not in logs: + errors.append(self.NOT_FOUND) + return "" + return logs[job_id] original = runs._gh runs._gh = fake_gh try: - return runs.inputs_from_jobs(jobs, "o/r"), asked + return runs.inputs_from_jobs(jobs, "o/r", errors), asked finally: runs._gh = original @@ -353,14 +364,74 @@ class TestInputsFromJobs(unittest.TestCase): }, ] - inputs, asked = self._read(jobs, {}) + errors: list[str] = [] + inputs, asked = self._read(jobs, {}, errors) self.assertEqual(asked, [2]) self.assertEqual(inputs, {}) + self.assertEqual(errors, [self.NOT_FOUND]) def test_a_run_without_a_called_job_reads_nothing(self) -> None: self.assertEqual(runs.inputs_from_jobs([{"name": "🎲 Pick"}], "o/r"), {}) + def test_the_guard_names_the_gh_error_of_the_failed_reads(self) -> None: + source = { + "jobs": [ + { + "name": "🎛️ Orchestrate CI (manual) / 🏁 Finish pipeline", + "databaseId": 1, + "conclusion": "success", + } + ], + "displayTitle": render({"priority": "web-app-x"}), + } + + def failing(jobs: list[dict], repo: str, errors: list[str]) -> dict[str, str]: + errors.append(self.NOT_FOUND) + return {} + + with ( + mock.patch.object(runs, "inputs_from_jobs", side_effect=failing), + self.assertRaises(SystemExit) as raised, + ): + runs.dispatched_priority(source, "o/r") + + self.assertIn( + f"1 log read(s) failed, the last with: {self.NOT_FOUND}", + str(raised.exception), + ) + + +class TestGhErrors(unittest.TestCase): + def _fail(self, stderr: str) -> list[str]: + errors: list[str] = [] + failed = subprocess.CompletedProcess([], 1, stdout="{}", stderr=stderr) + with mock.patch.object(gh.subprocess, "run", return_value=failed): + self.assertEqual(gh._gh(["api", "x"], errors=errors), "") + return errors + + def test_a_failure_with_errors_given_yields_empty_and_its_last_line(self) -> None: + self.assertEqual( + self._fail("warning\ngh: Not Found (HTTP 404)\n"), + ["gh: Not Found (HTTP 404)"], + ) + + def test_a_signed_redirect_url_loses_its_query_string(self) -> None: + self.assertEqual( + self._fail("HTTP 403: (https://blob.example/log.txt?sv=1&sig=secret)"), + ["HTTP 403: (https://blob.example/log.txt"], + ) + + def test_a_failure_without_errors_aborts(self) -> None: + failed = subprocess.CompletedProcess([], 4, stdout="", stderr="boom\n") + with ( + mock.patch.object(gh.subprocess, "run", return_value=failed), + mock.patch.object(gh.sys, "stderr"), + self.assertRaises(SystemExit) as raised, + ): + gh._gh(["api", "x"]) + self.assertEqual(raised.exception.code, 4) + class TestConfigFromTitle(unittest.TestCase): """A retrigger has to reproduce the source run's configuration.