diff --git a/.github/workflows/call-test-deploy.yml b/.github/workflows/call-test-deploy.yml index 078eae571b..94c0484bcd 100644 --- a/.github/workflows/call-test-deploy.yml +++ b/.github/workflows/call-test-deploy.yml @@ -316,6 +316,11 @@ jobs: shell: bash run: grep '^INFINITO_RESCUE_DIAGNOSTICS_BASE=' default.env >> "$GITHUB_ENV" + - name: "📈 Sample host memory, pressure and top RSS into the rescue diagnostics" + if: ${{ !env.ACT }} + shell: bash + run: nohup ./scripts/tests/deploy/ci/host-metrics-sampler.sh "${INFINITO_RESCUE_DIAGNOSTICS_BASE}/host-metrics.log" >/dev/null 2>&1 & + - name: 💽 Mount the empty spare disk at /mnt if: ${{ !env.ACT }} shell: bash diff --git a/cli/meta/ci/report_failures.py b/cli/meta/ci/report_failures.py index 1c74464d6b..a1f59c8c15 100644 --- a/cli/meta/ci/report_failures.py +++ b/cli/meta/ci/report_failures.py @@ -218,6 +218,17 @@ def report(run_id: str, repo: str) -> int: return 0 +def has_snapshot(dest: Path) -> bool: + """Whether any artifact under *dest* holds a rescue snapshot. + + Both rescue collectors write below ``//`` of the artifact, + while the host metrics log sits at its root on every run, green or red. + A file one folder deep inside an artifact is therefore real capture + content; a root file alone is not. + """ + return any(path.is_file() for path in dest.glob("*/*/**/*")) + + def _download_excerpt( repo: str, run_id: str, role: str, failures: list[Failure], dest: Path ) -> str: @@ -225,14 +236,24 @@ def _download_excerpt( name = artifact_name(role, failure) try: _gh( - ["run", "download", run_id, "--repo", repo, "-n", name, "-D", str(dest)] + [ + "run", + "download", + run_id, + "--repo", + repo, + "-n", + name, + "-D", + str(dest / name), + ] ) except subprocess.CalledProcessError: continue - return decisive_excerpt(dest) if dest.is_dir() else _NO_ARTIFACT + return decisive_excerpt(dest) if has_snapshot(dest) else _NO_SNAPSHOT -_NO_ARTIFACT = "_No rescue-diagnostics artifact was uploaded for this role._" +_NO_SNAPSHOT = "_No rescue snapshot was captured for this role._" def main(argv: list[str] | None = None) -> int: diff --git a/scripts/tests/deploy/ci/host-metrics-sampler.sh b/scripts/tests/deploy/ci/host-metrics-sampler.sh new file mode 100755 index 0000000000..435de5f196 --- /dev/null +++ b/scripts/tests/deploy/ci/host-metrics-sampler.sh @@ -0,0 +1,47 @@ +#!/bin/sh +# Param: $1 log file the blocks are appended to +set -u + +INTERVAL_SECONDS=60 +TOP_PROCESSES=10 + +memory_fields() { + awk '$1 ~ /^(MemTotal|MemAvailable|SwapTotal|SwapFree):$/ {sub(/:$/, "", $1); printf " %s_kB=%s", $1, $2}' "${1}" +} + +load_fields() { + read -r one five fifteen tasks _ <"${1}" + printf ' %s %s %s %s' "${one}" "${five}" "${fifteen}" "${tasks}" +} + +pressure_fields() { + if [ -r "${1}" ]; then + awk '{printf " %s %s %s", $1, $2, $3}' "${1}" + else + printf ' unavailable' + fi +} + +top_rows() { + awk -v stamp="${1}" -v limit="${TOP_PROCESSES}" \ + 'NR <= limit {exe = $3; sub(/:.*/, "", exe); printf "%s top pid=%s rss_kB=%s exe=%s\n", stamp, $1, $2, exe}' +} + +sample_once() { + stamp="$(date -u '+%Y-%m-%dT%H:%M:%SZ')" + printf '%s mem%s\n' "${stamp}" "$(memory_fields "${1}/meminfo")" + printf '%s load%s\n' "${stamp}" "$(load_fields "${1}/loadavg")" + for resource in cpu memory io; do + printf '%s psi %s%s\n' "${stamp}" "${resource}" "$(pressure_fields "${1}/pressure/${resource}")" + done + ps -eo pid=,rss=,comm= --sort=-rss | top_rows "${stamp}" +} + +[ "${HOST_METRICS_SAMPLER_LIB:-}" = "1" ] && return 0 + +: "${1:?usage: host-metrics-sampler.sh }" +mkdir -p "$(dirname "${1}")" +while :; do + sample_once /proc >>"${1}" + sleep "${INTERVAL_SECONDS}" +done diff --git a/tests/unit/python/cli/meta/ci/test_report_failures.py b/tests/unit/python/cli/meta/ci/test_report_failures.py index f302497db5..0a731a37f8 100644 --- a/tests/unit/python/cli/meta/ci/test_report_failures.py +++ b/tests/unit/python/cli/meta/ci/test_report_failures.py @@ -1,19 +1,116 @@ from __future__ import annotations +import subprocess import tempfile import unittest from pathlib import Path from unittest.mock import patch from cli.meta.ci.report_failures import ( + _NO_SNAPSHOT, Failure, + _download_excerpt, artifact_name, decisive_excerpt, failed_roles, + has_snapshot, issue_body, list_jobs, ) +ROLE = "web-app-nextcloud" +SWARM_0 = Failure("swarm", "0", "clearnet", "debian", "ext4", "amd64") +SWARM_7 = Failure("swarm", "7", "clearnet", "debian", "ext4", "amd64") + + +def _fake_gh(contents: dict[str, dict[str, str]]): + """Args: + contents: artifact name -> {relative path: text} it extracts. + + Returns a ``_gh`` stand-in that extracts like ``gh run download``: it + refuses to overwrite a file and fails the call, and an unknown artifact + fails too. + """ + + def gh(args: list[str]) -> str: + name = args[args.index("-n") + 1] + target = Path(args[args.index("-D") + 1]) + if name not in contents: + raise subprocess.CalledProcessError(1, ["gh", *args]) + for rel, text in contents[name].items(): + path = target / rel + path.parent.mkdir(parents=True, exist_ok=True) + try: + with path.open("x", encoding="utf-8") as handle: + handle.write(text) + except FileExistsError as exc: + raise subprocess.CalledProcessError(1, ["gh", *args]) from exc + return "" + + return gh + + +def _artifact(variant: str, error: str) -> dict[str, str]: + return { + "host-metrics.log": f"metrics of #{variant}\n", + f"debian/{ROLE}/error-context.md": error, + } + + +class TestDownloadExcerpt(unittest.TestCase): + def _download(self, contents: dict[str, dict[str, str]], dest: Path) -> str: + with patch("cli.meta.ci.report_failures._gh", _fake_gh(contents)): + return _download_excerpt("o/r", "1", ROLE, [SWARM_0, SWARM_7], dest) + + def test_two_artifacts_of_one_role_are_both_extracted(self) -> None: + names = [artifact_name(ROLE, SWARM_0), artifact_name(ROLE, SWARM_7)] + with tempfile.TemporaryDirectory() as td: + dest = Path(td) / "rescue" + excerpt = self._download( + { + names[0]: _artifact("0", "502 from #0\n"), + names[1]: _artifact("7", "502 from #7\n"), + }, + dest, + ) + expected = [ + f"{name}/{rel}" + for name, variant in zip(names, ("0", "7"), strict=True) + for rel in _artifact(variant, "") + ] + present = [rel for rel in expected if (dest / rel).is_file()] + folders = sorted(path.name for path in dest.iterdir()) + self.assertEqual(present, expected) + self.assertEqual(folders, sorted(names)) + self.assertIn("502 from #0", excerpt) + + def test_host_metrics_alone_is_no_snapshot(self) -> None: + with tempfile.TemporaryDirectory() as td: + dest = Path(td) / "rescue" + excerpt = self._download( + {artifact_name(ROLE, SWARM_0): {"host-metrics.log": "metrics\n"}}, + dest, + ) + self.assertFalse(has_snapshot(dest)) + self.assertEqual(excerpt, _NO_SNAPSHOT) + + def test_no_artifact_at_all_is_no_snapshot(self) -> None: + with tempfile.TemporaryDirectory() as td: + self.assertEqual(self._download({}, Path(td) / "rescue"), _NO_SNAPSHOT) + + def test_a_snapshot_without_a_decisive_file_says_so(self) -> None: + with tempfile.TemporaryDirectory() as td: + excerpt = self._download( + { + artifact_name(ROLE, SWARM_0): { + "host-metrics.log": "metrics\n", + f"debian/{ROLE}/free.txt": "Swap: 16G 6.8G\n", + } + }, + Path(td) / "rescue", + ) + self.assertIn("No decisive", excerpt) + class TestReportFailures(unittest.TestCase): def test_failed_roles_parses_mode_role_variant(self) -> None: diff --git a/tests/unit/python/scripts/tests/deploy/ci/test_host_metrics_sampler.py b/tests/unit/python/scripts/tests/deploy/ci/test_host_metrics_sampler.py new file mode 100644 index 0000000000..0e6b1337e5 --- /dev/null +++ b/tests/unit/python/scripts/tests/deploy/ci/test_host_metrics_sampler.py @@ -0,0 +1,191 @@ +from __future__ import annotations + +import os +import re +import subprocess +import tempfile +import unittest +from pathlib import Path + +from utils.cache.files import PROJECT_ROOT +from utils.cache.yaml import load_yaml + +SAMPLER = ( + PROJECT_ROOT / "scripts" / "tests" / "deploy" / "ci" / "host-metrics-sampler.sh" +) +WORKFLOW = PROJECT_ROOT / ".github" / "workflows" / "call-test-deploy.yml" + +STAMP = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z ") + +MEMINFO = ( + "MemTotal: 16384000 kB\n" + "MemFree: 512000 kB\n" + "MemAvailable: 4096000 kB\n" + "SwapCached: 20000 kB\n" + "SwapTotal: 16777212 kB\n" + "SwapFree: 9647000 kB\n" +) +LOADAVG = "3.20 2.90 2.10 5/812 45678\n" +CPU_PRESSURE = ( + "some avg10=12.50 avg60=8.00 avg300=4.00 total=123456\n" + "full avg10=0.00 avg60=0.00 avg300=0.00 total=0\n" +) +MEMORY_PRESSURE = ( + "some avg10=30.10 avg60=22.40 avg300=10.00 total=999\n" + "full avg10=18.20 avg60=11.00 avg300=5.00 total=555\n" +) +PS_ROWS = [ + " 812 2345678 dockerd", + " 1001 1800000 beam.smp", + " 1002 1500000 gunicorn: maste", + " 1003 1400000 node --passwor", + " 1004 1300000 mariadbd", + " 1005 1200000 php-fpm8.3", + " 1006 1100000 java", + " 1007 1000000 containerd-shim", + " 1008 900000 python3", + " 1009 800000 redis-server", + " 1010 700000 nginx", + " 1011 600000 sshd", +] + + +def _sample() -> tuple[list[str], str]: + with tempfile.TemporaryDirectory() as tmp: + proc_root = Path(tmp) / "proc" + (proc_root / "pressure").mkdir(parents=True) + (proc_root / "meminfo").write_text(MEMINFO, encoding="utf-8") + (proc_root / "loadavg").write_text(LOADAVG, encoding="utf-8") + (proc_root / "pressure" / "cpu").write_text(CPU_PRESSURE, encoding="utf-8") + (proc_root / "pressure" / "memory").write_text( + MEMORY_PRESSURE, encoding="utf-8" + ) + stub_dir = Path(tmp) / "bin" + stub_dir.mkdir() + stub = stub_dir / "ps" + stub.write_text( + "#!/bin/sh\n" + "printf 'ps-argv:%s\\n' \"$*\" >&2\n" + "printf '%s\\n' " + " ".join(f"'{row}'" for row in PS_ROWS) + "\n", + encoding="utf-8", + ) + stub.chmod(0o755) + proc = subprocess.run( + [ + "sh", + "-c", + 'HOST_METRICS_SAMPLER_LIB=1 . "$1" && sample_once "$2"', + "sh", + str(SAMPLER), + str(proc_root), + ], + capture_output=True, + text=True, + check=True, + env={**os.environ, "PATH": f"{stub_dir}{os.pathsep}{os.environ['PATH']}"}, + ) + return proc.stdout.splitlines(), proc.stderr + + +class SampleBlockTests(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + cls.lines, cls.stderr = _sample() + + def test_every_line_opens_with_one_shared_utc_stamp(self) -> None: + stamps = {line[:21] for line in self.lines} + self.assertEqual(len(stamps), 1, self.lines) + for line in self.lines: + self.assertRegex(line, STAMP) + + def _body(self) -> list[str]: + return [STAMP.sub("", line) for line in self.lines] + + def test_memory_and_swap_come_from_meminfo_in_kb(self) -> None: + self.assertEqual( + self._body()[0], + "mem MemTotal_kB=16384000 MemAvailable_kB=4096000 " + "SwapTotal_kB=16777212 SwapFree_kB=9647000", + ) + + def test_load_carries_the_three_averages_and_the_task_counts(self) -> None: + self.assertEqual(self._body()[1], "load 3.20 2.90 2.10 5/812") + + def test_pressure_carries_some_and_full_avg10_and_avg60(self) -> None: + self.assertEqual( + self._body()[2:5], + [ + "psi cpu some avg10=12.50 avg60=8.00 full avg10=0.00 avg60=0.00", + "psi memory some avg10=30.10 avg60=22.40 full avg10=18.20 avg60=11.00", + "psi io unavailable", + ], + ) + + def test_the_ten_largest_processes_follow_with_pid_rss_and_exe(self) -> None: + self.assertEqual( + self._body()[5:], + [ + "top pid=812 rss_kB=2345678 exe=dockerd", + "top pid=1001 rss_kB=1800000 exe=beam.smp", + "top pid=1002 rss_kB=1500000 exe=gunicorn", + "top pid=1003 rss_kB=1400000 exe=node", + "top pid=1004 rss_kB=1300000 exe=mariadbd", + "top pid=1005 rss_kB=1200000 exe=php-fpm8.3", + "top pid=1006 rss_kB=1100000 exe=java", + "top pid=1007 rss_kB=1000000 exe=containerd-shim", + "top pid=1008 rss_kB=900000 exe=python3", + "top pid=1009 rss_kB=800000 exe=redis-server", + ], + ) + + def test_ps_is_asked_for_pid_rss_and_comm_only(self) -> None: + self.assertEqual( + [line for line in self.stderr.splitlines() if line.startswith("ps-argv:")], + ["ps-argv:-eo pid=,rss=,comm= --sort=-rss"], + ) + + +class WorkflowWiringTests(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + workflow = load_yaml(str(WORKFLOW)) + cls.steps = workflow["jobs"]["deploy"]["steps"] + cls.runs = [str(step.get("run", "")) for step in cls.steps] + cls.sampler = next( + i for i, run in enumerate(cls.runs) if "host-metrics-sampler.sh" in run + ) + + def _index(self, needle: str) -> int: + return next(i for i, run in enumerate(self.runs) if needle in run) + + def test_the_sampler_detaches_into_the_rescue_base_on_real_runners(self) -> None: + self.assertEqual( + self.runs[self.sampler], + "nohup ./scripts/tests/deploy/ci/host-metrics-sampler.sh " + '"${INFINITO_RESCUE_DIAGNOSTICS_BASE}/host-metrics.log" >/dev/null 2>&1 &', + ) + self.assertEqual(self.steps[self.sampler].get("if"), "${{ !env.ACT }}") + + def test_the_sampler_starts_after_the_rescue_base_and_before_any_deploy( + self, + ) -> None: + self.assertLess(self._index("^INFINITO_RESCUE_DIAGNOSTICS_BASE="), self.sampler) + self.assertLess(self.sampler, self._index("00_one.sh")) + self.assertLess(self.sampler, self._index("ci/all.sh")) + + def test_the_rescue_upload_ships_the_base_even_after_a_red_deploy(self) -> None: + upload = next( + step + for step in self.steps + if str(step.get("with", {}).get("name", "")).startswith( + "rescue-diagnostics-" + ) + ) + self.assertEqual( + upload["with"]["path"], "${{ env.INFINITO_RESCUE_DIAGNOSTICS_BASE }}/" + ) + self.assertIn("always()", upload["if"]) + + +if __name__ == "__main__": + unittest.main()