forked from mtusi2026/mtusi2026lab6
59 lines
1.9 KiB
Python
59 lines
1.9 KiB
Python
"""Local lab6 evidence helpers. Never persist credentials or response bodies."""
|
|
import json
|
|
import subprocess
|
|
import time
|
|
import urllib.parse
|
|
import urllib.request
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
|
|
|
|
def compose(*args, check=True):
|
|
return subprocess.run([str(ROOT / 'scripts/compose.sh'), *args], cwd=ROOT,
|
|
check=check, capture_output=True, text=True)
|
|
|
|
|
|
def start_services(*services):
|
|
# Compose `start` may start dependencies as well. Fault injection must keep
|
|
# an intentionally stopped dependency stopped until its explicit recovery.
|
|
for service in services:
|
|
ids = compose('ps', '-a', '-q', service).stdout.split()
|
|
if not ids:
|
|
raise RuntimeError('Service container not created: ' + service)
|
|
subprocess.run(['docker', 'start', *ids], check=True, stdout=subprocess.DEVNULL)
|
|
|
|
|
|
def get_json(url, timeout=10):
|
|
with urllib.request.urlopen(urllib.request.Request(url, headers={'Accept': 'application/json'}), timeout=timeout) as r:
|
|
return json.load(r)
|
|
|
|
|
|
def prom(query):
|
|
result = get_json('http://127.0.0.1:19090/api/v1/query?' + urllib.parse.urlencode({'query': query}))
|
|
if result.get('status') != 'success':
|
|
raise RuntimeError('Prometheus query failed')
|
|
return result['data']['result']
|
|
|
|
|
|
def scalar(query):
|
|
return sum(float(x['value'][1]) for x in prom(query))
|
|
|
|
|
|
def ready(base='http://127.0.0.1:18086', timeout=120):
|
|
end = time.monotonic() + timeout
|
|
while time.monotonic() < end:
|
|
try:
|
|
if get_json(base + '/health/ready'):
|
|
return
|
|
except Exception:
|
|
pass
|
|
time.sleep(1)
|
|
raise RuntimeError('API readiness deadline exceeded')
|
|
|
|
|
|
def save(path, value):
|
|
path = ROOT / path
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + '\n')
|