From ab4ae5a42a88be8096cba7a949552f3f89fd59f8 Mon Sep 17 00:00:00 2001 From: Gaida Amzar Date: Thu, 26 Nov 2026 16:40:08 -0700 Subject: [PATCH 1/4] Add probe runner for check-in, download, run and upload --- probe/src/probe/runner.py | 181 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 181 insertions(+) create mode 100644 probe/src/probe/runner.py diff --git a/probe/src/probe/runner.py b/probe/src/probe/runner.py new file mode 100644 index 0000000..6422441 --- /dev/null +++ b/probe/src/probe/runner.py @@ -0,0 +1,181 @@ +"""Probe loop: check in, run the assigned test, and upload its measurement.""" + +from __future__ import annotations + +import hashlib +import json +import os +import signal +import subprocess +import sys +import tempfile +import threading +import uuid +from dataclasses import dataclass +from datetime import UTC, datetime +from pathlib import Path +from urllib.error import HTTPError, URLError +from urllib.request import Request, urlopen + +CHECK_IN_PATH = "/functions/v1/probe-check-in" +MEASUREMENTS_PATH = "/functions/v1/probe-measurements" +IDLE_WAIT_SECONDS = 30 +SCRIPT_TIMEOUT_SECONDS = 30 +HTTP_TIMEOUT_SECONDS = 30 + + +class ProbeError(Exception): + """A server or download failure that ends the run.""" + + +@dataclass(frozen=True) +class Config: + probe_id: str + backend_url: str + probe_token: str + + @classmethod + def from_env(cls) -> Config: + return cls( + probe_id=os.environ["PROBE_ID"].strip(), + backend_url=os.environ["BACKEND_URL"].strip().rstrip("/"), + probe_token=os.environ["PROBE_TOKEN"].strip(), + ) + + +def _post(config: Config, path: str, body: dict) -> object: + request = Request( + config.backend_url + path, + data=json.dumps(body).encode(), + method="POST", + headers={"Content-Type": "application/json", "X-Probe-Token": config.probe_token}, + ) + try: + with urlopen(request, timeout=HTTP_TIMEOUT_SECONDS) as response: + return json.load(response) + except HTTPError as error: + raise ProbeError(f"{path} returned HTTP {error.code}") from None + except (URLError, OSError) as error: + raise ProbeError(f"{path} failed: {error}") from None + except ValueError: + # No error text: a rejected header value would echo the token. + raise ProbeError(f"{path} returned a malformed response or bad request") from None + + +def _download(config: Config, file: dict) -> bytes: + """Fetch a signed path without the probe token and verify its hash.""" + try: + path, expected = file["download_path"], file["sha256"].lower() + except (KeyError, TypeError, AttributeError): + raise ProbeError("check-in returned a malformed download") from None + # The signed query token is not the probe token, but keep it out of logs anyway. + name = path.split("?", 1)[0] + try: + with urlopen(config.backend_url + path, timeout=HTTP_TIMEOUT_SECONDS) as response: + data = response.read() + except (URLError, OSError) as error: + raise ProbeError(f"download {name} failed: {error}") from None + if hashlib.sha256(data).hexdigest() != expected: + raise ProbeError(f"download {name} failed its hash check") + return data + + +def check_in(config: Config) -> dict | None: + body = _post(config, CHECK_IN_PATH, {"probe_id": config.probe_id}) + if not isinstance(body, dict) or "assignment" not in body: + raise ProbeError("check-in returned a malformed response") + return body["assignment"] + + +def run_script(test_dir: str, timeout: float) -> tuple[str, int | None, dict]: + """Run run.sh and return (status, result_code, result_data).""" + env = {k: v for k, v in os.environ.items() if k != "PROBE_TOKEN"} + try: + proc = subprocess.Popen( + ["bash", "run.sh"], + cwd=test_dir, + env=env, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + start_new_session=True, + ) + except OSError as error: + print(f"could not start test: {error}", file=sys.stderr) + return "failed", None, {} + with proc: + try: + stdout, stderr = proc.communicate(timeout=timeout) + except subprocess.TimeoutExpired: + # Kill the whole group so children like ping don't hold the pipes open. + if hasattr(os, "killpg"): + os.killpg(proc.pid, signal.SIGKILL) + else: + proc.kill() + proc.communicate() + return "timeout", None, {} + if stderr: + sys.stderr.write(stderr.decode(errors="replace")) + if proc.returncode == 0: + try: + output = json.loads(stdout) + except ValueError: + output = None + if isinstance(output, dict) and isinstance(output.get("result_data"), dict): + return "completed", 0, output["result_data"] + return "failed", proc.returncode, {} + + +def _now() -> str: + return datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ") + + +def run_once(config: Config, script_timeout: float = SCRIPT_TIMEOUT_SECONDS) -> bool: + """Run one pass. Return False when there was no assignment.""" + assignment = check_in(config) + if assignment is None: + return False + try: + revision_id = assignment["test_revision_id"] + script, definition = assignment["script"], assignment["definition"] + except (KeyError, TypeError): + raise ProbeError("check-in returned a malformed assignment") from None + + # On Windows the folder can stay locked for a moment after bash exits. + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as test_dir: + Path(test_dir, "run.sh").write_bytes(_download(config, script)) + Path(test_dir, "test.json").write_bytes(_download(config, definition)) + run_id = str(uuid.uuid4()) + started_at = _now() + status, result_code, result_data = run_script(test_dir, script_timeout) + finished_at = _now() + + _post( + config, + MEASUREMENTS_PATH, + { + "schema_version": 1, + "id": run_id, + "probe_id": config.probe_id, + "test_revision_id": revision_id, + "started_at": started_at, + "finished_at": finished_at, + "status": status, + "result_code": result_code, + "result_data": result_data, + "location": None, + }, + ) + print(f"run {run_id} of revision {revision_id}: {status}") + return True + + +def run_loop( + config: Config, + stop: threading.Event, + idle_wait: float = IDLE_WAIT_SECONDS, + script_timeout: float = SCRIPT_TIMEOUT_SECONDS, +) -> None: + """Run passes until stop is set; a pass in progress finishes first.""" + while not stop.is_set(): + if not run_once(config, script_timeout): + stop.wait(idle_wait) From 99ddb6137427d3fb14b3eafe240f5e5fd213f083 Mon Sep 17 00:00:00 2001 From: Gaida Amzar Date: Thu, 26 Nov 2026 16:40:08 -0700 Subject: [PATCH 2/4] Test the probe runner against a fake backend --- probe/tests/test_runner.py | 193 +++++++++++++++++++++++++++++++++++++ 1 file changed, 193 insertions(+) create mode 100644 probe/tests/test_runner.py diff --git a/probe/tests/test_runner.py b/probe/tests/test_runner.py new file mode 100644 index 0000000..6648bbd --- /dev/null +++ b/probe/tests/test_runner.py @@ -0,0 +1,193 @@ +"""Tests for the probe loop against a fake backend.""" + +from __future__ import annotations + +import hashlib +import json +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from urllib.parse import urlsplit + +import pytest + +from probe.runner import Config, ProbeError, run_loop, run_once, run_script + +PROBE_ID = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb" +TOKEN = "connectivity-local-probe-token" +FIXED_SCRIPT = b"printf '{\"result_data\":{\"rtt_avg_ms\":18.4,\"packet_loss_pct\":0}}\\n'\n" +DEFINITION = b'{"name": "Fixed"}\n' + + +class FakeBackend: + def __init__(self) -> None: + self.files: dict[str, bytes] = {} + self.assignments: list[dict] = [] + self.checked_in = threading.Event() + self.measurements: list[dict] = [] + self.download_tokens: list[str | None] = [] + backend = self + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *args: object) -> None: + pass + + def reply(self, code: int, data: bytes) -> None: + self.send_response(code) + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def do_GET(self) -> None: + backend.download_tokens.append(self.headers.get("X-Probe-Token")) + data = backend.files.get(urlsplit(self.path).path) + self.reply(404, b"") if data is None else self.reply(200, data) + + def do_POST(self) -> None: + body = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) + if self.headers.get("X-Probe-Token") != TOKEN or body["probe_id"] != PROBE_ID: + return self.reply(401, b'{"error":"unauthorized"}') + if self.path == "/functions/v1/probe-check-in": + backend.checked_in.set() + assignment = backend.assignments.pop(0) if backend.assignments else None + return self.reply(200, json.dumps({"assignment": assignment}).encode()) + backend.measurements.append(body) + self.reply(201, json.dumps({"id": body["id"]}).encode()) + + self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + self.url = f"http://127.0.0.1:{self.server.server_port}" + + def assign(self, revision_id: str, script: bytes, script_hash: str | None = None) -> None: + base = f"/storage/v1/object/sign/test-revisions/fixed/{revision_id}" + self.files[f"{base}/run.sh"] = script + self.files[f"{base}/test.json"] = DEFINITION + self.assignments.append( + { + "test_revision_id": revision_id, + "script": { + "download_path": f"{base}/run.sh?token=example", + "sha256": script_hash or hashlib.sha256(script).hexdigest(), + }, + "definition": { + "download_path": f"{base}/test.json?token=example", + "sha256": hashlib.sha256(DEFINITION).hexdigest(), + }, + } + ) + + +@pytest.fixture +def backend(): + fake = FakeBackend() + thread = threading.Thread(target=fake.server.serve_forever, daemon=True) + thread.start() + yield fake + fake.server.shutdown() + fake.server.server_close() + + +@pytest.fixture +def config(backend: FakeBackend) -> Config: + return Config(probe_id=PROBE_ID, backend_url=backend.url, probe_token=TOKEN) + + +def test_two_runs_in_order_with_new_revision(backend: FakeBackend, config: Config) -> None: + backend.assign("dddddddd-dddd-4ddd-8ddd-dddddddddddd", FIXED_SCRIPT) + backend.assign("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee", FIXED_SCRIPT) + + assert run_once(config) is True + assert run_once(config) is True + assert run_once(config) is False + + first, second = backend.measurements + assert first["test_revision_id"] == "dddddddd-dddd-4ddd-8ddd-dddddddddddd" + assert second["test_revision_id"] == "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee" + assert first["id"] != second["id"] + for record in (first, second): + assert record["status"] == "completed" + assert record["result_code"] == 0 + assert record["result_data"] == {"rtt_avg_ms": 18.4, "packet_loss_pct": 0} + assert record["probe_id"] == PROBE_ID + assert record["location"] is None + + +def test_bad_hash_prevents_execution(backend: FakeBackend, config: Config, tmp_path: Path) -> None: + marker = tmp_path / "ran" + backend.assign( + "dddddddd-dddd-4ddd-8ddd-dddddddddddd", + f"touch '{marker.as_posix()}'\n".encode(), + script_hash="0" * 64, + ) + + with pytest.raises(ProbeError, match="hash check"): + run_once(config) + + assert not marker.exists() + assert backend.measurements == [] + + +def test_empty_assignment_waits_and_shutdown_stops_loop( + backend: FakeBackend, config: Config +) -> None: + stop = threading.Event() + thread = threading.Thread(target=run_loop, args=(config, stop), kwargs={"idle_wait": 60}) + thread.start() + assert backend.checked_in.wait(5) + + stop.set() + thread.join(timeout=5) + + assert not thread.is_alive() + assert backend.measurements == [] + + +def test_token_with_newline_is_stripped_and_not_logged( + backend: FakeBackend, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("PROBE_ID", PROBE_ID) + monkeypatch.setenv("BACKEND_URL", backend.url) + monkeypatch.setenv("PROBE_TOKEN", TOKEN + "\n") + + assert run_once(Config.from_env()) is False + + # Without the strip, the HTTP layer rejects the header; its error must not echo the token. + with pytest.raises(ProbeError) as error: + run_once(Config(probe_id=PROBE_ID, backend_url=backend.url, probe_token=TOKEN + "\n")) + assert TOKEN not in str(error.value) + + +def test_token_kept_out_of_downloads_and_script( + backend: FakeBackend, config: Config, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("PROBE_TOKEN", TOKEN) + backend.assign( + "dddddddd-dddd-4ddd-8ddd-dddddddddddd", + b'printf \'{"result_data":{"token":"%s"}}\' "${PROBE_TOKEN-unset}"\n', + ) + + run_once(config) + + assert backend.measurements[0]["result_data"] == {"token": "unset"} + assert backend.download_tokens == [None, None] + + +@pytest.mark.parametrize( + ("script", "expected"), + [ + (b"echo oops >&2; exit 3\n", ("failed", 3, {})), + (b"echo not-json\n", ("failed", 0, {})), + (b'echo \'{"other":1}\'\n', ("failed", 0, {})), + (b'echo \'{"result_data":{"rtt_avg_ms":null,"packet_loss_pct":100}}\'\n', + ("completed", 0, {"rtt_avg_ms": None, "packet_loss_pct": 100})), + ], +) +def test_run_script_statuses(tmp_path: Path, script: bytes, expected: tuple) -> None: + (tmp_path / "run.sh").write_bytes(script) + + assert run_script(str(tmp_path), timeout=10) == expected + + +def test_run_script_timeout(tmp_path: Path) -> None: + (tmp_path / "run.sh").write_bytes(b"exec sleep 5\n") + + assert run_script(str(tmp_path), timeout=0.2) == ("timeout", None, {}) From b8c2e9d59cefbb99bf41a351f1ec5bf960f41693 Mon Sep 17 00:00:00 2001 From: Gaida Amzar Date: Thu, 26 Nov 2026 16:40:09 -0700 Subject: [PATCH 3/4] Run the probe loop from main with graceful shutdown --- probe/compose.yaml | 2 ++ probe/src/probe/__main__.py | 15 +++++++++++++-- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/probe/compose.yaml b/probe/compose.yaml index a0a1dd9..cc49f4b 100644 --- a/probe/compose.yaml +++ b/probe/compose.yaml @@ -2,6 +2,8 @@ services: probe: build: context: . + # Let a pass in progress (script deadline plus upload) finish on stop. + stop_grace_period: 1m env_file: - path: .env required: false diff --git a/probe/src/probe/__main__.py b/probe/src/probe/__main__.py index c7d1e6a..4d2a0ba 100644 --- a/probe/src/probe/__main__.py +++ b/probe/src/probe/__main__.py @@ -1,12 +1,16 @@ -"""Probe bootstrap configuration check.""" +"""Probe entry point: validate configuration, then run the probe loop.""" from __future__ import annotations import os +import signal import sys +import threading import uuid from urllib.parse import urlsplit +from probe.runner import Config, ProbeError, run_loop + def validate_config() -> list[str]: """Return configuration errors without exposing secret values.""" @@ -50,7 +54,14 @@ def main() -> int: print(error, file=sys.stderr) return 1 - print("config valid") + stop = threading.Event() + signal.signal(signal.SIGTERM, lambda *_: stop.set()) + signal.signal(signal.SIGINT, lambda *_: stop.set()) + try: + run_loop(Config.from_env(), stop) + except ProbeError as error: + print(f"probe stopped: {error}", file=sys.stderr) + return 1 return 0 From 024869b531518994526b6dd5d349edf2080fe08d Mon Sep 17 00:00:00 2001 From: Gaida Amzar Date: Thu, 26 Nov 2026 16:40:09 -0700 Subject: [PATCH 4/4] Document the probe loop --- AGENTS.md | 2 +- probe/README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 1816547..169a0b2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -41,7 +41,7 @@ docker compose --env-file .env.example config --quiet docker compose up --build ``` -The probe validates `PROBE_ID`, `BACKEND_URL`, and `PROBE_TOKEN`, prints `config valid`, and exits. For a non-Docker check, run `uv run --locked python -m probe` with those variables set. +The probe validates `PROBE_ID`, `BACKEND_URL`, and `PROBE_TOKEN`, then runs the check-in, test, and upload loop until stopped. For a non-Docker check, run `uv run --locked python -m probe` with those variables set. Probe unit tests live in `probe/tests/`. `uv` reads `probe/.python-version`, so run the commands from `probe/`. Dependencies are declared in `probe/pyproject.toml`; add new Python dependencies with `uv add` and commit `probe/pyproject.toml` and `probe/uv.lock` together. diff --git a/probe/README.md b/probe/README.md index a1dce5c..40c0b8e 100644 --- a/probe/README.md +++ b/probe/README.md @@ -2,7 +2,7 @@ Bootstrap starter for the probe. -The current implementation validates `PROBE_ID`, `BACKEND_URL`, and `PROBE_TOKEN` when run as `python -m probe`, prints `config valid`, and exits. Upcoming tickets cover polling, SQLite storage, test execution, and testing. +When run as `python -m probe`, it validates `PROBE_ID`, `BACKEND_URL`, and `PROBE_TOKEN`, then loops: check in, download and hash-check the assigned `run.sh` and `test.json`, run `bash run.sh` (30 s deadline, without `PROBE_TOKEN` in its environment), and upload the result. With no assignment it waits 30 s and checks again. A server or download error stops the probe with a message. `SIGTERM` or Ctrl-C stops it after the current pass. Measurement intervals, retries, caching, and queues come later. ## Configuration