"""Read-only Prometheus access through the Kubernetes API proxy. No port-forward, no extra credentials: `kubectl get --raw` against the monitoring Service proxy works from the admin host as the operator. """ from __future__ import annotations import json import os import shutil import subprocess import urllib.parse from typing import Iterable, List, Tuple from . import config class SensorError(Exception): """A sensor input is unavailable. `cls` is the memoizable failure class.""" def __init__(self, cls: str, detail: str = ""): super().__init__(detail or cls) self.cls = cls self.detail = detail def _which(candidates: Iterable[str]) -> str: for cand in candidates: path = shutil.which(cand) if not cand.startswith("/") else (cand if os.path.exists(cand) else None) if path: return path raise SensorError("no-kubectl", "kubectl not found in PATH") def _classify(text: str) -> str: low = text.lower() if "503" in low or "serviceunavailable" in low or "service unavailable" in low: return "HTTP 503" if "timeout" in low or "timed out" in low or "deadline" in low: return "timeout" if "connection refused" in low or "no such host" in low: return "api-unreachable" return "prom-error" def raw(path: str) -> dict: kubectl = _which(config.KUBECTL_CANDIDATES) try: proc = subprocess.run( [kubectl, "get", "--raw", path], capture_output=True, text=True, timeout=config.PROM_TIMEOUT, ) except subprocess.TimeoutExpired: raise SensorError("timeout", "kubectl get --raw exceeded %ss" % config.PROM_TIMEOUT) if proc.returncode != 0: raise SensorError(_classify(proc.stderr or proc.stdout), (proc.stderr or "").strip()[:200]) try: return json.loads(proc.stdout) except ValueError: raise SensorError("prom-bad-json", proc.stdout[:120]) def query(expr: str) -> List[Tuple[dict, float]]: """Instant query. Returns [(metric_labels, value)] or raises SensorError.""" path = config.PROM_PROXY + "/api/v1/query?query=" + urllib.parse.quote(expr) payload = raw(path) if payload.get("status") != "success": raise SensorError("prom-error", str(payload.get("error", ""))[:160]) out: List[Tuple[dict, float]] = [] for series in payload["data"]["result"]: try: out.append((series.get("metric") or {}, float(series["value"][1]))) except (KeyError, IndexError, ValueError): continue return out def scalar(expr: str) -> float: """Sum of an (expected single-series) query; 0.0 when it matches nothing.""" return sum(v for _, v in query(expr))