120 lines
4.6 KiB
Python
120 lines
4.6 KiB
Python
|
|
"""Read-only Loki access through the Kubernetes API proxy.
|
||
|
|
|
||
|
|
Same access model as `prom.py`: no port-forward, no extra credentials, no
|
||
|
|
cluster writes — `kubectl get --raw` against the `logging/loki` Service proxy as
|
||
|
|
the operator. Only the (small) matching line set is returned; the filtering
|
||
|
|
happens in LogQL so the agent never pulls the whole 528 MB/day ingress stream
|
||
|
|
into this process (see `http_rules.py`).
|
||
|
|
|
||
|
|
Two shapes are used:
|
||
|
|
|
||
|
|
* `query_range(...)` for "give me the matching log lines in this window"
|
||
|
|
(attack-shape rules). Bounded by `limit`, newest first.
|
||
|
|
* `query(...)` for an instant metric query (per-client 401/403 rate, aggregated
|
||
|
|
by Loki into one series per client).
|
||
|
|
"""
|
||
|
|
|
||
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
import json
|
||
|
|
import subprocess
|
||
|
|
import urllib.parse
|
||
|
|
from typing import Dict, List, Tuple
|
||
|
|
|
||
|
|
from . import config
|
||
|
|
from .prom import SensorError, _which
|
||
|
|
|
||
|
|
|
||
|
|
def _classify(text: str) -> str:
|
||
|
|
low = text.lower()
|
||
|
|
if "503" in low or "service unavailable" in low or "serviceunavailable" in low:
|
||
|
|
return "loki-503"
|
||
|
|
if "timeout" in low or "timed out" in low or "deadline" in low:
|
||
|
|
return "loki-timeout"
|
||
|
|
if "connection refused" in low or "no such host" in low:
|
||
|
|
return "loki-unreachable"
|
||
|
|
return "loki-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.LOKI_TIMEOUT,
|
||
|
|
)
|
||
|
|
except subprocess.TimeoutExpired:
|
||
|
|
raise SensorError("loki-timeout", "kubectl get --raw exceeded %ss" % config.LOKI_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("loki-bad-json", proc.stdout[:120])
|
||
|
|
|
||
|
|
|
||
|
|
def _payload(payload: dict) -> dict:
|
||
|
|
if payload.get("status") != "success":
|
||
|
|
raise SensorError("loki-error", str(payload.get("error", ""))[:160])
|
||
|
|
return payload["data"]
|
||
|
|
|
||
|
|
|
||
|
|
def query_range(expr: str, start: float, end: float, limit: int = 600) -> Tuple[List[Tuple[dict, List[Tuple[str, str]]]], dict]:
|
||
|
|
"""Log lines matching `expr` in [start, end]; newest first, `limit` bounded.
|
||
|
|
|
||
|
|
Returns `(streams, summary)` where summary is Loki's own
|
||
|
|
`stats.summary` (bytes/lines processed, exec time) so the tick can report how
|
||
|
|
much it actually read rather than guessing from the window length.
|
||
|
|
"""
|
||
|
|
params = {
|
||
|
|
"query": expr,
|
||
|
|
"start": "%d000000000" % int(start),
|
||
|
|
"end": "%d000000000" % int(end),
|
||
|
|
"limit": str(int(limit)),
|
||
|
|
"direction": "backward",
|
||
|
|
}
|
||
|
|
path = config.LOKI_PROXY + "/loki/api/v1/query_range?" + urllib.parse.urlencode(params)
|
||
|
|
payload = _raw(path)
|
||
|
|
data = _payload(payload)
|
||
|
|
out: List[Tuple[dict, List[Tuple[str, str]]]] = []
|
||
|
|
for stream in data.get("result") or []:
|
||
|
|
values = [(str(v[0]), str(v[1])) for v in (stream.get("values") or []) if len(v) >= 2]
|
||
|
|
out.append((stream.get("stream") or {}, values))
|
||
|
|
summary = ((payload.get("stats") or {}).get("summary") or {})
|
||
|
|
return out, summary
|
||
|
|
|
||
|
|
|
||
|
|
def query(expr: str, at: float) -> List[Tuple[dict, float]]:
|
||
|
|
"""Instant metric query -> [(labels, value)] (0 series on no match)."""
|
||
|
|
params = {"query": expr, "time": "%d000000000" % int(at)}
|
||
|
|
path = config.LOKI_PROXY + "/loki/api/v1/query?" + urllib.parse.urlencode(params)
|
||
|
|
data = _payload(_raw(path))
|
||
|
|
out: List[Tuple[dict, float]] = []
|
||
|
|
for series in data.get("result") or []:
|
||
|
|
try:
|
||
|
|
out.append((series.get("metric") or {}, float(series["value"][1])))
|
||
|
|
except (KeyError, IndexError, ValueError):
|
||
|
|
continue
|
||
|
|
return out
|
||
|
|
|
||
|
|
|
||
|
|
def query_matrix(expr: str, start: float, end: float, step: int) -> List[Tuple[dict, List[Tuple[float, float]]]]:
|
||
|
|
"""Range metric query -> [(labels, [(ts, value)])]."""
|
||
|
|
params = {
|
||
|
|
"query": expr,
|
||
|
|
"start": "%d000000000" % int(start),
|
||
|
|
"end": "%d000000000" % int(end),
|
||
|
|
"step": str(int(step)),
|
||
|
|
}
|
||
|
|
path = config.LOKI_PROXY + "/loki/api/v1/query_range?" + urllib.parse.urlencode(params)
|
||
|
|
data = _payload(_raw(path))
|
||
|
|
out: List[Tuple[dict, List[Tuple[float, float]]]] = []
|
||
|
|
for series in data.get("result") or []:
|
||
|
|
values: List[Tuple[float, float]] = []
|
||
|
|
for point in series.get("values") or []:
|
||
|
|
try:
|
||
|
|
values.append((float(point[0]), float(point[1])))
|
||
|
|
except (IndexError, ValueError):
|
||
|
|
continue
|
||
|
|
out.append((series.get("metric") or {}, values))
|
||
|
|
return out
|