Add healthcheck

This commit is contained in:
2026-06-02 04:33:12 -04:00
parent 1fd7803f12
commit 242820f9d1
5 changed files with 33 additions and 3 deletions
+26 -1
View File
@@ -2,6 +2,8 @@ from __future__ import annotations
import logging
import time
import urllib.error
import urllib.request
from datetime import datetime, timezone
from typing import Any
@@ -73,6 +75,27 @@ def save_reading(device: Device, status: dict[str, Any]) -> None:
)
def _ping_healthcheck(success: bool, detail: str | None = None) -> None:
url = config.healthcheck_url
if not url:
logger.debug("Healthcheck ping skipped: HEALTHCHECK_URL not configured")
return
try:
if success:
logger.debug("Pinging healthcheck (success): %s", url)
urllib.request.urlopen(url, timeout=10) # noqa: S310
logger.info("Healthcheck ping sent successfully")
else:
fail_url = f"{url}/fail"
logger.debug("Pinging healthcheck (fail): %s%s", fail_url, detail)
payload = (detail or "").encode()
req = urllib.request.Request(fail_url, data=payload, method="POST")
urllib.request.urlopen(req, timeout=10) # noqa: S310
logger.info("Healthcheck fail ping sent: %s", detail)
except Exception as exc: # noqa: BLE001
logger.warning("Healthcheck ping failed: %s", exc)
def collect_once(client: SwitchBotClient) -> None:
logger.info("Starting collection cycle")
devices = sync_devices(client)
@@ -106,8 +129,10 @@ def main() -> int:
started = time.monotonic()
try:
collect_once(client)
except Exception:
_ping_healthcheck(True)
except Exception as exc:
logger.exception("Collector cycle failed")
_ping_healthcheck(False, str(exc))
elapsed = time.monotonic() - started
time.sleep(max(1, interval - elapsed))