feat: secure telemetry ingestion and grafana data sources
This commit is contained in:
@@ -0,0 +1,93 @@
|
||||
"""Send a synthetic HTTPS upload and check its signals through authenticated Grafana."""
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from urllib.error import HTTPError
|
||||
from urllib.parse import urlencode, urlsplit
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--base-url", default="https://localhost:8443")
|
||||
parser.add_argument("--grafana-url", default="https://localhost:3000")
|
||||
parser.add_argument("--ca-file", default=str(ROOT / "secrets/ca.crt"))
|
||||
args = parser.parse_args()
|
||||
grafana = args.grafana_url.rstrip("/")
|
||||
origin = urlsplit(grafana)
|
||||
if origin.scheme != "https" or origin.hostname not in ("localhost", "127.0.0.1") or origin.path:
|
||||
parser.error("--grafana-url must be a local HTTPS origin")
|
||||
ssl_context = ssl.create_default_context(cafile=args.ca_file)
|
||||
password = subprocess.run(
|
||||
["docker", "compose", "exec", "-T", "grafana", "cat", "/run/tls/admin_password"],
|
||||
cwd=ROOT, capture_output=True, check=True,
|
||||
).stdout.strip()
|
||||
header = "Basic " + base64.b64encode(b"admin:" + password).decode()
|
||||
|
||||
def call(path, authenticated=True):
|
||||
req = Request(grafana + "/api/datasources/proxy/uid/" + path,
|
||||
headers={"Authorization": header} if authenticated else {})
|
||||
try:
|
||||
with urlopen(req, context=ssl_context, timeout=7) as response:
|
||||
return response.status, json.load(response)
|
||||
except HTTPError as error:
|
||||
return error.code, {}
|
||||
|
||||
assert call("prometheus/api/v1/query?query=up", authenticated=False)[0] == 401
|
||||
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
owner = client.user("telemetry")
|
||||
chat = client.call("POST", "/api/v1/chats", 201, actor=owner, body={
|
||||
"title": "Telemetry check", "member_ids": [owner["id"]],
|
||||
}, schema="Chat")["json"]
|
||||
trace_id = uuid.uuid4().hex
|
||||
result = client.call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=sample.png",
|
||||
202, actor=owner, raw=(ROOT / "tests/fixtures/sample.png").read_bytes(),
|
||||
headers={"Content-Type": "image/png",
|
||||
"traceparent": f"00-{trace_id}-{uuid.uuid4().hex[:16]}-01"},
|
||||
schema="Attachment")
|
||||
client.wait_ready(owner, result["json"])
|
||||
log_query = urlencode({"query": '{service_name=~"messenger-.+"} | trace_id="' + trace_id + '"',
|
||||
"limit": 50, "since": "10m"})
|
||||
metric_query = urlencode({"query": 'http_server_requests_total or up{job="otel-collector"}'})
|
||||
required = {"messenger-api", "messenger-relay", "messenger-worker"}
|
||||
deadline = time.monotonic() + 60
|
||||
while time.monotonic() < deadline:
|
||||
_, trace = call("tempo/api/traces/" + trace_id)
|
||||
services = {
|
||||
attribute["value"]["stringValue"]
|
||||
for batch in trace.get("batches", [])
|
||||
for attribute in batch.get("resource", {}).get("attributes", [])
|
||||
if attribute["key"] == "service.name"
|
||||
}
|
||||
_, logs = call("loki/loki/api/v1/query_range?" + log_query)
|
||||
log_services = {
|
||||
stream["stream"].get("service_name") for stream in logs.get("data", {}).get("result", [])
|
||||
}
|
||||
_, metrics = call("prometheus/api/v1/query?" + metric_query)
|
||||
series = metrics.get("data", {}).get("result", [])
|
||||
api_metrics = any(row["metric"].get("__name__") == "http_server_requests_total" for row in series)
|
||||
scraped = any(row["metric"].get("job") == "otel-collector" and row["value"][1] == "1" for row in series)
|
||||
if required <= services and {"messenger-api", "messenger-worker"} <= log_services and api_metrics and scraped:
|
||||
print("PASS: authenticated Grafana queries returned API metrics, Collector scrape, "
|
||||
"API/relay/worker spans and API/worker logs for one upload")
|
||||
return
|
||||
time.sleep(2)
|
||||
raise SystemExit("Telemetry incomplete: "
|
||||
f"trace services={sorted(services)}, logs={sorted(log_services)}, "
|
||||
f"API metrics={api_metrics}, Collector scrape={scraped}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user