feat(monitors): unify ping/dns/http into one Monitor entity + custom targets
Collapse the three former check types into a single core `Monitor` entity
with one management surface (/monitors), one result table (monitor_results),
and a single scheduled task. Every type can now watch a free-standing custom
destination (optional host_id) — not just a registered Host.
- models: Monitor + MonitorResult replace PingResult/DnsResult; Host loses its
ping/dns facet columns (now Monitor rows linked by host_id).
- checks: monitors/{ping,dns,http}.py pure probes + runner.run_monitor
dispatcher; one monitor_check scheduler with a per-monitor due-filter.
- status: single monitor_status_source replaces the three sources.
- UI: /monitors blueprint (type-aware add/edit/list/widget); host hub shows a
host's linked monitors + "add monitor for this host"; nav + widget registry
+ alert metric catalog rewired. http plugin folded into core and removed.
- migration 0022 merges the http branch, data-migrates host facets +
http_monitors + all three result histories, drops the old tables/columns.
Resolves the per-host ping/dns auto-attach issue (#275): monitors are now
explicit, never auto-added to every host.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016Jg27rgypiW2efULXJDtMC
This commit is contained in:
@@ -0,0 +1,100 @@
|
||||
"""HTTP(S) check — one synthetic request, returns a normalised result dict.
|
||||
|
||||
Moved into core from the former http plugin (plugins/http/checker.py) when
|
||||
ping/dns/http were unified under the Monitor entity.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import asyncio
|
||||
import logging
|
||||
import ssl
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import httpx
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def _get_tls_expiry(hostname: str, port: int) -> datetime | None:
|
||||
"""Bare TLS handshake to read the certificate's notAfter date."""
|
||||
ctx = ssl.create_default_context()
|
||||
try:
|
||||
reader, writer = await asyncio.wait_for(
|
||||
asyncio.open_connection(hostname, port, ssl=ctx),
|
||||
timeout=5.0,
|
||||
)
|
||||
cert = writer.get_extra_info("ssl_object").getpeercert()
|
||||
writer.close()
|
||||
try:
|
||||
await writer.wait_closed()
|
||||
except Exception:
|
||||
pass
|
||||
exp_str = cert.get("notAfter", "")
|
||||
if not exp_str:
|
||||
return None
|
||||
# Format: "Mar 22 12:00:00 2027 GMT"
|
||||
return datetime.strptime(exp_str, "%b %d %H:%M:%S %Y %Z").replace(
|
||||
tzinfo=timezone.utc
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.debug("TLS check failed for %s:%d — %s", hostname, port, exc)
|
||||
return None
|
||||
|
||||
|
||||
async def http_check(
|
||||
url: str,
|
||||
method: str = "GET",
|
||||
expected_status: int = 200,
|
||||
content_match: str = "",
|
||||
headers: dict | None = None,
|
||||
timeout_seconds: int = 10,
|
||||
follow_redirects: bool = True,
|
||||
verify_ssl: bool = True,
|
||||
) -> dict:
|
||||
"""Perform one HTTP check. Returns the MonitorResult field dict."""
|
||||
result: dict = {
|
||||
"is_up": False,
|
||||
"status_code": None,
|
||||
"response_ms": None,
|
||||
"content_matched": None,
|
||||
"error_msg": None,
|
||||
"tls_expires_at": None,
|
||||
}
|
||||
|
||||
parsed = urlparse(url)
|
||||
is_https = parsed.scheme.lower() == "https"
|
||||
|
||||
t0 = time.monotonic()
|
||||
try:
|
||||
async with httpx.AsyncClient(
|
||||
follow_redirects=follow_redirects,
|
||||
verify=verify_ssl,
|
||||
timeout=timeout_seconds,
|
||||
) as client:
|
||||
response = await client.request(method, url, headers=headers or {})
|
||||
result["response_ms"] = round((time.monotonic() - t0) * 1000, 1)
|
||||
result["status_code"] = response.status_code
|
||||
|
||||
status_ok = response.status_code == expected_status
|
||||
if content_match:
|
||||
matched = content_match in response.text
|
||||
result["content_matched"] = matched
|
||||
result["is_up"] = status_ok and matched
|
||||
else:
|
||||
result["is_up"] = status_ok
|
||||
|
||||
except httpx.TimeoutException:
|
||||
result["response_ms"] = round((time.monotonic() - t0) * 1000, 1)
|
||||
result["error_msg"] = "Timeout"
|
||||
except httpx.ConnectError as exc:
|
||||
result["error_msg"] = f"Connection error: {exc}"
|
||||
except Exception as exc:
|
||||
result["error_msg"] = str(exc)[:512]
|
||||
|
||||
# TLS expiry — only for HTTPS once we have any response.
|
||||
if is_https and result["status_code"] is not None and parsed.hostname:
|
||||
port = parsed.port or 443
|
||||
result["tls_expires_at"] = await _get_tls_expiry(parsed.hostname, port)
|
||||
|
||||
return result
|
||||
Reference in New Issue
Block a user