Files
mtusi2026lab7/tests/observability.py
T
Бахрам 1df2202403
Skeleton contracts / contracts (pull_request) Canceled after 0s
Complete lab 7 TLS and secret management
2026-12-01 22:44:28 +03:00

145 lines
5.6 KiB
Python

"""Verify the protected Prometheus, Loki, Tempo and Grafana endpoints."""
import base64
import json
import os
from pathlib import Path
import ssl
import time
import urllib.parse
import urllib.request
ROOT = Path(__file__).resolve().parents[1]
PKI = ROOT / '.local' / 'pki'
PROM = os.getenv('PROM_URL', 'https://localhost:9097')
LOKI = os.getenv('LOKI_URL', 'https://localhost:3107')
TEMPO = os.getenv('TEMPO_URL', 'https://localhost:3207')
GRAFANA = os.getenv('GRAFANA_URL', 'https://localhost:3007')
def context_for(url):
context = ssl.create_default_context(cafile=str(PKI / 'service-ca.crt'))
if url.startswith((PROM, LOKI, TEMPO)):
context.load_cert_chain(str(PKI / 'backend-grafana.crt'), str(PKI / 'backend-grafana.key'))
return context
def get_json(url, auth=None):
request = urllib.request.Request(url)
if auth:
token = base64.b64encode((auth[0] + ':' + auth[1]).encode()).decode()
request.add_header('Authorization', 'Basic ' + token)
with urllib.request.urlopen(request, context=context_for(url), timeout=8) as response:
return json.load(response)
def grafana_password():
value = os.getenv('GRAFANA_PASSWORD')
if value:
return value
env_file = ROOT / '.env'
if env_file.exists():
for line in env_file.read_text().splitlines():
if line.startswith('GRAFANA_PASSWORD='):
return line.split('=', 1)[1]
return 'local-grafana-password-only'
def prom_value(expr):
doc = get_json(PROM + '/api/v1/query?' + urllib.parse.urlencode({'query': expr}))
assert doc['status'] == 'success', doc
result = doc['data']['result']
return float(result[0]['value'][1]) if result else 0.0
def main():
deadline = time.time() + 90
api_total = worker_total = 0.0
while time.time() < deadline:
try:
api_total = prom_value('sum(messenger_http_requests_total)')
worker_total = prom_value('sum(messenger_jobs_processed_total)')
if api_total > 0 and worker_total > 0:
break
except Exception:
pass
time.sleep(2)
assert api_total > 0, 'API request metric not found in Prometheus'
assert worker_total > 0, 'worker job metric not found in Prometheus'
start = int((time.time() - 900) * 1_000_000_000)
end = time.time_ns()
q = '{service_name="messenger-api"} |= "http.request.completed"'
url = LOKI + '/loki/api/v1/query_range?' + urllib.parse.urlencode(
{'query': q, 'start': str(start), 'end': str(end), 'limit': '20', 'direction': 'backward'})
logs = get_json(url)
assert logs['status'] == 'success' and logs['data']['result'], 'API structured logs not found in Loki'
deadline = time.time() + 90
while time.time() < deadline:
try:
with urllib.request.urlopen(TEMPO + '/ready', context=context_for(TEMPO), timeout=5) as response:
if response.status == 200:
break
except Exception:
time.sleep(2)
else:
raise AssertionError('Tempo did not become ready')
def trace_search(service):
params = {'tags': 'service.name=' + service, 'start': str(int(time.time() - 900)),
'end': str(int(time.time())), 'limit': '20'}
return get_json(TEMPO + '/api/search?' + urllib.parse.urlencode(params)).get('traces', [])
api_traces = worker_traces = []
deadline = time.time() + 90
while time.time() < deadline:
try:
api_traces = trace_search('messenger-api')
worker_traces = trace_search('messenger-worker')
if api_traces and worker_traces:
break
except Exception:
pass
time.sleep(3)
assert api_traces, 'API traces not found in Tempo'
assert worker_traces, 'worker traces not found in Tempo'
correlated_trace = None
deadline = time.time() + 90
while time.time() < deadline and correlated_trace is None:
q = '{service_name="messenger-worker"} |= "worker.job.completed"'
params = {'query': q, 'start': str(int((time.time() - 900) * 1_000_000_000)),
'end': str(time.time_ns()), 'limit': '20', 'direction': 'backward'}
rows = get_json(LOKI + '/loki/api/v1/query_range?' + urllib.parse.urlencode(params))['data']['result']
for row in rows:
trace_id = row['stream'].get('trace_id')
if not trace_id:
continue
try:
trace_doc = get_json(TEMPO + '/api/traces/' + trace_id)
except Exception:
continue
services = set()
for batch in trace_doc.get('batches', []):
for attr in batch.get('resource', {}).get('attributes', []):
if attr.get('key') == 'service.name':
services.add(attr.get('value', {}).get('stringValue'))
if {'messenger-api', 'messenger-worker'} <= services:
correlated_trace = trace_id
break
if correlated_trace is None:
time.sleep(2)
assert correlated_trace, 'worker log trace is not correlated with API trace'
health = get_json(GRAFANA + '/api/health')
assert health.get('database') == 'ok', 'Grafana is not ready'
password = grafana_password()
dashboard = get_json(GRAFANA + '/api/dashboards/uid/messenger-observability', ('admin', password))
assert dashboard.get('dashboard', {}).get('uid') == 'messenger-observability', 'provisioned dashboard is missing'
print('PASS: protected Prometheus/Loki/Tempo; API and worker telemetry; correlated traces; Grafana dashboard')
if __name__ == '__main__':
main()