|
| 1 | +"""Lightweight client for reporting check results to Kuberhealthy.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import json |
| 6 | +import os |
| 7 | +import urllib.request |
| 8 | +from typing import Optional |
| 9 | + |
| 10 | +KH_REPORTING_URL = "KH_REPORTING_URL" |
| 11 | +KH_RUN_UUID = "KH_RUN_UUID" |
| 12 | + |
| 13 | +def _get_env(name: str) -> str: |
| 14 | + """Return the value of the environment variable *name* or raise an error.""" |
| 15 | + value = os.getenv(name) |
| 16 | + if not value: |
| 17 | + raise EnvironmentError(f"{name} must be set") |
| 18 | + return value |
| 19 | + |
| 20 | +def _post_status(payload: dict, *, url: Optional[str] = None, run_uuid: Optional[str] = None) -> None: |
| 21 | + """Send *payload* to the Kuberhealthy reporting URL.""" |
| 22 | + url = url or _get_env(KH_REPORTING_URL) |
| 23 | + run_uuid = run_uuid or _get_env(KH_RUN_UUID) |
| 24 | + data = json.dumps(payload).encode("utf-8") |
| 25 | + request = urllib.request.Request( |
| 26 | + url, |
| 27 | + data=data, |
| 28 | + headers={"content-type": "application/json", "kh-run-uuid": run_uuid}, |
| 29 | + ) |
| 30 | + with urllib.request.urlopen(request, timeout=10) as response: # nosec B310 |
| 31 | + response.read() |
| 32 | + |
| 33 | +def report_ok(*, url: Optional[str] = None, run_uuid: Optional[str] = None) -> None: |
| 34 | + """Report a successful check to Kuberhealthy.""" |
| 35 | + _post_status({"OK": True, "Errors": []}, url=url, run_uuid=run_uuid) |
| 36 | + |
| 37 | +def report_error(message: str, *, url: Optional[str] = None, run_uuid: Optional[str] = None) -> None: |
| 38 | + """Report a failure to Kuberhealthy with *message* as the error.""" |
| 39 | + _post_status({"OK": False, "Errors": [message]}, url=url, run_uuid=run_uuid) |
| 40 | + |
| 41 | +__all__ = ["report_ok", "report_error", "KH_REPORTING_URL", "KH_RUN_UUID"] |
0 commit comments