forked from mtusi2026/mtusi2026lab6
LR6: monitoring and SLO
This commit is contained in:
@@ -0,0 +1,82 @@
|
||||
"""Check image edge cases through the public API using the worker's pinned Pillow."""
|
||||
import base64
|
||||
import json
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import zlib
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, check
|
||||
|
||||
|
||||
def pillow(code, data=""):
|
||||
result = subprocess.run(
|
||||
["docker", "compose", "exec", "-T", "worker", "python3", "-c", code],
|
||||
cwd=ROOT, input=data, capture_output=True, text=True, encoding="utf-8", timeout=30, check=True,
|
||||
)
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
def main():
|
||||
client = Client()
|
||||
alice, bob, _, chat = client.bootstrap()
|
||||
path = f"/api/v1/chats/{chat['id']}/attachments?filename=synthetic"
|
||||
fixtures = pillow("""
|
||||
import base64, io, json
|
||||
from PIL import Image
|
||||
jpeg = Image.new("RGB", (300, 100), "red")
|
||||
exif = Image.Exif()
|
||||
exif[274] = 6
|
||||
exif[271] = "Synthetic EXIF"
|
||||
png = Image.new("RGBA", (8, 4), (255, 0, 0, 0))
|
||||
def encode(image, kind, **options):
|
||||
buffer = io.BytesIO()
|
||||
image.save(buffer, kind, **options)
|
||||
return base64.b64encode(buffer.getvalue()).decode()
|
||||
print(json.dumps([encode(jpeg, "JPEG", exif=exif), encode(png, "PNG")]))
|
||||
""")
|
||||
downloads = {}
|
||||
for fixture, mime, dimensions in zip(fixtures, ("image/jpeg", "image/png"),
|
||||
([(85, 256), (128, 128), (100, 300)],
|
||||
[(8, 4), (128, 128), (8, 4)])):
|
||||
raw = base64.b64decode(fixture)
|
||||
att = client.call("POST", path, 202, actor=alice, raw=raw,
|
||||
headers={"Content-Type": mime}, schema="Attachment")["json"]
|
||||
ready = client.wait_ready(bob, att)
|
||||
content = f"/api/v1/attachments/{att['id']}/content"
|
||||
check(client.call("GET", content, actor=bob)["bytes"] == raw, "original changed")
|
||||
for (width, height), name in zip(dimensions, ("thumbnail", "crop", "optimized")):
|
||||
download = client.call("GET", content + "?variant=" + name, actor=bob)
|
||||
downloads[mime + "/" + name] = [base64.b64encode(download["bytes"]).decode(), width, height]
|
||||
print(f"{mime} attachment={att['id']} dimensions={dimensions}")
|
||||
probes = pillow("""
|
||||
import base64, io, json, sys
|
||||
from PIL import Image
|
||||
results = {}
|
||||
for key, (body, width, height) in json.load(sys.stdin).items():
|
||||
with Image.open(io.BytesIO(base64.b64decode(body))) as image:
|
||||
image.load()
|
||||
white = all(channel >= 250 for channel in image.convert("RGB").getpixel((0, 0)))
|
||||
results[key] = image.size == (width, height) and not image.getexif() and (white or not key.startswith("image/png"))
|
||||
print(json.dumps(results))
|
||||
""", json.dumps(downloads))
|
||||
check(all(probes.values()), "wrong actual dimensions, leaked EXIF or invalid alpha composition")
|
||||
|
||||
fixture = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
ihdr = struct.pack(">II", 10_000, 4_001) + fixture[24:29]
|
||||
too_many_pixels = fixture[:16] + ihdr + struct.pack(">I", zlib.crc32(b"IHDR" + ihdr)) + fixture[33:]
|
||||
for body, mime, status in (
|
||||
(too_many_pixels, "image/png", 413),
|
||||
(b"0" * (10 * 1024 * 1024 + 1), "image/png", 413),
|
||||
(fixture, "image/jpeg", 415),
|
||||
(fixture[:33], "image/png", 415),
|
||||
):
|
||||
client.call("POST", path, status, actor=alice, raw=body, headers={"Content-Type": mime})
|
||||
print("PASS EXIF, fit, crop, WebP, transparency, metadata removal, byte/pixel/format limits")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,355 @@
|
||||
"""Black-box checks on the dedicated, local Lab6 Compose project."""
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from urllib.error import HTTPError
|
||||
from urllib.parse import urlencode, urlsplit
|
||||
from urllib.request import urlopen
|
||||
from uuid import uuid4
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, check
|
||||
|
||||
|
||||
def local_port(name, default):
|
||||
return int(os.environ.get(name, default))
|
||||
|
||||
|
||||
BASE = os.environ.get('BASE_URL', f'http://127.0.0.1:{local_port("APP_PORT", 8080)}')
|
||||
PROM = f'http://127.0.0.1:{local_port("PROMETHEUS_PORT", 9090)}'
|
||||
LOKI = f'http://127.0.0.1:{local_port("LOKI_PORT", 3100)}'
|
||||
TEMPO = f'http://127.0.0.1:{local_port("TEMPO_PORT", 3200)}'
|
||||
GRAFANA = f'http://127.0.0.1:{local_port("GRAFANA_PORT", 3000)}'
|
||||
COMPOSE = ['docker', 'compose', '--project-directory', str(ROOT)]
|
||||
FIXTURE = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
|
||||
|
||||
def compose(*args):
|
||||
return subprocess.run([*COMPOSE, *args], cwd=ROOT, check=True, capture_output=True,
|
||||
text=True, encoding='utf-8', errors='replace', timeout=60).stdout.strip()
|
||||
|
||||
|
||||
def backend(base, path, **params):
|
||||
query = '?' + urlencode(params) if params else ''
|
||||
with urlopen(base + path + query, timeout=5) as response:
|
||||
return json.load(response)
|
||||
|
||||
|
||||
def tempo_ready():
|
||||
with urlopen(TEMPO + '/ready', timeout=5) as response:
|
||||
return response.status == 200
|
||||
|
||||
|
||||
def prometheus(expr, at=None):
|
||||
params = {'query': expr}
|
||||
if at is not None:
|
||||
params['time'] = at
|
||||
vector = backend(PROM, '/api/v1/query', **params)['data']['result']
|
||||
return [{**item['metric'], 'value': float(item['value'][1])} for item in vector]
|
||||
|
||||
|
||||
def wait_for(probe, message, timeout=45):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
result = probe()
|
||||
if result:
|
||||
return result
|
||||
except (HTTPError, OSError):
|
||||
pass
|
||||
time.sleep(1)
|
||||
raise AssertionError(message)
|
||||
|
||||
|
||||
def save(output, name, result):
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
(output / name).write_text(json.dumps(result, ensure_ascii=False, indent=2, allow_nan=False) + '\n',
|
||||
encoding='utf-8')
|
||||
|
||||
|
||||
def lab_only():
|
||||
check(urlsplit(BASE).hostname in {'localhost', '127.0.0.1', '::1'}, 'use the dedicated local lab')
|
||||
project = json.loads(compose('config', '--format', 'json'))['name']
|
||||
check(project.startswith('mtusi-lab6'), 'Compose project name must begin with mtusi-lab6')
|
||||
for service in ('worker', 'dispatcher', 'db', 'tempo', 'otel-collector'):
|
||||
check(bool(compose('ps', '-q', '--status', 'running', service)), f'{service} must be running')
|
||||
|
||||
|
||||
def actor_and_chat(client, label):
|
||||
actor = client.user(label)
|
||||
chat = client.call('POST', '/api/v1/chats', 201, actor=actor,
|
||||
body={'title': 'Синтетическая Lab6', 'member_ids': [actor['id']]}, schema='Chat')['json']
|
||||
return actor, chat
|
||||
|
||||
|
||||
def upload(client, actor, chat, filename='synthetic.png'):
|
||||
return client.call('POST', f'/api/v1/chats/{chat["id"]}/attachments?filename={filename}', 202,
|
||||
actor=actor, raw=FIXTURE, headers={'Content-Type': 'image/png'}, schema='Attachment')
|
||||
|
||||
|
||||
def loki_records(expression, lookback=300):
|
||||
now = time.time_ns()
|
||||
data = backend(LOKI, '/loki/api/v1/query_range', query=expression, start=now - lookback * 10**9,
|
||||
end=now, limit=100)['data']['result']
|
||||
result = []
|
||||
for stream in data:
|
||||
for timestamp, line, *extra in stream['values']:
|
||||
metadata = extra[0] if extra else {}
|
||||
result.append({**stream['stream'], **metadata, 'timestamp_ns': timestamp, 'body': line})
|
||||
return result
|
||||
|
||||
|
||||
def api_log(request_id, lookback=300):
|
||||
logs = loki_records(f'{{service_name="messenger-api"}} | request_id="{request_id}"', lookback)
|
||||
return logs[0] if logs else None
|
||||
|
||||
|
||||
def otlp_value(item):
|
||||
return next(iter(item.values()))
|
||||
|
||||
|
||||
def span_id(value):
|
||||
if not value or re.fullmatch('[0-9a-f]{16}', value):
|
||||
return value
|
||||
return base64.b64decode(value, validate=True).hex()
|
||||
|
||||
|
||||
def trace_by_id(trace_id):
|
||||
data = backend(TEMPO, '/api/traces/' + trace_id)
|
||||
spans = []
|
||||
for batch in data.get('batches', data.get('resourceSpans', [])):
|
||||
resource = {a['key']: otlp_value(a['value']) for a in batch['resource']['attributes']}
|
||||
for scope in batch.get('scopeSpans', batch.get('instrumentationLibrarySpans', [])):
|
||||
for span in scope['spans']:
|
||||
spans.append({
|
||||
'name': span['name'], 'service': resource['service.name'],
|
||||
'service_version': resource['service.version'],
|
||||
'environment': resource['deployment.environment.name'],
|
||||
'id': span_id(span['spanId']), 'parent': span_id(span.get('parentSpanId')),
|
||||
'kind': span['kind'], 'status': span.get('status', {}),
|
||||
'duration_ms': round((int(span['endTimeUnixNano']) - int(span['startTimeUnixNano'])) / 1e6, 3),
|
||||
'attributes': {a['key']: otlp_value(a['value']) for a in span.get('attributes', [])},
|
||||
})
|
||||
return spans
|
||||
|
||||
|
||||
def assert_privacy(records, secrets):
|
||||
serialized = json.dumps(records, ensure_ascii=False)
|
||||
check(not any(secret in serialized for secret in secrets), 'unexpected synthetic sensitive value in telemetry')
|
||||
forbidden = {'user_id', 'chat_id', 'message_id', 'attachment_id', 'request_id', 'filename',
|
||||
'url', 'url_full', 'url_path', 'text', 'trace_id', 'span_id'}
|
||||
sample = prometheus('count by (__name__) ({__name__=~"messenger_.+"})')
|
||||
check(bool(sample), 'no application metric series')
|
||||
series = backend(PROM, '/api/v1/series', **{'match[]': '{__name__=~"messenger_.+"}'})['data']
|
||||
check(not any(forbidden & entry.keys() for entry in series), 'forbidden metric label')
|
||||
return len(series)
|
||||
|
||||
|
||||
def correlation(output):
|
||||
client = Client(BASE)
|
||||
actor, chat = actor_and_chat(client, 'trace')
|
||||
canary = 'private-' + uuid4().hex
|
||||
message = client.message(actor, chat, canary)
|
||||
compose('stop', 'worker')
|
||||
extra_worker = 'mtusi-lab6-trace-' + uuid4().hex[:8]
|
||||
try:
|
||||
received = upload(client, actor, chat, canary + '.png')
|
||||
attachment = received['json']['id']
|
||||
compose('run', '-d', '--no-deps', '--name', extra_worker, '-e', 'LAB5_FAULT=temporary_once',
|
||||
'-e', 'LAB5_FAULT_ATTACHMENT=' + attachment, 'worker')
|
||||
wait_for(lambda: client.call('GET', '/api/v1/attachments/' + attachment, actor=actor,
|
||||
schema='Attachment')['json']['status'] == 'ready',
|
||||
'retry did not produce a ready result')
|
||||
request_id = received['headers']['X-Request-Id']
|
||||
log = wait_for(lambda: api_log(request_id), 'no upload log in Loki')
|
||||
trace_id = log['trace_id']
|
||||
check(bool(re.fullmatch('[0-9a-f]{32}', trace_id)), 'invalid Loki trace ID')
|
||||
logs = wait_for(lambda: enough_attempts(trace_id), 'no log for both worker attempts')
|
||||
spans = wait_for(lambda: enough_spans(trace_id), 'missing worker trace or S3 spans')
|
||||
server = next(span for span in spans if span['name'].startswith('POST /api/v1/chats/'))
|
||||
check(log['span_id'] == server['id'], 'API log has the wrong span')
|
||||
producers = {int(s['attributes']['job.attempt']): s for s in spans if s['name'].endswith(' publish')}
|
||||
consumers = {int(s['attributes']['job.attempt']): s for s in spans if s['name'].endswith(' process')}
|
||||
check(set(producers) == set(consumers) == {1, 2}, 'expected one failed attempt and one retry')
|
||||
for attempt in (1, 2):
|
||||
check(producers[attempt]['parent'] == server['id'], 'producer parent is not the upload')
|
||||
check(consumers[attempt]['parent'] == producers[attempt]['id'], 'consumer parent is not the producer')
|
||||
check(any(s['span_id'] == consumers[attempt]['id'] for s in logs), 'worker log span mismatch')
|
||||
check({log['outcome'] for log in logs} == {'queued', 'ready'}, 'missing retry/ready outcomes')
|
||||
check(any(s['name'] == 'postgresql query' and s['parent'] == consumers[2]['id'] for s in spans),
|
||||
'missing SQL span for the successful worker attempt')
|
||||
message_log = wait_for(lambda: api_log(message['headers']['X-Request-Id']), 'missing message log')
|
||||
message_spans = wait_for(lambda: trace_by_id(message_log['trace_id']), 'missing message trace')
|
||||
series = assert_privacy([log, logs, spans, message_log, message_spans],
|
||||
[canary, actor['registration']['password'], actor['token']])
|
||||
dashboard = backend(GRAFANA, '/api/dashboards/uid/messenger-lab6')['dashboard']
|
||||
sources = {ds['uid'] for ds in backend(GRAFANA, '/api/datasources')}
|
||||
check({'lab-prom', 'lab-loki', 'lab-tempo'} <= sources, 'missing provisioned datasource')
|
||||
save(output, 'correlation.json', {
|
||||
'trace_id': trace_id, 'request_id': request_id, 'logs': [log, *logs], 'spans': spans,
|
||||
'privacy': {'synthetic_canaries_absent': True, 'metric_series_checked': series},
|
||||
'grafana': {'dashboard_uid': dashboard['uid'], 'panels': len(dashboard['panels']),
|
||||
'datasources': sorted(sources)},
|
||||
})
|
||||
finally:
|
||||
subprocess.run(['docker', 'stop', '-t', '5', extra_worker], capture_output=True, timeout=20)
|
||||
subprocess.run(['docker', 'rm', extra_worker], capture_output=True, timeout=20)
|
||||
compose('start', 'worker')
|
||||
|
||||
|
||||
def enough_attempts(trace_id):
|
||||
logs = loki_records(f'{{service_name="messenger-worker"}} | trace_id="{trace_id}" | event="image.attempt"')
|
||||
return logs if len(logs) >= 2 else None
|
||||
|
||||
|
||||
def enough_spans(trace_id):
|
||||
spans = trace_by_id(trace_id)
|
||||
return spans if sum(span['name'] == 's3 put result' for span in spans) == 4 else None
|
||||
|
||||
|
||||
def queue_restart(output):
|
||||
def stream_entry(attachment):
|
||||
raw = compose('exec', '-T', 'broker', 'sh', '-c',
|
||||
'REDISCLI_AUTH="$(cat /run/secrets/broker_password)" '
|
||||
'exec valkey-cli --json XRANGE attachment-jobs - +')
|
||||
for identifier, fields in json.loads(raw):
|
||||
values = dict(zip(fields[::2], fields[1::2]))
|
||||
if json.loads(values.get('job', '{}')).get('attachment_id') == attachment:
|
||||
return identifier
|
||||
return None
|
||||
|
||||
def started_at():
|
||||
containers = compose('ps', '-q', 'api', 'broker').splitlines()
|
||||
check(len(containers) >= 3, 'expected two API replicas and a broker running')
|
||||
raw = subprocess.check_output(
|
||||
['docker', 'inspect', '--format', '{{.Id}} {{.State.StartedAt}}', *containers], text=True, timeout=15)
|
||||
return dict(line.split() for line in raw.splitlines())
|
||||
|
||||
def api_ready():
|
||||
with urlopen(BASE + '/health/ready', timeout=5) as response:
|
||||
return response.status == 200
|
||||
|
||||
client = Client(BASE)
|
||||
actor, chat = actor_and_chat(client, 'restart')
|
||||
compose('stop', 'worker')
|
||||
try:
|
||||
accepted = upload(client, actor, chat)['json']
|
||||
identifier = accepted['id']
|
||||
path = '/api/v1/attachments/' + identifier
|
||||
message = client.message(actor, chat, 'synthetic queued attachment', attachments=[identifier])['json']
|
||||
entry = wait_for(lambda: stream_entry(identifier), 'outbox did not publish the queued job')
|
||||
before = started_at()
|
||||
compose('restart', 'api', 'broker')
|
||||
wait_for(api_ready, 'API did not recover after restart')
|
||||
after = started_at()
|
||||
check(before.keys() == after.keys() and all(before[key] != after[key] for key in before),
|
||||
'restart did not affect every API replica and the broker')
|
||||
check(not compose('ps', '-q', '--status', 'running', 'worker'), 'worker processed the job during restart')
|
||||
check(wait_for(lambda: stream_entry(identifier), 'Stream lost the published job') == entry,
|
||||
'original Stream entry was lost')
|
||||
check(client.call('GET', path, actor=actor, schema='Attachment')['json']['status'] == 'queued',
|
||||
'attachment did not stay queued')
|
||||
history = client.call('GET', '/api/v1/chats/' + chat['id'] + '/messages', actor=actor)['bytes']
|
||||
check(message['id'] in history.decode('utf-8'), 'message with queued attachment disappeared')
|
||||
finally:
|
||||
compose('start', 'worker')
|
||||
ready = client.wait_ready(actor, accepted)
|
||||
original = client.call('GET', path + '/content', actor=actor)['bytes']
|
||||
thumbnail = client.call('GET', path + '/content?variant=thumbnail', actor=actor)['bytes']
|
||||
check(original == FIXTURE and thumbnail.startswith(b'\xff\xd8'), 'published file or thumbnail is invalid')
|
||||
save(output, 'queue-restart.json', {
|
||||
'api_and_broker_started_at_before': before, 'api_and_broker_started_at_after': after,
|
||||
'stream_entry_before_and_after': entry, 'worker_stopped_during_restart': True,
|
||||
'attachment_status_before': 'queued', 'attachment_status_after': ready['status'],
|
||||
'message_preserved': True, 'original_equal': True, 'thumbnail_jpeg': True,
|
||||
})
|
||||
|
||||
|
||||
def outage(output):
|
||||
loss = 'sum({__name__=~"otelcol_exporter_send_failed_spans(_total)?",exporter="otlphttp/tempo"})'
|
||||
queue = 'max(otelcol_exporter_queue_size{exporter="otlphttp/tempo"})'
|
||||
refused = 'sum({__name__=~"otelcol_exporter_enqueue_failed_spans(_total)?",exporter="otlphttp/tempo"})'
|
||||
queries = {'send_failed': loss, 'enqueue_failed': refused, 'queue': queue,
|
||||
'queue_capacity': 'max(otelcol_exporter_queue_capacity{exporter="otlphttp/tempo"})',
|
||||
'collector_rss_bytes': 'max({__name__=~"otelcol_process_memory_rss(_bytes)?"})'}
|
||||
|
||||
def sample():
|
||||
return {name: next(iter(prometheus(expr)), {}).get('value', 0) for name, expr in queries.items()}
|
||||
|
||||
client = Client(BASE)
|
||||
actor, chat = actor_and_chat(client, 'backend')
|
||||
baseline = sample()
|
||||
collector = compose('ps', '-q', 'otel-collector')
|
||||
inspect = ['docker', 'inspect', '--format',
|
||||
'{{.State.StartedAt}} {{.RestartCount}} {{.State.OOMKilled}} {{.HostConfig.Memory}}', collector]
|
||||
identity = subprocess.check_output(inspect, text=True).strip()
|
||||
timeline = []
|
||||
delivered = 0
|
||||
compose('stop', 'tempo')
|
||||
started = time.monotonic()
|
||||
try:
|
||||
snapshot = started
|
||||
while time.monotonic() - started < 35:
|
||||
client.message(actor, chat, 'synthetic during Tempo outage')
|
||||
delivered += 1
|
||||
if time.monotonic() >= snapshot:
|
||||
timeline.append({'elapsed_s': round(time.monotonic() - started, 3), **sample()})
|
||||
snapshot += 2
|
||||
time.sleep(.1)
|
||||
attachment = upload(client, actor, chat)['json']['id']
|
||||
wait_for(lambda: client.call('GET', '/api/v1/attachments/' + attachment, actor=actor,
|
||||
schema='Attachment')['json']['status'] == 'ready', 'worker blocked on Tempo')
|
||||
timeline.append({'elapsed_s': round(time.monotonic() - started, 3), **sample()})
|
||||
check(delivered >= 50, 'not enough successful writes during outage')
|
||||
check(max(s['send_failed'] for s in timeline) > baseline['send_failed'], 'no accounted span loss')
|
||||
check(subprocess.check_output(inspect, text=True).strip() == identity, 'collector restarted or OOMed')
|
||||
finally:
|
||||
recovery_started = time.monotonic()
|
||||
compose('start', 'tempo')
|
||||
wait_for(tempo_ready, 'Tempo did not become ready after restart')
|
||||
probes = []
|
||||
|
||||
def resumed_trace():
|
||||
resumed = client.message(actor, chat, 'synthetic after Tempo restart')
|
||||
probes.append(resumed['headers']['X-Request-Id'])
|
||||
for request_id in probes[-6:]:
|
||||
log = api_log(request_id)
|
||||
if log:
|
||||
try:
|
||||
if trace_by_id(log['trace_id']):
|
||||
return log['trace_id']
|
||||
except HTTPError as error:
|
||||
if error.code != 404:
|
||||
raise
|
||||
return None
|
||||
|
||||
recovered = wait_for(resumed_trace, 'traces did not recover')
|
||||
save(output, 'backend-outage.json', {
|
||||
'fault': 'tempo stopped', 'baseline': baseline, 'samples': timeline,
|
||||
'successful_message_writes': delivered, 'upload_ready_while_tempo_stopped': True,
|
||||
'collector_started_at_restarts_oom_limit_bytes': identity,
|
||||
'recovery_trace_id': recovered,
|
||||
'fault_duration_s': round(recovery_started - started, 3),
|
||||
'new_trace_after_restart_s': round(time.monotonic() - recovery_started, 3),
|
||||
})
|
||||
|
||||
|
||||
def main():
|
||||
args = argparse.ArgumentParser(description=__doc__)
|
||||
args.add_argument('scenario', choices=['correlation', 'outage', 'queue-restart'])
|
||||
args.add_argument('--output', type=Path, default=ROOT / 'evidence')
|
||||
options = args.parse_args()
|
||||
lab_only()
|
||||
{'correlation': correlation, 'outage': outage, 'queue-restart': queue_restart}[options.scenario](options.output)
|
||||
print(options.scenario + ' passed')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,254 @@
|
||||
"""Drive the local Lab6 workload and record the three phases of the SLO experiment."""
|
||||
import argparse
|
||||
from collections import Counter
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from contextlib import contextmanager
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from uuid import uuid4
|
||||
|
||||
from observability import (
|
||||
BASE, COMPOSE, ROOT, Client, actor_and_chat, api_log, check, compose, lab_only,
|
||||
prometheus, save, trace_by_id, upload, wait_for,
|
||||
)
|
||||
|
||||
ALERTS = ('APIFastBurn', 'APISlowBurn', 'ReadyFastBurn', 'ReadySlowBurn', 'QueueLagHigh')
|
||||
MESSAGE_RATE = 4
|
||||
UPLOAD_RATE = 1
|
||||
|
||||
|
||||
@contextmanager
|
||||
def locked_messages(seconds):
|
||||
# A lock on one business table keeps SELECT 1/readiness and other routes alive.
|
||||
# pg_sleep bounds the fault even if the client running the experiment dies.
|
||||
cmd = [*COMPOSE, 'exec', '-T', 'db', 'psql', '-X', '-q', '-v', 'ON_ERROR_STOP=1',
|
||||
'-U', 'messenger', '-d', 'messenger']
|
||||
with subprocess.Popen(cmd, cwd=ROOT, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT, text=True, encoding='utf-8') as session:
|
||||
assert session.stdin is not None and session.stdout is not None
|
||||
session.stdin.write("SET application_name = 'lab6_slo_lock';\n"
|
||||
"SET lock_timeout = '3s';\n"
|
||||
"BEGIN; LOCK TABLE messages IN ACCESS EXCLUSIVE MODE;\n"
|
||||
"\\echo LAB6_LOCKED\n"
|
||||
f"SELECT pg_sleep({seconds});\nCOMMIT;\n\\echo LAB6_RELEASED\n")
|
||||
session.stdin.close()
|
||||
check(session.stdout.readline().strip() == 'LAB6_LOCKED', 'database lock setup failed')
|
||||
started = time.time()
|
||||
try:
|
||||
yield started
|
||||
finally:
|
||||
session.wait(timeout=seconds + 10)
|
||||
check('LAB6_RELEASED' in session.stdout.read() and session.returncode == 0, 'database lock not released')
|
||||
|
||||
|
||||
class Workload:
|
||||
def __init__(self, actor, chat):
|
||||
self.actor = actor
|
||||
self.chat = chat
|
||||
self.client = threading.local()
|
||||
self.shutdown = threading.Event()
|
||||
self.rows = []
|
||||
self.dropped = []
|
||||
self.pool = ThreadPoolExecutor(max_workers=12)
|
||||
self.thread = threading.Thread(target=self.schedule)
|
||||
|
||||
def one(self, kind):
|
||||
if not hasattr(self.client, 'value'):
|
||||
self.client.value = Client(BASE, timeout=4)
|
||||
client = self.client.value
|
||||
started = time.time()
|
||||
try:
|
||||
if kind == 'message':
|
||||
response = client.call(
|
||||
'POST', f'/api/v1/chats/{self.chat["id"]}/messages', [201, 503], actor=self.actor,
|
||||
body={'text': 'Synthetic constant-rate SLO study'}, headers={'Idempotency-Key': uuid4().hex},
|
||||
schema='Message',
|
||||
)
|
||||
else:
|
||||
response = upload(client, self.actor, self.chat)
|
||||
self.rows.append({'t': started, 'kind': kind, 'status': response['status'],
|
||||
'request_id': response['headers']['X-Request-Id'],
|
||||
'latency_s': round(time.time() - started, 6),
|
||||
**({'attachment': response['json']['id']} if kind == 'upload' else {})})
|
||||
except (AssertionError, OSError):
|
||||
self.rows.append({'t': started, 'kind': kind, 'status': 'transport_or_contract_error',
|
||||
'latency_s': round(time.time() - started, 6)})
|
||||
|
||||
def schedule(self):
|
||||
tick = time.monotonic()
|
||||
i = 0
|
||||
inflight = set()
|
||||
while not self.shutdown.is_set():
|
||||
for kind in ('message', 'upload') if i % (MESSAGE_RATE // UPLOAD_RATE) == 0 else ('message',):
|
||||
inflight = {task for task in inflight if not task.done()}
|
||||
if len(inflight) >= 12:
|
||||
self.dropped.append({'t': time.time(), 'kind': kind})
|
||||
else:
|
||||
inflight.add(self.pool.submit(self.one, kind))
|
||||
i += 1
|
||||
tick += 1 / MESSAGE_RATE
|
||||
self.shutdown.wait(max(0, tick - time.monotonic()))
|
||||
|
||||
def __enter__(self):
|
||||
self.thread.start()
|
||||
return self
|
||||
|
||||
def __exit__(self, *_):
|
||||
self.shutdown.set()
|
||||
self.thread.join()
|
||||
self.pool.shutdown()
|
||||
|
||||
|
||||
def snapshot():
|
||||
active = prometheus('ALERTS{alertname=~"' + '|'.join(ALERTS) + '"}')
|
||||
return {
|
||||
't': time.time(),
|
||||
'alerts': {item['alertname']: item['alertstate'] for item in active},
|
||||
'depth': next(iter(prometheus('messenger_queue_depth')), {}).get('value'),
|
||||
'oldest_seconds': next(iter(prometheus('messenger_queue_oldest_age_seconds')), {}).get('value'),
|
||||
'worker_cpu_cores': next(iter(prometheus('sum(rate(messenger_container_cpu_seconds_total{service_name="messenger-worker"}[15s]))')),
|
||||
{}).get('value'),
|
||||
'api_cpu_cores': next(iter(prometheus('sum(rate(messenger_container_cpu_seconds_total{service_name="messenger-api"}[15s]))')),
|
||||
{}).get('value'),
|
||||
'worker_ram_bytes': next(iter(prometheus('sum(messenger_container_memory_bytes{service_name="messenger-worker"})')),
|
||||
{}).get('value'),
|
||||
'api_ram_bytes': next(iter(prometheus('sum(messenger_container_memory_bytes{service_name="messenger-api"})')),
|
||||
{}).get('value'),
|
||||
}
|
||||
|
||||
|
||||
def observe(samples, seconds):
|
||||
until = time.monotonic() + seconds
|
||||
while time.monotonic() < until:
|
||||
tick = time.monotonic()
|
||||
samples.append(snapshot())
|
||||
time.sleep(max(0, min(2 - (time.monotonic() - tick), until - time.monotonic())))
|
||||
|
||||
|
||||
def during(rows, start, stop):
|
||||
return [row for row in rows if start <= row['t'] < stop]
|
||||
|
||||
|
||||
def quantiles(values):
|
||||
ordered = sorted(values)
|
||||
return {f'p{p}_ms': round(1000 * ordered[math.ceil(len(ordered) * p / 100) - 1], 3)
|
||||
for p in (50, 95, 99)} if ordered else {}
|
||||
|
||||
|
||||
def summary(rows, start, stop):
|
||||
result = {}
|
||||
for kind in ('message', 'upload'):
|
||||
items = [r for r in during(rows, start, stop) if r['kind'] == kind]
|
||||
statuses = Counter(str(r['status']) for r in items)
|
||||
result[kind] = {'statuses': dict(statuses), 'successful_per_s':
|
||||
round((statuses['201'] + statuses['202']) / (stop - start), 3),
|
||||
**quantiles([row['latency_s'] for row in items])}
|
||||
return result
|
||||
|
||||
|
||||
def alert_timing(samples, start, stop, names):
|
||||
result = {}
|
||||
for name in names:
|
||||
firing = [s['t'] for s in samples if s['t'] >= start and s['alerts'].get(name) == 'firing']
|
||||
if not firing:
|
||||
result[name] = None
|
||||
continue
|
||||
resolved = next((s['t'] for s in samples if s['t'] > max(firing) and name not in s['alerts']), None)
|
||||
result[name] = {
|
||||
'firing_after_s': round(min(firing) - start, 3),
|
||||
'resolved_after_restoration_s': round(resolved - stop, 3) if resolved is not None else None,
|
||||
}
|
||||
return result
|
||||
|
||||
|
||||
def diagnose_db(rows):
|
||||
failing = [row for row in rows if row['status'] == 503]
|
||||
check(bool(failing), 'no application 503 from the database lock')
|
||||
for row in failing[:5]:
|
||||
log = wait_for(lambda: api_log(row['request_id']), 'missing incident log', timeout=8)
|
||||
trace = wait_for(lambda: trace_by_id(log['trace_id']), 'missing incident trace', timeout=8)
|
||||
sql = [span for span in trace if span['name'] == 'postgresql query' and span['duration_ms'] >= 900]
|
||||
if sql:
|
||||
return {'log': log, 'slow_postgresql_spans': sql, 'trace_id': log['trace_id']}
|
||||
raise AssertionError('incident trace lacks a slow PostgreSQL child span')
|
||||
|
||||
|
||||
def validate_result(result):
|
||||
check(not result['firing_during_baseline'] and not result['firing_after_short_spike'],
|
||||
'unexpected firing during baseline or brief fault')
|
||||
summaries = result['client_summary']
|
||||
check(summaries['short_db_spike']['message']['statuses'].get('503', 0) > 0, 'short spike did not generate errors')
|
||||
events = [*result['database_alerts'].values(), *result['worker_alerts'].values()]
|
||||
check(all(event and event['resolved_after_restoration_s'] is not None for event in events),
|
||||
'expected alert was not detected and resolved')
|
||||
recovery = result['worker_recovery']
|
||||
check(recovery['uploads_ready'] == recovery['uploads_accepted'] >= 30 and recovery['max_backlog'] >= 30,
|
||||
'backlog did not grow and drain as expected')
|
||||
check(result['prometheus_samples'][-1]['depth'] in (0, 1), 'unfinished recovery')
|
||||
# Count the sampled phases as a conservative lower bound for offered traffic.
|
||||
observed = sum(sum(item['statuses'].values()) for phase in summaries.values() for item in phase.values())
|
||||
check(result['dropped_by_generator'] <= observed * .01, 'load generator skipped more than 1% of requests')
|
||||
|
||||
|
||||
def experiment(output):
|
||||
lab_only()
|
||||
client = Client(BASE)
|
||||
actor, chat = actor_and_chat(client, 'slo')
|
||||
samples, phases = [], {}
|
||||
with Workload(actor, chat) as load:
|
||||
baseline = time.time()
|
||||
observe(samples, 82)
|
||||
phases['baseline'] = [baseline, time.time()]
|
||||
with locked_messages(2.5) as start:
|
||||
observe(samples, 2)
|
||||
phases['short_db_spike'] = [start, time.time()]
|
||||
observe(samples, 30)
|
||||
with locked_messages(65) as start:
|
||||
observe(samples, 63)
|
||||
phases['database_lock'] = [start, time.time()]
|
||||
observe(samples, 36)
|
||||
compose('stop', 'worker')
|
||||
start = time.time()
|
||||
try:
|
||||
observe(samples, 62)
|
||||
finally:
|
||||
compose('start', 'worker')
|
||||
phases['worker_stopped'] = [start, time.time()]
|
||||
observe(samples, 50)
|
||||
|
||||
at = [item['attachment'] for item in during(load.rows, *phases['worker_stopped']) if 'attachment' in item]
|
||||
ready = sum(client.call('GET', '/api/v1/attachments/' + identifier, actor=actor,
|
||||
schema='Attachment')['json']['status'] == 'ready' for identifier in at)
|
||||
db = alert_timing(samples, *phases['database_lock'], ALERTS[:2])
|
||||
worker = alert_timing(samples, *phases['worker_stopped'], ALERTS[2:])
|
||||
short_firing = sorted({name for s in during(samples, phases['short_db_spike'][0], phases['database_lock'][0])
|
||||
for name, state in s['alerts'].items() if state == 'firing'})
|
||||
baseline_firing = sorted({name for s in during(samples, *phases['baseline'])
|
||||
for name, state in s['alerts'].items() if state == 'firing'})
|
||||
diagnosis = diagnose_db(during(load.rows, *phases['database_lock']))
|
||||
worker_samples = during(samples, *phases['worker_stopped'])
|
||||
result = {
|
||||
'profile': {'messages_per_s': MESSAGE_RATE, 'uploads_per_s': UPLOAD_RATE, 'max_inflight': 12,
|
||||
'png_bytes': len((ROOT / 'tests/fixtures/sample.png').read_bytes()), 'monitor_interval_s': 2},
|
||||
'phases_utc_unix': phases, 'client_summary': {phase: summary(load.rows, *times) for phase, times in phases.items()},
|
||||
'dropped_by_generator': len(load.dropped),
|
||||
'firing_during_baseline': baseline_firing, 'firing_after_short_spike': short_firing,
|
||||
'database_alerts': db, 'worker_alerts': worker,
|
||||
'worker_recovery': {'uploads_accepted': len(at), 'uploads_ready': ready,
|
||||
'max_backlog': max(s['depth'] or 0 for s in worker_samples),
|
||||
'max_oldest_s': max(s['oldest_seconds'] or 0 for s in worker_samples)},
|
||||
'database_diagnosis': diagnosis, 'prometheus_samples': samples,
|
||||
}
|
||||
save(output, 'slo-experiment.json', result)
|
||||
validate_result(result)
|
||||
print(json.dumps({key: result[key] for key in ('database_alerts', 'worker_alerts', 'worker_recovery')}, indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--output', type=Path, default=ROOT / 'evidence')
|
||||
experiment(parser.parse_args().output)
|
||||
Reference in New Issue
Block a user