forked from mtusi2026/mtusi2026lab6
Реализовать лабораторную 6: OpenTelemetry, Grafana, SLO и burn-rate alerts
- api и worker отдают traces, metrics и logs по OTLP в Collector (memory_limiter, redaction, batch, ограниченная очередь и retry); хранилища: Prometheus (OTLP receiver), Loki, Tempo; Grafana с provisioning datasources и dashboard «Messenger lab6» - W3C trace context через outbox и RabbitMQ: producer/consumer spans связывают upload, публикации и попытки worker в одном trace - SLO доступности API (SLI на HAProxy) и времени до ready, multiwindow burn-rate alerts, ApiHighErrorRate, JobQueueLagGrowing, DbPoolSaturated, TelemetryExportFailing; unit-тесты promtool, runbooks - кампания трека 2 (k6, 6 отказов по расписанию), разбор и графики; проверки сигналов и истории telemetry, evidence и REPORT.md
This commit is contained in:
@@ -0,0 +1,139 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Отказы вокруг S3 и перезапуск всего стенда (уровни 3–4). Управляет Docker Compose этого каталога:
|
||||
1. S3 остановлен: upload/download → 503 быстро, метаданные и текст работают, readiness = 200;
|
||||
2. S3 «завис» (docker pause): ответ 503 по таймауту API раньше таймаута LB;
|
||||
3. после возврата S3 всё работает; неудачные загрузки не оставили строк (lab5: компенсация сначала удаляет строку),
|
||||
«воскресший» после pause объект staging убирает reconciler (orphan_staging);
|
||||
4. docker compose down (без -v) + up: метаданные, оригинал и прежний токен сохранены.
|
||||
Запуск: python3 student-tests/failures.py --base-url http://localhost:8080"""
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client, ROOT, arguments, check, run # noqa: E402
|
||||
|
||||
PNG = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
|
||||
|
||||
def compose(*args, capture=False):
|
||||
r = subprocess.run(['docker', 'compose', *args], cwd=ROOT, text=True, capture_output=True)
|
||||
check(r.returncode == 0, 'docker compose %s: %s' % (args[0], r.stderr.strip().splitlines()[-1:]))
|
||||
return r.stdout if capture else None
|
||||
|
||||
|
||||
def sql(query):
|
||||
return compose('exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-tAc', query, capture=True).strip()
|
||||
|
||||
|
||||
def reconcile(*flags):
|
||||
out = compose('run', '--rm', '--no-deps', '-T', 'reconciler', 'node', 'src/main.ts', 'reconcile', *flags, capture=True)
|
||||
return json.loads(out.strip().splitlines()[-1])
|
||||
|
||||
|
||||
def wait_ready(c, seconds=90):
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
if c.call('GET', '/health/ready', [200, 503])['status'] == 200:
|
||||
return
|
||||
except AssertionError:
|
||||
pass
|
||||
time.sleep(1)
|
||||
raise AssertionError('stand not ready')
|
||||
|
||||
|
||||
def recover(c, path, actor, seconds=60):
|
||||
"""Время до первого успешного скачивания после возврата S3."""
|
||||
start = time.monotonic()
|
||||
while c.call('GET', path, [200, 503], actor=actor)['status'] != 200:
|
||||
check(time.monotonic() - start < seconds, 'S3 path did not recover')
|
||||
time.sleep(0.5)
|
||||
return time.monotonic() - start
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('S3 outage, S3 hang and full stand restart')
|
||||
c = Client(args.base_url, args.ca_file, timeout=30)
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
up = '/api/v1/chats/' + chat['id'] + '/attachments?filename=outage.png'
|
||||
send = '/api/v1/chats/' + chat['id'] + '/messages'
|
||||
hdr = {'Content-Type': 'image/png'}
|
||||
att = c.call('POST', up, 202, actor=alice, raw=PNG, headers=hdr, schema='Attachment')['json']
|
||||
att = c.wait_ready(bob, att) # lab5: байты доступны после обработки worker
|
||||
content = '/api/v1/attachments/' + att['id'] + '/content'
|
||||
pending_before = int(sql("SELECT count(*) FROM attachments WHERE state = 'pending'"))
|
||||
log = []
|
||||
|
||||
def step(name, r):
|
||||
log.append('%-52s %d %5d ms' % (name, r['status'], r['elapsed'] * 1000))
|
||||
|
||||
# 1. S3 остановлен.
|
||||
compose('stop', 's3')
|
||||
try:
|
||||
step('S3 stopped: /health/ready (S3 не критичен)', c.call('GET', '/health/ready', 200))
|
||||
for i in range(3):
|
||||
step('S3 stopped: upload #%d' % (i + 1), c.call('POST', up, 503, actor=alice, raw=PNG, headers=hdr))
|
||||
step('S3 stopped: download', c.call('GET', content, 503, actor=bob))
|
||||
step('S3 stopped: metadata (только БД)', c.call('GET', '/api/v1/attachments/' + att['id'], 200, actor=bob, schema='Attachment'))
|
||||
step('S3 stopped: text message', c.call('POST', send, 201, actor=alice, body={'text': 'S3 недоступен'},
|
||||
headers={'Idempotency-Key': uuid.uuid4().hex}, schema='Message'))
|
||||
step('S3 stopped: message with ready attachment', c.call('POST', send, 201, actor=alice, body={'text': '', 'attachment_ids': [att['id']]},
|
||||
headers={'Idempotency-Key': uuid.uuid4().hex}, schema='Message'))
|
||||
finally:
|
||||
compose('start', 's3')
|
||||
# Компенсация сначала удаляет pending-строку (БД доступна), объектов при остановленном S3 не появилось.
|
||||
leftover = int(sql("SELECT count(*) FROM attachments WHERE state = 'pending'")) - pending_before
|
||||
log.append('pending-строк после 3 неудачных загрузок: %d' % leftover)
|
||||
check(leftover == 0, 'failed uploads left pending rows')
|
||||
|
||||
log.append('S3 started: download снова 200 через %.1f s' % recover(c, content, bob))
|
||||
|
||||
# 2. S3 завис: TCP-соединения не отвечают.
|
||||
c.call('GET', content, 200, actor=bob) # прогреть keep-alive соединения API → S3
|
||||
compose('pause', 's3')
|
||||
try:
|
||||
step('S3 paused: download (таймаут сокета S3 8 с)', c.call('GET', content, 503, actor=bob))
|
||||
step('S3 paused: upload', c.call('POST', up, 503, actor=alice, raw=PNG, headers=hdr))
|
||||
step('S3 paused: text message', c.call('POST', send, 201, actor=alice, body={'text': 'S3 завис'},
|
||||
headers={'Idempotency-Key': uuid.uuid4().hex}, schema='Message'))
|
||||
finally:
|
||||
compose('unpause', 's3')
|
||||
|
||||
# 3. S3 вернулся.
|
||||
log.append('S3 unpaused: download снова 200 через %.1f s' % recover(c, content, bob))
|
||||
r = c.call('POST', up, 202, actor=alice, raw=PNG, headers=hdr, schema='Attachment')
|
||||
step('S3 back: upload', r)
|
||||
c.wait_ready(bob, r['json']) # reconcile --grace=0 ниже не должен застать работу в процессе
|
||||
r = c.call('GET', content, 200, actor=bob)
|
||||
check(r['bytes'] == PNG, 'original changed')
|
||||
step('S3 back: download old attachment', r)
|
||||
# Возможен orphan_staging — PUT, который S3 буферизовал во время pause и выполнил после того, как API сдался
|
||||
# и компенсационный DELETE уже прошёл (объект «воскрес»). Других расхождений быть не должно.
|
||||
dry = reconcile('--grace=0')
|
||||
log.append('reconcile dry-run --grace=0: %s' % json.dumps(dry['findings'], ensure_ascii=False))
|
||||
check(set(dry['findings']) <= {'orphan_staging'}, 'unexpected findings')
|
||||
fixed = reconcile('--grace=0', '--apply')
|
||||
again = reconcile('--grace=0')
|
||||
log.append('reconcile --apply: applied=%d; повтор: %s' % (fixed['applied'], json.dumps(again['findings'])))
|
||||
check(not again['findings'], 'reconciler left inconsistencies')
|
||||
|
||||
# 4. Полный перезапуск стенда с сохранением volumes: down удаляет контейнеры и сети, не volumes.
|
||||
compose('down')
|
||||
compose('up', '-d', '--wait')
|
||||
wait_ready(c)
|
||||
r = c.call('GET', content, 200, actor=bob) # прежний токен
|
||||
check(r['bytes'] == PNG and hashlib.sha256(r['bytes']).hexdigest() == att['sha256'], 'original lost after down/up')
|
||||
step('down + up -d: download with old token', r)
|
||||
meta = c.call('GET', '/api/v1/attachments/' + att['id'], 200, actor=bob, schema='Attachment')['json']
|
||||
check(meta == att, 'metadata changed after restart')
|
||||
print('\n'.join(log))
|
||||
print('PASS: S3 outage/hang degrade only attachments (503), compensation + reconciler clean up, full restart keeps data')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Reference in New Issue
Block a user