forked from mtusi2026/mtusi2026lab6
lab6: observability, otel, grafana, incidents and dashboard
This commit is contained in:
@@ -0,0 +1,13 @@
|
||||
"""Convenience runner. Does not fabricate evidence or control Docker itself."""
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
for command in (
|
||||
[sys.executable, str(ROOT / "tests/smoke.py")],
|
||||
[sys.executable, str(ROOT / "student-tests/run.py")],
|
||||
[sys.executable, str(ROOT / "student-tests/test_attachments.py")],
|
||||
):
|
||||
print("RUN:", " ".join(command), flush=True)
|
||||
subprocess.run(command, cwd=ROOT, check=True)
|
||||
print("PASS: public smoke + lab3 concurrency + grade4 negative cases; run extra resilience and memory experiment separately")
|
||||
@@ -0,0 +1,71 @@
|
||||
"""10 simultaneous real uploads + Docker RSS observations (NO invented metrics)."""
|
||||
import concurrent.futures
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
from statistics import median
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, check, arguments, run
|
||||
|
||||
|
||||
def mib(value):
|
||||
value = value.strip()
|
||||
for suffix, multiplier in (("GiB",1024),("MiB",1),("KiB",1/1024),("B",1/1048576)):
|
||||
if value.endswith(suffix):
|
||||
return float(value[:-len(suffix)]) * multiplier
|
||||
return None
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Concurrent uploads + observed API container memory')
|
||||
client = Client(args.base_url, args.ca_file, timeout=30)
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
file = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
results, memory = [], []
|
||||
stop = threading.Event()
|
||||
def observe():
|
||||
while not stop.is_set():
|
||||
r = subprocess.run(['docker','stats','--no-stream','--format','{{.Name}}|{{.MemUsage}}'],
|
||||
capture_output=True, text=True, timeout=10)
|
||||
if r.returncode == 0:
|
||||
for line in r.stdout.splitlines():
|
||||
if '|api1-' in line or '|api2-' in line:
|
||||
pass
|
||||
parts = line.split('|')
|
||||
if len(parts)==2 and ('api1-' in parts[0] or 'api2-' in parts[0]):
|
||||
amount = mib(parts[1].split('/')[0])
|
||||
if amount is not None:
|
||||
memory.append({'container': parts[0], 'mem_mib': round(amount,3)})
|
||||
stop.wait(0.2)
|
||||
monitor = threading.Thread(target=observe, daemon=True)
|
||||
monitor.start()
|
||||
try:
|
||||
def worker(i):
|
||||
local = Client(args.base_url,args.ca_file,timeout=30)
|
||||
start=time.perf_counter()
|
||||
resp=local.call('POST', f'/api/v1/chats/{chat["id"]}/attachments?filename=run{i}.png',
|
||||
202, actor=alice, raw=file, headers={'Content-Type':'image/png'}, schema='Attachment')
|
||||
return {'elapsed_ms':round((time.perf_counter()-start)*1000,2), 'instance': resp['headers'].get('X-Instance-Id')}
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
|
||||
futures=[executor.submit(worker,i) for i in range(10)]
|
||||
results=[f.result() for f in concurrent.futures.as_completed(futures)]
|
||||
finally:
|
||||
stop.set(); monitor.join(timeout=12)
|
||||
output={'concurrency':10,'file_bytes':len(file),'completed':len(results),
|
||||
'median_latency_ms':round(median(x['elapsed_ms'] for x in results),2),
|
||||
'api_peak_mem_mib_observed':max([x['mem_mib'] for x in memory],default=None),
|
||||
'memory_samples':len(memory),'instances':sorted(set(x['instance'] for x in results))}
|
||||
target=ROOT / 'evidence' / 'uploads-10.json'
|
||||
target.write_text(json.dumps(output,ensure_ascii=False,indent=2),encoding='utf-8')
|
||||
check(len(results)==10, 'not all uploads completed')
|
||||
print('PASS: 10 parallel uploads; metrics written:',target)
|
||||
print(json.dumps(output, ensure_ascii=False, indent=2))
|
||||
if not memory:
|
||||
print('WARNING: no Docker memory samples; run docker stats separately for a valid grade-4 experiment')
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,95 @@
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import secrets
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
BASE = 'http://localhost:8080'
|
||||
|
||||
|
||||
def call(method, url, body=None, headers=None):
|
||||
request = urllib.request.Request(url, data=body, headers=headers or {}, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=15) as response:
|
||||
raw = response.read()
|
||||
return response.status, json.loads(raw) if raw else {}
|
||||
except urllib.error.HTTPError as error:
|
||||
raw = error.read()
|
||||
return error.code, json.loads(raw) if raw else {}
|
||||
|
||||
|
||||
def json_request(method, path, data, auth=None):
|
||||
headers = {'Content-Type':'application/json'}
|
||||
if auth:
|
||||
headers['Authorization'] = 'Bearer '+auth
|
||||
return call(method, BASE+path, json.dumps(data).encode(), headers)
|
||||
|
||||
|
||||
def docker(*args):
|
||||
subprocess.run(['docker', 'compose', *args], check=True)
|
||||
|
||||
|
||||
def alerts():
|
||||
try:
|
||||
code, result = call('GET', 'http://localhost:9090/api/v1/alerts')
|
||||
if code == 200:
|
||||
return {a['labels'].get('alertname'):a['state'] for a in result['data']['alerts']}
|
||||
except Exception:
|
||||
pass
|
||||
return {}
|
||||
|
||||
|
||||
def main():
|
||||
cli = argparse.ArgumentParser()
|
||||
cli.add_argument('--hold', type=int, default=50)
|
||||
opts = cli.parse_args()
|
||||
username = 'obs'+secrets.token_hex(6)
|
||||
password = secrets.token_urlsafe(24)
|
||||
status, user = json_request('POST','/api/v1/users',{'username':username,'password':password,'display_name':'Lab6 Test'})
|
||||
assert status == 201, user
|
||||
basic = base64.b64encode((username+':'+password).encode()).decode()
|
||||
status, auth = call('POST',BASE+'/api/v1/auth/sessions',b'',{'Authorization':'Basic '+basic})
|
||||
assert status == 201, auth
|
||||
token = auth['token']
|
||||
status, chat = json_request('POST','/api/v1/chats',{'title':'Lab6 Incident','member_ids':[user['id']]},token)
|
||||
assert status == 201, chat
|
||||
docker('stop','worker')
|
||||
ready = False
|
||||
try:
|
||||
sample = Path('tests/fixtures/sample.png').read_bytes()
|
||||
status, attachment = call('POST', BASE+f"/api/v1/chats/{chat['id']}/attachments?filename=sample.png",
|
||||
sample, {'Content-Type':'image/png','Authorization':'Bearer '+token})
|
||||
assert status == 202 and attachment['status'] == 'queued', (status,attachment)
|
||||
attachment_id = attachment['id']
|
||||
status, _ = call('GET',BASE+f'/api/v1/attachments/{attachment_id}/content',None,{'Authorization':'Bearer '+token})
|
||||
assert status == 409, status
|
||||
print('202 queued; content 409; worker stopped')
|
||||
time.sleep(opts.hold)
|
||||
before = alerts().get('MessengerQueueLagGrowing','not_observed')
|
||||
print('QueueLag alert:',before)
|
||||
finally:
|
||||
docker('start','worker')
|
||||
deadline = time.monotonic()+100
|
||||
while time.monotonic()<deadline:
|
||||
status, attachment = call('GET',BASE+f'/api/v1/attachments/{attachment_id}',None,{'Authorization':'Bearer '+token})
|
||||
if status == 200 and attachment['status'] == 'ready':
|
||||
ready = True
|
||||
break
|
||||
time.sleep(2)
|
||||
assert ready, 'Attachment did not become ready after restoring worker'
|
||||
names = sorted(v['name'] for v in attachment['variants'])
|
||||
assert names == ['crop','optimized','thumbnail'], names
|
||||
result = {'scenario':'stop worker -> 202 queued -> restart -> ready',
|
||||
'attachment_id':attachment_id,'status':'ready','variants':names,
|
||||
'queue_alert_before_worker_start':before,'passed':True}
|
||||
Path('evidence').mkdir(exist_ok=True)
|
||||
Path('evidence/worker-incident.json').write_text(json.dumps(result,indent=2),encoding='utf-8')
|
||||
print('PASS worker recovery:',json.dumps(result,ensure_ascii=False))
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
main()
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Operator actions for the local Compose stand; volumes are kept."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SERVICES = ("api1", "api2")
|
||||
BASE_URL = os.environ.get("BASE_URL", "http://localhost:8080").rstrip("/")
|
||||
|
||||
|
||||
def compose(*args, capture=False):
|
||||
result = subprocess.run(["docker", "compose", *args], cwd=ROOT, check=True,
|
||||
text=True, stdout=subprocess.PIPE if capture else None)
|
||||
return result.stdout.strip() if capture else None
|
||||
|
||||
|
||||
def state(service):
|
||||
cid = compose("ps", "--all", "--quiet", service, capture=True)
|
||||
if not cid:
|
||||
raise RuntimeError("No container for " + service)
|
||||
result = subprocess.check_output(
|
||||
["docker", "inspect", "--format",
|
||||
'{{json .Config.Hostname}} {{json .State.Status}}', cid], text=True)
|
||||
hostname, status = result.strip().split()
|
||||
return {"service": service, "container": cid[:12],
|
||||
"hostname": json.loads(hostname), "status": json.loads(status)}
|
||||
|
||||
|
||||
def wait_instances(count=2, timeout=40):
|
||||
deadline = time.monotonic() + timeout
|
||||
seen = set()
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
with urllib.request.urlopen(BASE_URL + "/health/ready", timeout=2) as r:
|
||||
instance = r.headers.get("X-Instance-Id")
|
||||
if instance:
|
||||
seen.add(instance)
|
||||
if len(seen) >= count:
|
||||
return seen
|
||||
except (OSError, urllib.error.URLError):
|
||||
pass
|
||||
time.sleep(0.2)
|
||||
raise RuntimeError("Not enough ready API instances through LB")
|
||||
|
||||
|
||||
def stop_one(service=None):
|
||||
target = os.environ.get("TARGET_INSTANCE_ID", "").split(":", 1)[0]
|
||||
if target:
|
||||
service = next((s for s in SERVICES if state(s)["hostname"] == target), None)
|
||||
if not service:
|
||||
raise RuntimeError("TARGET_INSTANCE_ID is not an API container")
|
||||
service = service or "api1"
|
||||
if service not in SERVICES:
|
||||
raise RuntimeError("Only API replicas may be stopped")
|
||||
compose("kill", "--signal", "SIGKILL", service)
|
||||
current = state(service)
|
||||
if current["status"] != "exited":
|
||||
raise RuntimeError("API did not stop")
|
||||
print(json.dumps(current))
|
||||
|
||||
|
||||
def restore():
|
||||
compose("up", "-d", "--no-deps", "--no-build", "--wait", "--wait-timeout", "40", *SERVICES)
|
||||
wait_instances()
|
||||
|
||||
|
||||
def restart():
|
||||
compose("down")
|
||||
compose("up", "-d", "--no-build", "--wait", "--wait-timeout", "60")
|
||||
wait_instances()
|
||||
|
||||
|
||||
def rolling_update():
|
||||
phases = []
|
||||
compose("build", "api1")
|
||||
# This migration only adds tables and is compatible with the old API.
|
||||
compose("run", "--rm", "--no-deps", "migrate")
|
||||
for service in SERVICES:
|
||||
before = state(service)
|
||||
started = time.monotonic()
|
||||
compose("up", "-d", "--no-deps", "--no-build", "--force-recreate",
|
||||
"--wait", "--wait-timeout", "40", service)
|
||||
after = state(service)
|
||||
if before["container"] == after["container"]:
|
||||
raise RuntimeError("Container was not replaced")
|
||||
seen = wait_instances()
|
||||
if not any(i.split(":", 1)[0] == after["hostname"] for i in seen):
|
||||
raise RuntimeError("LB has not discovered the replacement")
|
||||
phases.append({"service": service, "started": started, "finished": time.monotonic()})
|
||||
print(json.dumps({"replaced": service, "before": before, "after": after}))
|
||||
return phases
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("action", choices=["restart", "stop-one", "restore", "rolling-update"])
|
||||
parser.add_argument("--service", choices=SERVICES)
|
||||
args = parser.parse_args()
|
||||
if args.action == "stop-one":
|
||||
stop_one(args.service)
|
||||
else:
|
||||
{"restart": restart, "restore": restore, "rolling-update": rolling_update}[args.action]()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,4 @@
|
||||
@echo off
|
||||
cd /d "%~dp0.."
|
||||
python scripts\ops.py restart
|
||||
exit /b %errorlevel%
|
||||
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
exec python3 scripts/ops.py restart
|
||||
@@ -0,0 +1,4 @@
|
||||
@echo off
|
||||
cd /d "%~dp0.."
|
||||
python scripts\ops.py stop-one
|
||||
exit /b %errorlevel%
|
||||
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
exec python3 scripts/ops.py stop-one
|
||||
Reference in New Issue
Block a user