This repository has been archived on 2026-10-28. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
karldns.de/karldns/store/metrics.py
T

86 lines
2.9 KiB
Python
Raw Normal View History

2026-05-21 10:05:40 +02:00
from __future__ import annotations
from datetime import UTC, datetime
2026-05-22 17:05:06 +02:00
from .base import StoreConnectionMixin
2026-05-21 10:05:40 +02:00
2026-05-22 17:05:06 +02:00
class MetricsMixin(StoreConnectionMixin):
2026-05-21 10:05:40 +02:00
def increment_metric(self, name: str, amount: float = 1.0) -> None:
now = datetime.now(UTC).isoformat()
with self.connect() as conn:
conn.execute(
"""
INSERT INTO service_metrics(name, value, updated_at)
VALUES (?, ?, ?)
ON CONFLICT(name) DO UPDATE SET
value=value + excluded.value,
updated_at=excluded.updated_at
""",
(name, amount, now),
)
def set_metric(self, name: str, value: float) -> None:
now = datetime.now(UTC).isoformat()
with self.connect() as conn:
conn.execute(
"""
INSERT INTO service_metrics(name, value, updated_at)
VALUES (?, ?, ?)
ON CONFLICT(name) DO UPDATE SET
value=excluded.value,
updated_at=excluded.updated_at
""",
(name, value, now),
)
def get_service_metrics(self) -> dict[str, float]:
with self.connect() as conn:
rows = conn.execute("SELECT name, value FROM service_metrics").fetchall()
return {str(row["name"]): float(row["value"]) for row in rows}
def record_update_metrics(
self,
latency_ms: float,
*,
is_success: bool = False,
is_dns_failure: bool = False,
is_reconcile_failure: bool = False,
is_bad_ip: bool = False,
) -> None:
increments = {
"update_requests_total": 1,
"update_latency_ms_total": latency_ms,
"update_latency_samples_total": 1,
}
if is_success:
increments["update_success_total"] = 1
if is_dns_failure:
increments["dns_failures_total"] = 1
if is_reconcile_failure:
increments["dns_reconcile_failures_total"] = 1
if is_bad_ip:
increments["bad_ip_total"] = 1
now = datetime.now(UTC).isoformat()
with self.connect() as conn:
conn.executemany(
"""
INSERT INTO service_metrics(name, value, updated_at)
VALUES (?, ?, ?)
ON CONFLICT(name) DO UPDATE SET
value=value + excluded.value,
updated_at=excluded.updated_at
""",
[(name, value, now) for name, value in increments.items()],
)
conn.execute(
"""
INSERT INTO service_metrics(name, value, updated_at)
VALUES ('last_update_latency_ms', ?, ?)
ON CONFLICT(name) DO UPDATE SET
value=excluded.value,
updated_at=excluded.updated_at
""",
(latency_ms, now),
)