Initialize observability stack with local monitoring and server134 deployment
This commit is contained in:
@@ -0,0 +1,134 @@
|
||||
"""Write fresh synthetic Metrics, Logs and Traces, then query this run's data."""
|
||||
from datetime import datetime, timezone
|
||||
import base64
|
||||
import json
|
||||
import secrets
|
||||
from pathlib import Path
|
||||
import time
|
||||
from urllib.error import URLError
|
||||
from urllib.parse import urlencode
|
||||
from urllib.request import Request, build_opener, ProxyHandler
|
||||
|
||||
# Local validation must not go through a workstation HTTP proxy.
|
||||
HTTP = build_opener(ProxyHandler({}))
|
||||
|
||||
|
||||
def request(url, data=None, content_type="application/json"):
|
||||
headers = {"Accept": "application/json"}
|
||||
if data is not None:
|
||||
headers["Content-Type"] = content_type
|
||||
with HTTP.open(Request(url, data=data, headers=headers), timeout=10) as response:
|
||||
return response.read().decode("utf-8")
|
||||
|
||||
|
||||
def poll(name, check, seconds=120):
|
||||
deadline = time.monotonic() + seconds
|
||||
detail = "condition not met"
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
if check():
|
||||
print(f"PASS: {name}", flush=True)
|
||||
return
|
||||
except (URLError, TimeoutError, OSError, ValueError) as exc:
|
||||
detail = str(exc)
|
||||
time.sleep(2)
|
||||
raise RuntimeError(f"FAIL: {name}: {detail}")
|
||||
|
||||
|
||||
def grafana_smoke(url, password, username="admin", dashboard_uid="new-api-local"):
|
||||
# Read a local secret into memory; never print credentials or Authorization headers.
|
||||
auth = base64.b64encode((username + ":" + password.strip()).encode()).decode()
|
||||
|
||||
def api(path):
|
||||
with HTTP.open(Request(url + path, headers={"Authorization": "Basic " + auth}), timeout=15) as response:
|
||||
return json.load(response)
|
||||
|
||||
for uid in ("victoriametrics", "victorialogs", "tempo"):
|
||||
poll(f"Grafana {uid} datasource", lambda uid=uid: api(f"/api/datasources/uid/{uid}/health").get("status") == "OK")
|
||||
poll(f"Grafana {dashboard_uid} dashboard", lambda: api(f"/api/dashboards/uid/{dashboard_uid}")["dashboard"]["uid"] == dashboard_uid)
|
||||
|
||||
|
||||
def smoke(endpoints, application=False):
|
||||
checks = [("victoriametrics", 8428, "/health"), ("victorialogs", 9428, "/health"),
|
||||
("tempo", 3200, "/ready"), ("alertmanager", 9093, "/-/ready"),
|
||||
("vmalert", 8880, "/health"), ("vmagent", 8429, "/health"),
|
||||
("grafana", 3000, "/api/health")]
|
||||
if ("node-exporter", 9100) in endpoints:
|
||||
checks.append(("node-exporter", 9100, "/metrics"))
|
||||
for service, port, path in checks:
|
||||
def ready(url=endpoints[(service, port)] + path):
|
||||
request(url)
|
||||
return True
|
||||
# First Grafana startup downloads the pinned datasource plugin (~78 MB).
|
||||
poll(f"{service} ready", ready, seconds=600 if service == "grafana" else 120)
|
||||
|
||||
vm = endpoints[("victoriametrics", 8428)]
|
||||
vl = endpoints[("victorialogs", 9428)]
|
||||
tempo = endpoints[("tempo", 3200)]
|
||||
run_id = secrets.token_hex(8)
|
||||
trace_id, span_id = secrets.token_hex(16), secrets.token_hex(8)
|
||||
|
||||
# Omit the optional text timestamp so VM uses receipt time (not seconds as milliseconds).
|
||||
request(vm + "/api/v1/import/prometheus",
|
||||
f'observability_smoke{{source="smoke-test",run_id="{run_id}"}} 1\n'.encode(), "text/plain")
|
||||
|
||||
def query(expression):
|
||||
payload = json.loads(request(vm + "/api/v1/query?" + urlencode({"query": expression, "nocache": "1"})))
|
||||
if payload.get("status") != "success":
|
||||
raise ValueError("Metrics query failed")
|
||||
return payload["data"]["result"]
|
||||
|
||||
poll("Metrics fresh write/query", lambda: any(float(row["value"][1]) == 1
|
||||
for row in query(f'observability_smoke{{run_id="{run_id}"}}')))
|
||||
|
||||
entry = {"_time": datetime.now(timezone.utc).isoformat(), "service": "observability-smoke",
|
||||
"host": "local-smoke", "message": "synthetic smoke " + run_id, "trace_id": trace_id}
|
||||
request(vl + "/insert/jsonline?_stream_fields=service,host&_msg_field=message&_time_field=_time",
|
||||
(json.dumps(entry) + "\n").encode(), "application/stream+json")
|
||||
log_query = urlencode({"query": f'service:="observability-smoke" AND trace_id:="{trace_id}"', "limit": "10"})
|
||||
poll("Logs fresh write/query", lambda: run_id in request(vl + "/select/logsql/query?" + log_query))
|
||||
|
||||
now = time.time_ns()
|
||||
payload = {"resourceSpans": [{"resource": {"attributes": [
|
||||
{"key": "service.name", "value": {"stringValue": "observability-smoke"}}]},
|
||||
"scopeSpans": [{"scope": {"name": "local-smoke"}, "spans": [{
|
||||
"traceId": trace_id, "spanId": span_id, "name": "smoke-" + run_id, "kind": 2,
|
||||
"startTimeUnixNano": str(now - 1000000), "endTimeUnixNano": str(now),
|
||||
"status": {"code": 1}}]}]}]}
|
||||
response = json.loads(request(endpoints[("tempo", 4318)] + "/v1/traces", json.dumps(payload).encode()) or "{}")
|
||||
if int(response.get("partialSuccess", {}).get("rejectedSpans", 0)):
|
||||
raise RuntimeError("Tempo rejected smoke span")
|
||||
poll("Traces fresh OTLP write/exact trace query",
|
||||
lambda: "smoke-" + run_id in request(tempo + "/api/traces/" + trace_id))
|
||||
|
||||
if application:
|
||||
poll("new-api /api/status probe success", lambda: any(float(row["value"][1]) == 1
|
||||
for row in query('probe_success{job="new-api-health"}')))
|
||||
poll("new-api HTTP 200 recorded", lambda: any(float(row["value"][1]) == 200
|
||||
for row in query('probe_http_status_code{job="new-api-health"}')))
|
||||
poll("all configured scrapes healthy", lambda: bool(query("up"))
|
||||
and all(float(row["value"][1]) == 1 for row in query("up")))
|
||||
print(f"All smoke tests passed. Synthetic run={run_id}, trace={trace_id}", flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
ports = {"victoriametrics": [8428], "victorialogs": [9428], "tempo": [3200, 4318],
|
||||
"alertmanager": [9093], "vmalert": [8880], "vmagent": [8429],
|
||||
"node-exporter": [9100], "grafana": [3000]}
|
||||
# Parse generated KEY=value settings as data; never execute .env as shell code.
|
||||
settings = {}
|
||||
env_file = Path(__file__).resolve().parents[1] / ".env"
|
||||
if env_file.exists():
|
||||
for line in env_file.read_text().splitlines():
|
||||
if line.strip() and not line.lstrip().startswith("#") and "=" in line:
|
||||
key, value = line.split("=", 1)
|
||||
settings[key.strip()] = value.strip().strip("\"'")
|
||||
grafana_port = int(settings.get("GRAFANA_PORT", "3000"))
|
||||
if not 1 <= grafana_port <= 65535:
|
||||
raise ValueError("GRAFANA_PORT must be between 1 and 65535")
|
||||
endpoints = {(name, port): f"http://127.0.0.1:{port}" for name, numbers in ports.items() for port in numbers}
|
||||
endpoints[("grafana", 3000)] = f"http://127.0.0.1:{grafana_port}"
|
||||
smoke(endpoints)
|
||||
if settings.get("GRAFANA_ADMIN_PASSWORD"):
|
||||
grafana_smoke(endpoints[("grafana", 3000)], settings["GRAFANA_ADMIN_PASSWORD"],
|
||||
settings.get("GRAFANA_ADMIN_USER", "admin"), "monitor-host-overview")
|
||||
Reference in New Issue
Block a user