Реализовать лабораторную 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:
celis
2026-10-31 01:45:56 +03:00
parent 470d9d6f1e
commit 51b02a541d
88 changed files with 14033 additions and 16 deletions
+200
View File
@@ -0,0 +1,200 @@
#!/usr/bin/env python3
"""Негативные и граничные сценарии вложений (уровень 4) через LB: ни один из них не должен дать 500.
Lab5: принятый файл — 202 queued, байты и варианты доступны после ready (worker).
Изображения генерируются кодом (PNG — zlib/struct), JPEG — синтетический fixtures/sample.jpg (sips из sample.png).
Запуск: python3 student-tests/attachments.py --base-url http://localhost:8080"""
import hashlib
import http.client
import os
from pathlib import Path
import struct
import sys
import time
import urllib.parse
import uuid
import zlib
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import Client, ROOT, arguments, check, run # noqa: E402
MiB = 1024 * 1024
SAMPLE_PNG = (ROOT / 'tests/fixtures/sample.png').read_bytes()
SAMPLE_JPG = (Path(__file__).parent / 'fixtures/sample.jpg').read_bytes()
def chunk(kind, data):
return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data))
def png(width, height, raw, depth=8, color=2, level=1):
"""PNG из готовых распакованных строк raw (байт фильтра + пиксели)."""
ihdr = struct.pack('>IIBBBBB', width, height, depth, color, 0, 0, 0)
return b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', ihdr) + chunk(b'IDAT', zlib.compress(raw, level)) + chunk(b'IEND', b'')
def noise_png(side):
"""RGB-шум не сжимается: размер файла ≈ side² × 3 байт."""
row = 1 + side * 3
return png(side, side, b''.join(b'\0' + os.urandom(row - 1) for _ in range(side)))
def gray1(width, height):
"""1-битный серый PNG из нулей: 40 Мпикс занимают несколько килобайт файла."""
return png(width, height, bytes(height * (1 + (width + 7) // 8)), depth=1, color=0, level=9)
def jpeg_with_size(data, width, height):
"""Подменить размеры в SOF0 существующего JPEG."""
i = data.index(b'\xff\xc0')
return data[:i + 5] + struct.pack('>HH', height, width) + data[i + 9:]
def main():
args = arguments('Attachment negative suite')
c = Client(args.base_url, args.ca_file, timeout=30)
alice, bob, eve, chat = c.bootstrap()
other = c.call('POST', '/api/v1/chats', 201, actor=alice, body={'title': 'Другой чат', 'member_ids': [alice['id']]}, schema='Chat')['json']
results = []
def upload(data, expected, ctype='image/png', name='file.png', actor=alice, target=chat, label=None):
path = '/api/v1/chats/' + target['id'] + '/attachments?filename=' + urllib.parse.quote(name, safe='')
r = c.call('POST', path, expected, actor=actor, raw=data, headers={'Content-Type': ctype}, schema='Attachment' if expected == 202 else None)
results.append((label or name, r['status'], (r['json'] or {}).get('error', {}).get('code', ''), round(r['elapsed'] * 1000)))
if expected == 202:
att = r['json']
check(att['sha256'] == hashlib.sha256(data).hexdigest() and att['size_bytes'] == len(data), label + ': checksum/size')
check(att['content_type'] == ctype and att['filename'] == name, label + ': metadata')
check(att['status'] == 'queued' and att['variants'] == [] and att['error_code'] is None, label + ': 202 snapshot')
return att
return r['json']
def download(att, actor=bob, expect=None):
att = c.wait_ready(actor, att, 120)
r = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=actor)
check(r['bytes'] == expect and hashlib.sha256(r['bytes']).hexdigest() == att['sha256'], 'download differs')
check(r['headers'].get_content_type() == att['content_type'], 'download content type')
check(r['headers'].get('X-Content-Type-Options') == 'nosniff', 'missing nosniff')
check(not r['headers'].get('Location'), 'download must not redirect')
# Принимаются реальные PNG/JPEG, граница по размеру и по пикселям.
jpg = upload(SAMPLE_JPG, 202, 'image/jpeg', 'фото 📷 2026.jpg', label='real JPEG + unicode filename')
download(jpg, expect=SAMPLE_JPG)
big = noise_png(1860)
check(9 * MiB < len(big) <= 10 * MiB, 'big fixture size %d' % len(big))
big_att = upload(big, 202, label='PNG %.2f MiB (noise 1860x1860)' % (len(big) / MiB))
download(big_att, expect=big)
huge = upload(gray1(6400, 6250), 202, label='PNG ровно 40 000 000 px')
huge = c.wait_ready(bob, huge, 120) # worker обрабатывает предельный по пикселям файл в своих лимитах
dims = {v['name']: (v['width'], v['height']) for v in huge['variants']}
check(dims == {'thumbnail': (256, 250), 'crop': (128, 128), 'optimized': (1280, 1250)}, 'variants of 6400x6250: %s' % dims)
# Лимиты: до чтения тела (Content-Length) и по заголовку изображения до распаковки.
upload(noise_png(1900), 413, label='PNG 10.33 MiB > 10 MiB')
upload(os.urandom(10 * MiB + 1), 413, label='10 MiB + 1 байт')
upload(gray1(6400, 6251), 413, label='PNG 40 006 400 px')
bomb = gray1(30000, 30000)
upload(bomb, 413, label='pixel-bomb 30000x30000, файл %d КБ' % (len(bomb) // 1024))
upload(jpeg_with_size(SAMPLE_JPG, 10000, 10000), 413, 'image/jpeg', 'bomb.jpg', label='JPEG SOF 10000x10000')
# IHDR обещает 100x100, а IDAT распаковывается в 64 МБ нулей: распаковка останавливается на лишних данных.
upload(png(100, 100, bytes(64 * MiB), level=9), 415, label='zip-bomb в IDAT (64 МБ при 100x100)')
# Повреждённые файлы и подмена типа.
bad_crc = bytearray(SAMPLE_PNG)
bad_crc[1000] ^= 0xFF
upload(bytes(bad_crc), 415, label='PNG: байт IDAT испорчен (CRC)')
upload(png(320, 200, os.urandom(1000)), 415, label='PNG: корректные CRC, мусор в zlib')
upload(png(320, 200, bytes(100)), 415, label='PNG: данных меньше, чем пикселей')
upload(SAMPLE_PNG[:-200], 415, label='PNG обрезан')
upload(SAMPLE_PNG + b'<html>', 415, label='PNG + данные после IEND')
upload(SAMPLE_JPG[:-500], 415, 'image/jpeg', 'cut.jpg', label='JPEG обрезан (нет EOI)')
upload(SAMPLE_PNG, 415, 'image/jpeg', 'spoof.jpg', label='PNG под видом image/jpeg')
upload(SAMPLE_JPG, 415, 'image/png', 'spoof.png', label='JPEG под видом image/png')
upload(b'GIF89a' + os.urandom(100), 415, label='GIF под видом image/png')
upload(b'<svg xmlns="http://www.w3.org/2000/svg"/>', 415, label='SVG под видом image/png')
upload(SAMPLE_PNG, 415, 'image/gif', 'x.gif', label='Content-Type image/gif')
upload(SAMPLE_PNG, 415, 'application/octet-stream', 'x.png', label='Content-Type octet-stream')
upload(b'', 415, label='пустое тело')
# Опасные и некорректные filename: 400 до чтения тела.
for name in ['../etc/passwd', 'a/b.png', 'a\\b.png', 'nul\x00.png', 'tab\t.png', 'line\n.png', 'c1\x85.png', '', ' ', 'x' * 256]:
upload(SAMPLE_PNG, 400, name=name, label='filename %r' % name[:20])
r = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments', 400, actor=alice, raw=SAMPLE_PNG, headers={'Content-Type': 'image/png'})
results.append(('без filename', r['status'], r['json']['error']['code'], round(r['elapsed'] * 1000)))
results.append(('chunked без Content-Length',) + chunked_upload(c, alice, chat))
# Доступ: без сессии, посторонний, чужое вложение.
upload(SAMPLE_PNG, 401, actor={'id': '', 'token': 'bad'}, label='без действительной сессии')
upload(SAMPLE_PNG, 404, actor=eve, label='посторонний грузит в чужой чат')
upload(SAMPLE_PNG, 404, target={'id': str(uuid.uuid4())}, label='несуществующий чат')
upload(SAMPLE_PNG, 400, target={'id': 'not-a-uuid'}, label='chat_id не UUID')
own = upload(SAMPLE_PNG, 202, label='обычный PNG')
foreign = upload(SAMPLE_PNG, 202, target=other, label='PNG в другом чате')
for suffix in ('', '/content'):
c.call('GET', '/api/v1/attachments/' + own['id'] + suffix, 404, actor=eve)
c.call('GET', '/api/v1/attachments/' + foreign['id'] + suffix, 404, actor=bob)
c.call('GET', '/api/v1/attachments/' + str(uuid.uuid4()) + suffix, 404, actor=bob)
c.call('GET', '/api/v1/attachments/xyz' + suffix, 400, actor=bob)
c.call('GET', '/api/v1/attachments/' + own['id'] + suffix, 401)
content = '/api/v1/attachments/' + own['id'] + '/content'
c.wait_ready(bob, own)
check(c.call('GET', content + '?variant=thumbnail', actor=bob)['headers'].get_content_type() == 'image/jpeg', 'thumbnail type')
check(c.call('GET', content + '?variant=optimized', actor=bob)['headers'].get_content_type() == 'image/webp', 'optimized type')
c.call('GET', content + '?variant=bogus', 400, actor=bob)
check(c.call('GET', content + '?variant=original', actor=bob)['bytes'] == SAMPLE_PNG, 'variant=original')
# Привязка к сообщению: только вложения этого чата, 0–10 уникальных UUID.
send = '/api/v1/chats/' + chat['id'] + '/messages'
def post(body, expected, key=None):
return c.call('POST', send, expected, actor=alice, body=body, headers={'Idempotency-Key': key or uuid.uuid4().hex},
schema='Message' if expected == 201 else None)['json']
post({'text': 'чужое', 'attachment_ids': [foreign['id']]}, 404)
post({'text': 'смесь', 'attachment_ids': [own['id'], foreign['id']]}, 404)
post({'text': 'нет такого', 'attachment_ids': [str(uuid.uuid4())]}, 404)
post({'text': 'дубль', 'attachment_ids': [own['id'], own['id'].upper()]}, 400)
post({'text': 'много', 'attachment_ids': [str(uuid.uuid4()) for _ in range(11)]}, 400)
post({'text': 'не uuid', 'attachment_ids': ['x']}, 400)
post({'text': 'не массив', 'attachment_ids': own['id']}, 400)
post({'text': ' '}, 400)
post({'text': '', 'attachment_ids': []}, 400)
c.call('POST', '/api/v1/chats/' + other['id'] + '/messages', 404, actor=bob, body={'text': 'x', 'attachment_ids': [foreign['id']]},
headers={'Idempotency-Key': uuid.uuid4().hex})
key = uuid.uuid4().hex
m = post({'text': '', 'attachment_ids': [own['id'], jpg['id']]}, 201, key)
check(m['attachment_ids'] == [own['id'], jpg['id']] and m['text'] == '', 'attachment order/text')
check(post({'attachment_ids': [own['id'], jpg['id']], 'text': ''}, 201, key) == m, 'replay with attachments differs')
post({'text': '', 'attachment_ids': [jpg['id'], own['id']]}, 409, key)
post({'text': '', 'attachment_ids': [own['id']]}, 409, key)
key = uuid.uuid4().hex
t = post({'text': 'без вложений'}, 201, key)
check(post({'text': 'без вложений', 'attachment_ids': []}, 201, key) == t and t['attachment_ids'] == [], 'missing attachment_ids != []')
history = c.call('GET', send + '?limit=100', actor=bob, schema='MessagePage')['json']['items']
check([x for x in history if x['id'] == m['id']] == [m], 'history lost attachment_ids')
width = max(len(r[0]) for r in results)
for label, status, code, ms in results:
print('%-*s %d %-24s %5d ms' % (width, label, status, code, ms))
check(all(status < 500 for _, status, _, _ in results), 'server error in negative suite')
print('PASS: %d upload cases, ACL and message linking; no 5xx' % len(results))
def chunked_upload(c, actor, chat):
"""Тело без Content-Length (Transfer-Encoding: chunked): потоковая запись в S3 требует длину — 400."""
url = urllib.parse.urlsplit(c.base)
conn = http.client.HTTPConnection(url.hostname, url.port, timeout=10)
conn.putrequest('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=c.png')
conn.putheader('Authorization', 'Bearer ' + actor['token'])
conn.putheader('Content-Type', 'image/png')
conn.putheader('Transfer-Encoding', 'chunked')
conn.endheaders()
start = time.monotonic()
conn.send(b'%x\r\n%s\r\n0\r\n\r\n' % (len(SAMPLE_PNG), SAMPLE_PNG))
r = conn.getresponse()
body = r.read()
check(r.status == 400 and b'invalid_request' in body, 'chunked upload: %d' % r.status)
return r.status, 'invalid_request', round((time.monotonic() - start) * 1000)
if __name__ == '__main__':
run(main)
+139
View File
@@ -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)
Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

+59
View File
@@ -0,0 +1,59 @@
#!/usr/bin/env python3
"""Один Idempotency-Key, N параллельных запросов через LB (то есть через разные реплики).
Половина запросов с телом A, половина с телом B: должно появиться ровно одно сообщение, каждый 201 возвращает его,
другое тело получает 409. Запуск: python3 student-tests/idempotency_race.py --base-url http://localhost:8080"""
from concurrent.futures import ThreadPoolExecutor
import json
from pathlib import Path
import sys
import threading
import uuid
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import Client, arguments, check, run # noqa: E402
def main():
args = arguments('Parallel same-key POST race', lambda p: p.add_argument('--parallel', type=int, default=32))
c = Client(args.base_url, args.ca_file)
alice, bob, _, chat = c.bootstrap()
path = '/api/v1/chats/' + chat['id'] + '/messages'
key = 'race-' + uuid.uuid4().hex
texts = ['гонка A ' + key, 'гонка B ' + key]
barrier = threading.Barrier(args.parallel)
def send(i):
local = Client(args.base_url, args.ca_file)
barrier.wait()
r = local.call('POST', path, [201, 409], actor=alice, body={'text': texts[i % 2]}, headers={'Idempotency-Key': key}, schema='Message')
return r['status'], r['json'], r['headers']['X-Instance-Id']
with ThreadPoolExecutor(args.parallel) as pool:
results = list(pool.map(send, range(args.parallel)))
created = [body for status, body, _ in results if status == 201]
check(created, 'no request succeeded')
winner = created[0]
check(all(body == winner for body in created), 'replicas returned different messages for one key')
check(all(body['error']['code'] == 'conflict' for status, body, _ in results if status == 409), '409 without conflict code')
statuses = {texts[i % 2]: set() for i in range(2)}
for i, (status, _, _) in enumerate(results):
statuses[texts[i % 2]].add(status)
check(statuses[winner['text']] == {201}, 'winning body must always get 201')
check(statuses[next(t for t in texts if t != winner['text'])] == {409}, 'other body must always get 409')
instances = {inst for _, _, inst in results}
check(len(instances) >= 2, 'race did not reach two replicas')
history = c.call('GET', path + '?limit=100', actor=bob, schema='MessagePage')['json']['items']
stored = [m for m in history if key in m['text']]
check(stored == [winner], 'expected exactly one stored message equal to the replayed one')
# Тот же ключ у другого пользователя независим.
other = c.message(bob, chat, texts[0], key=key)['json']
check(other['id'] != winner['id'] and other['sender_id'] == bob['id'], 'key scope leaked across users')
print(json.dumps({'parallel': args.parallel, 'replicas_hit': len(instances), 'created_201': len(created),
'conflict_409': args.parallel - len(created), 'stored_messages': len(stored)}, ensure_ascii=False))
print('PASS: concurrent same-key POSTs through different replicas created exactly one message')
if __name__ == '__main__':
run(main)
+354
View File
@@ -0,0 +1,354 @@
#!/usr/bin/env python3
"""Уровень 4 и трек 2: автоматический fault-injection pipeline вложений и проверка инвариантов.
На время теста api и worker пересоздаются с FAILPOINTS=1 и JOB_TIMEOUT_SECONDS=10 (аренда 25 с), в конце —
снова с конфигурацией из .env. Отказы настоящие: аварийный выход процесса в точке (src/failpoints.ts), пауза процесса,
дубли и перестановка сообщений через outbox, остановка S3 и брокера, устаревшая job после новой версии pipeline.
Инварианты (проверяются в конце по всем вложениям тестового чата):
I1 нет потерянной работы: каждое вложение, для которого записано задание, в конечном состоянии ready/failed;
I2 один результат: у пары (вложение, версия) ровно 3 варианта, лишние объекты попыток убирает reconciler;
I3 новый результат не перезаписан старым: версия только растёт, варианты v2 не меняются после старых job;
I4 повтор даёт тот же результат: sha256 вариантов после сбоев = sha256 контрольной обработки тех же байтов;
I5 API согласован: каждый вариант и оригинал скачиваются, размер и sha256 совпадают с метаданными;
I6 все job в конечном состоянии (done/failed/superseded), reconciler после очистки ничего не находит.
Запуск: python3 student-tests/pipeline_faults.py --base-url http://localhost:8080"""
import hashlib
import http.client
import json
import os
import struct
import subprocess
import time
import urllib.parse
import uuid
import zlib
from failures import PNG, ROOT, sql, wait_ready
from client import Client, arguments, check, run
TEST_ENV = {'FAILPOINTS': '1', 'JOB_TIMEOUT_SECONDS': '10'} # аренда = таймаут + 15 с
LEASE = 25
def compose(*args, env=None):
r = subprocess.run(['docker', 'compose', *args], cwd=ROOT, text=True, capture_output=True, env={**os.environ, **(env or {})})
check(r.returncode == 0, 'docker compose %s: %s' % (args[0], r.stderr.strip().splitlines()[-1:]))
return r.stdout
def jobs(*args):
out = compose('exec', '-T', 'api', 'node', 'src/main.ts', 'jobs', *args)
return [json.loads(line) for line in out.splitlines() if line.startswith('{')]
def reconcile(*flags):
"""Находки reconciler (по одной JSON-строке) и итоговая сводка."""
out = compose('run', '--rm', '--no-deps', '-T', 'reconciler', 'node', 'src/main.ts', 'reconcile', *flags)
lines = [json.loads(line) for line in out.splitlines() if line.startswith('{')]
return [x for x in lines if 'finding' in x], lines[-1]
def rows(query):
out = sql(query)
return [line.split('|') for line in out.splitlines()] if out else []
def wait_for(what, fn, seconds):
deadline = time.monotonic() + seconds
while True:
value = fn()
if value:
return value
check(time.monotonic() < deadline, 'timeout: ' + what)
time.sleep(1)
def healthy(service):
"""Все реплики сервиса healthy (после crash Docker перезапускает контейнер)."""
out = compose('ps', '-a', service, '--format', '{{.State}} {{.Health}}').split('\n')
return all(line == 'running healthy' for line in out if line)
def bad_filter_png():
"""Структура PNG верна (CRC, объём данных), но байт фильтра строк 9 не существует: API принимает, libvips — нет."""
def chunk(kind, data):
return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data))
raw = b''.join(b'\x09' + bytes(64 * 3) for _ in range(64))
return (b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', 64, 64, 8, 2, 0, 0, 0))
+ chunk(b'IDAT', zlib.compress(raw)) + chunk(b'IEND', b''))
def main():
args = arguments('Pipeline fault injection with invariant checks')
c = Client(args.base_url, args.ca_file, timeout=30)
since = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())
compose('up', '-d', '--no-deps', 'api', 'worker', env=TEST_ENV)
wait_for('api healthy with FAILPOINTS=1', lambda: healthy('api'), 90)
for service in ('api', 'worker'):
ids = compose('ps', '-q', service).split()
check(len(ids) == 2 and all(subprocess.run(['docker', 'exec', i, 'printenv', 'FAILPOINTS'], capture_output=True, text=True)
.stdout.strip() == '1' for i in ids), '%s replicas without FAILPOINTS=1' % service)
wait_ready(c)
alice, bob, _, chat = c.bootstrap()
report = []
def record(name, text):
report.append('%-44s %s' % (name, text))
print(report[-1], flush=True)
def upload(name, data=PNG):
path = '/api/v1/chats/%s/attachments?filename=%s' % (chat['id'], urllib.parse.quote(name))
return c.call('POST', path, 202, actor=alice, raw=data, headers={'Content-Type': 'image/png'}, schema='Attachment')['json']['id']
def raw_upload(name):
"""Upload, при котором API может погибнуть посреди запроса: статус без проверок клиента (0 — обрыв)."""
url = urllib.parse.urlsplit(c.base)
conn = http.client.HTTPConnection(url.hostname, url.port, timeout=30)
try:
conn.request('POST', '/api/v1/chats/%s/attachments?filename=%s' % (chat['id'], name), body=PNG,
headers={'Authorization': 'Bearer ' + alice['token'], 'Content-Type': 'image/png'})
return conn.getresponse().status
except OSError:
return 0
finally:
conn.close()
def find(name):
return sql("SELECT id FROM attachments WHERE chat_id = '%s' AND filename = '%s'" % (chat['id'], name))
def state(aid):
return rows("SELECT state, coalesce(pipeline_version, 0), coalesce(error_code, '') FROM attachments WHERE id = '%s'" % aid)[0]
def job(aid, version=1):
r = rows("SELECT job_id, state, attempts, coalesce(error_code, '') FROM jobs WHERE attachment_id = '%s' AND pipeline_version = %d"
% (aid, version))
return r[0] if r else None
def variants(aid, version):
return {name: sha for name, sha in rows("SELECT name, sha256 FROM attachment_variants WHERE attachment_id = '%s' "
"AND pipeline_version = %d" % (aid, version))}
def settle(aid, seconds=90, version=1):
"""Дождаться конечного состояния вложения и его job нужной версии."""
return wait_for('attachment %s final' % aid, lambda: state(aid)[0] in ('ready', 'failed')
and (job(aid, version) or ['', ''])[1] in ('done', 'failed', 'superseded') and state(aid), seconds)
def deliveries(job_id):
log = compose('logs', '--no-log-prefix', '--since', since, 'worker')
return [line for line in log.splitlines() if job_id in line]
try:
# S0. Контроль: эталонные sha256 вариантов v1 для тех же байтов.
control = upload('control.png')
settle(control)
ref = variants(control, 1)
check(len(ref) == 3, 'control variants')
record('S0 контроль', 'ready v1, варианты %s' % ', '.join(sorted(ref)))
# S1. API падает после записи staging, до транзакции задания: 202 не было — работы не обещано.
status = raw_upload('failpoint-api_after_staging.png')
s1 = find('failpoint-api_after_staging.png')
check(status != 202 and state(s1)[0] == 'pending' and job(s1) is None, 'S1: %s %s' % (status, state(s1)))
wait_for('api restarted', lambda: healthy('api'), 90)
record('S1 API: crash после staging', 'клиент получил %d; строка pending, заданий нет → stale_pending для reconciler' % status)
# S2. API падает после COMMIT задания+outbox, до publish и ответа: публикует relay другой реплики.
status = raw_upload('failpoint-api_after_commit.png')
s2 = find('failpoint-api_after_commit.png')
st = settle(s2)
j = job(s2)
check(status != 202 and st[0] == 'ready' and j[1:3] == ['done', '1'], 'S2: %s %s %s' % (status, st, j))
wait_for('api restarted', lambda: healthy('api'), 90)
record('S2 API: crash после COMMIT, до publish', 'клиент %d; задание из outbox опубликовано → ready, попыток 1' % status)
# S3. Relay падает после publisher confirm, до отметки published_at: строку публикует снова — дубль.
status = raw_upload('failpoint-relay_after_publish.png')
s3 = find('failpoint-relay_after_publish.png')
st = settle(s3)
j = job(s3)
seen = wait_for('duplicate delivered', lambda: len(deliveries(j[0])) >= 2 and deliveries(j[0]), 20)
check(st[0] == 'ready' and j[1:3] == ['done', '1'] and len(seen) >= 2 and len(variants(s3, 1)) == 3, 'S3: %s %s %s' % (st, j, seen))
wait_for('api restarted', lambda: healthy('api'), 90)
record('S3 relay: crash после confirm', 'клиент %d; доставок worker: %d (дубль), обработка 1, вариантов 3' % (status, len(seen)))
# S4. Тройная доставка одной попытки одновременно двум worker.
compose('stop', 'worker')
s4 = upload('duplicate.png')
j4 = job(s4)[0]
sql("INSERT INTO outbox (job_id, attempt) VALUES ('%s', 1), ('%s', 1)" % (j4, j4))
wait_for('duplicates published', lambda: sql("SELECT count(*) FROM outbox WHERE job_id = '%s' AND published_at IS NOT NULL" % j4) == '3', 20)
compose('start', 'worker')
st = settle(s4)
seen = wait_for('all copies delivered', lambda: len(deliveries(j4)) >= 3 and deliveries(j4), 20)
noop = [line for line in seen if 'no-op' in line]
check(st[0] == 'ready' and job(s4)[2] == '1' and len(seen) == 3 and len(noop) == 2 and variants(s4, 1) == ref, 'S4: %s' % seen)
record('S4 дубль: 3 копии попытки 1', '3 доставки → 1 обработка, 2 no-op; попыток 1, варианты = контрольным')
# S5. Reorder в новой версии: сообщение попытки 2 опубликовано раньше попытки 1 (job v2 для ready v1).
j5 = str(uuid.uuid4())
sql("INSERT INTO jobs (job_id, attachment_id, pipeline_version) VALUES ('%s', '%s', 2); "
"INSERT INTO outbox (job_id, attempt) VALUES ('%s', 2), ('%s', 1)" % (j5, s4, j5, j5))
st = settle(s4, version=2)
v2 = variants(s4, 2)
seen = wait_for('attempt 2 no-op', lambda: any('попытка 2: no-op' in line for line in deliveries(j5)) and deliveries(j5), 20)
check(st[:2] == ['ready', '2'] and job(s4, 2)[1:3] == ['done', '1'] and len(v2) == 3 and v2['thumbnail'] != ref['thumbnail']
and any('попытка 2: no-op' in line for line in seen), 'S5: %s %s' % (st, seen))
record('S5 reorder: попытка 2 раньше 1 (job v2)', 'попытка 2 → no-op, попытка 1 → done; версия 1 → 2, вариантов v2: 3')
# S6. Устаревшая job v1 после публикации v2: поздний дубль старого сообщения и повторно поставленная v1.
j1 = job(s4)[0]
before = len(deliveries(j1))
sql("INSERT INTO outbox (job_id, attempt) VALUES ('%s', 1)" % j1)
wait_for('late duplicate handled', lambda: len(deliveries(j1)) > before, 20)
sql("UPDATE jobs SET state = 'queued' WHERE job_id = '%s'; "
"INSERT INTO outbox (job_id, attempt) SELECT job_id, attempts + 1 FROM jobs WHERE job_id = '%s'" % (j1, j1))
wait_for('stale v1 superseded', lambda: job(s4)[1] == 'superseded', 30)
check(state(s4)[:2] == ['ready', '2'] and variants(s4, 2) == v2, 'S6: v2 changed')
record('S6 устаревшая v1 после v2 (захват)', 'дубль старого сообщения → no-op; повторно поставленная v1 → superseded; v2 не тронута')
# S7. v1 фиксируется после v2: v1 «зависла» 10 с после записи объектов, тем временем v2 опубликована.
name = 'failpoint-worker_after_side_effect-10s.png'
s7 = upload(name)
wait_for('v1 stalled after side effects', lambda: sql("SELECT count(*) FROM failpoint_hits WHERE attachment_id = '%s'" % s7) == '1', 30)
j7 = str(uuid.uuid4())
sql("INSERT INTO jobs (job_id, attachment_id, pipeline_version) VALUES ('%s', '%s', 2); "
"INSERT INTO outbox (job_id, attempt) VALUES ('%s', 1)" % (j7, s7, j7))
wait_for('v2 done', lambda: (job(s7, 2) or ['', ''])[1] == 'done', 30)
v2_7 = variants(s7, 2)
wait_for('v1 superseded at commit', lambda: job(s7)[1] == 'superseded', 30)
check(state(s7)[:2] == ['ready', '2'] and variants(s7, 1) == {} and variants(s7, 2) == v2_7, 'S7: %s' % state(s7))
record('S7 v1 фиксируется после v2 (фиксация)', 'v2 ready; v1 при фиксации → superseded, вариантов v1 в БД 0, объекты удалены')
# S8–S10. Worker crash до side effect, после side effect, после COMMIT (до ack).
crashed = {}
for label, point, attempts in (('S8 worker: crash после захвата', 'worker_after_claim', '2'),
('S9 worker: crash после записи S3', 'worker_after_side_effect', '2'),
('S10 worker: crash после COMMIT до ack', 'worker_after_commit', '1')):
started = time.monotonic()
aid = crashed[point] = upload('failpoint-%s.png' % point)
st = settle(aid, LEASE * 3)
j = job(aid)
check(st[0] == 'ready' and j[1:3] == ['done', attempts] and variants(aid, 1) == ref, '%s: %s %s' % (point, st, j))
wait_for('worker restarted', lambda: set(compose('ps', '-a', 'worker', '--format', '{{.State}}').split()) == {'running'}, 30)
how = 'redelivery → no-op (аренда жива), аренда истекла → попытка 2' if attempts == '2' else 'redelivery → no-op (job done)'
record(label, '%s; ready за %.0f с, попыток %s, варианты = контрольным' % (how, time.monotonic() - started, attempts))
# S11. Зависший worker: пауза 35 с > аренды 25 с. Работу забирает другая попытка, поздний результат отброшен.
started = time.monotonic()
s11 = upload('failpoint-worker_after_side_effect-35s.png')
st = settle(s11, 90)
j = job(s11)
ready_after = time.monotonic() - started
wait_for('stale attempt fenced', lambda: any('аренда потеряна' in line for line in deliveries(j[0])), 60)
check(st[0] == 'ready' and j[1:3] == ['done', '2'] and variants(s11, 1) == ref, 'S11: %s %s' % (st, j))
record('S11 worker завис на 35 с (аренда 25 с)', 'попытка 2 → ready за %.0f с; попытка 1 проснулась → fencing: результат отброшен' % ready_after)
# S12. S3 недоступен для worker: backoff с jitter → retry_exhausted → реестр failed → replay.
compose('stop', 'worker')
s12 = upload('transient.png')
compose('stop', 's3')
try:
compose('up', '-d', '--no-deps', 'worker', env=TEST_ENV) # start поднял бы и S3 по цепочке depends_on
st = wait_for('retry exhausted', lambda: state(s12)[0] == 'failed' and state(s12), 120)
j = job(s12)
delays = rows("SELECT attempt, round(extract(epoch FROM available_at - created_at)::numeric, 1) FROM outbox "
"WHERE job_id = '%s' AND attempt > 1 ORDER BY attempt" % j[0])
registry = [r for r in jobs('failed') if r.get('attachment_id') == s12]
meta = c.call('GET', '/api/v1/attachments/' + s12, 200, actor=bob, schema='Attachment')['json']
c.call('GET', '/api/v1/attachments/' + s12 + '/content', 409, actor=bob)
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=alice, body={'text': '', 'attachment_ids': [s12]},
headers={'Idempotency-Key': uuid.uuid4().hex})
check(st[2] == 'retry_exhausted' and j[1:3] == ['failed', '5'] and len(registry) == 1
and meta['status'] == 'failed' and meta['error_code'] == 'retry_exhausted', 'S12: %s %s' % (st, j))
finally:
compose('start', 's3')
wait_for('s3 healthy', lambda: healthy('s3'), 60)
replay = jobs('replay', s12)[-1]
st = settle(s12)
audit = rows("SELECT previous_error, previous_attempts FROM job_replays WHERE job_id = '%s'" % j[0])
again = jobs('replay', s12)[-1]
check(replay['replayed'] and st[0] == 'ready' and audit == [['retry_exhausted', '5']] and not again['replayed']
and variants(s12, 1) == ref, 'S12 replay: %s %s %s' % (replay, st, again))
record('S12 S3 недоступен → retry_exhausted', 'задержки попыток 2–5: %s с; failed в реестре, API: failed/409'
% ', '.join(d for _, d in delays))
record(' replay', 'аудит (retry_exhausted, 5) → ready; повторный replay: %s' % again['reason'])
# S13. Постоянная ошибка: файл проходит приём, но не декодируется — failed сразу, без повторов.
s13 = upload('bad-filter.png', bad_filter_png())
st = wait_for('permanent failure', lambda: state(s13)[0] == 'failed' and state(s13), 60)
check(st[2] == 'invalid_image' and job(s13)[1:3] == ['failed', '1'], 'S13: %s' % st)
record('S13 постоянная ошибка (фильтр PNG = 9)', 'failed invalid_image с первой попытки, без повторов')
# S14. Брокер остановлен: API принимает файлы (202), задания ждут в outbox; брокер вернулся — ready.
compose('stop', 'rabbitmq')
try:
s14 = [upload('broker-down-%d.png' % i) for i in range(3)]
c.call('GET', '/health/ready', 200) # readiness API не зависит от брокера
unpublished = sql("SELECT count(*) FROM outbox o JOIN jobs j ON j.job_id = o.job_id WHERE o.published_at IS NULL "
"AND j.attachment_id IN ('%s')" % "', '".join(s14))
check(unpublished == '3', 'S14: unpublished %s' % unpublished)
finally:
compose('start', 'rabbitmq')
started = time.monotonic()
for aid in s14:
check(settle(aid, 180)[0] == 'ready' and variants(aid, 1) == ref, 'S14: %s' % aid)
record('S14 брокер остановлен', '3 upload → 202, неопубликовано в outbox 3; брокер вернулся → все ready за %.0f с'
% (time.monotonic() - started))
# Инварианты по всем вложениям тестового чата.
print('\nИнварианты:')
atts = rows("SELECT id, state, coalesce(pipeline_version, 0), filename FROM attachments WHERE chat_id = '%s'" % chat['id'])
open_work = [a for a in atts if a[1] not in ('ready', 'failed') and a[0] != s1]
check(not open_work, 'I1: %s' % open_work)
print(' I1 нет потерянной работы: %d вложений с заданием, все ready/failed; S1 (без 202) — pending до reconciler' % (len(atts) - 1))
counts = rows("SELECT v.attachment_id, v.pipeline_version, count(*) FROM attachment_variants v JOIN attachments a ON a.id = v.attachment_id "
"WHERE a.chat_id = '%s' GROUP BY 1, 2" % chat['id'])
check(all(n == '3' for _, _, n in counts), 'I2: %s' % counts)
ready = [a for a in atts if a[1] == 'ready']
check(all(any(aid == a[0] and ver == a[2] for aid, ver, _ in counts) for a in ready), 'I2: ready without variants')
print(' I2 один результат: %d наборов (вложение, версия), в каждом ровно 3 варианта' % len(counts))
check(state(s4)[:2] == ['ready', '2'] and variants(s4, 2) == v2 and state(s7)[:2] == ['ready', '2'] and variants(s7, 2) == v2_7, 'I3')
print(' I3 v2 не перезаписана: S5–S7 остались v2, sha256 вариантов v2 не изменились после старых job')
same = [a for a in ready if a[2] == '1']
check(all(variants(a[0], 1) == ref for a in same) and variants(s4, 1) == ref, 'I4')
print(' I4 тот же результат: у %d ready v1 после сбоев sha256 вариантов = контрольным' % len(same))
downloads = 0
for a in ready:
meta = c.call('GET', '/api/v1/attachments/' + a[0], 200, actor=bob, schema='Attachment')['json']
check(c.call('GET', '/api/v1/attachments/' + a[0] + '/content', 200, actor=bob)['bytes'] == PNG, 'I5 original')
for v in meta['variants']:
body = c.call('GET', '/api/v1/attachments/%s/content?variant=%s' % (a[0], v['name']), 200, actor=bob)['bytes']
check(len(body) == v['size_bytes'] and hashlib.sha256(body).hexdigest() == v['sha256'], 'I5 %s' % v['name'])
downloads += 1
print(' I5 API согласован: %d оригиналов и %d вариантов скачаны, размер и sha256 = метаданным' % (len(ready), downloads))
states = dict((s, n) for s, n in rows("SELECT j.state, count(*) FROM jobs j JOIN attachments a ON a.id = j.attachment_id "
"WHERE a.chat_id = '%s' GROUP BY 1" % chat['id']))
check(set(states) <= {'done', 'failed', 'superseded'}, 'I6 jobs: %s' % states)
# Остатки ожидаются ровно от трёх сценариев; находки по чужим вложениям (прерванные прошлые прогоны) не считаем.
found, summary = reconcile('--grace=0')
ids = {a[0] for a in atts}
mine = {}
for f in found:
owner = f.get('id') or f['key'].split('/')[1]
if owner in ids:
mine.setdefault(f['finding'], set()).add(owner)
check(mine == {'stale_pending': {s1}, 'orphan_variant': {crashed['worker_after_side_effect']},
'published_staging': {crashed['worker_after_commit']}}, 'I6 reconcile: %s' % mine)
n_variants = sum(1 for f in found if f['finding'] == 'orphan_variant' and f['key'].split('/')[1] in ids)
fixed = reconcile('--grace=0', '--apply')[1]
after = reconcile('--grace=0')[1]['findings']
check(not after and n_variants == 3, 'I6 after cleanup: %s, orphan variants %d' % (after, n_variants))
print(' I6 job: %s; reconciler: stale_pending S1, orphan_variant ×%d попытки 1 в S9, published_staging S10 — и только они;'
' применено %d (всего на стенде %s), повторный обход: {}' % (json.dumps(states), n_variants, fixed['applied'],
json.dumps(summary['findings'])))
finally:
compose('start', 's3', 'worker')
compose('up', '-d', '--no-deps', 'api', 'worker') # FAILPOINTS и таймаут — снова из .env
wait_for('api healthy', lambda: healthy('api'), 90)
print('\n'.join(['', 'Сводка:'] + report))
print('PASS: 14 fault scenarios, invariants I1–I6 hold (at-least-once delivery + idempotent effect, not exactly-once)')
if __name__ == '__main__':
run(main)
+79
View File
@@ -0,0 +1,79 @@
#!/usr/bin/env python3
"""Трек 2, versioned pipeline: выкатка pipeline v2 без потери работы и без перезаписи.
1. Новые загрузки сразу получают v2: api пересоздаётся с PIPELINE_VERSION=2 (worker уже поддерживает v1 и v2).
2. Старые ready-вложения: `jobs reprocess --version=2`; повтор команды ничего не ставит (ключ attachment_id + версия).
3. Пока идёт переобработка, вложение остаётся ready и отдаёт прежние варианты: в processing не откатывается.
4. Итог: у всех ready версия 2; для одинаковых байтов v2 детерминирована (sha256 совпадает с новой загрузкой);
у каждой пары (вложение, версия) ровно 3 варианта, варианты v1 остаются историей и не отдаются.
В конце api возвращается к PIPELINE_VERSION из .env. Запуск: python3 student-tests/reprocess_v2.py --base-url http://localhost:8080"""
import hashlib
import time
from failures import PNG, sql
from pipeline_faults import compose, healthy, jobs, rows, wait_for
from client import Client, arguments, check, run
def main():
args = arguments('Pipeline v1 -> v2 rollout and reprocess')
c = Client(args.base_url, args.ca_file, timeout=30)
alice, bob, _, chat = c.bootstrap()
def upload(name):
att = c.call('POST', '/api/v1/chats/%s/attachments?filename=%s' % (chat['id'], name), 202, actor=alice, raw=PNG,
headers={'Content-Type': 'image/png'}, schema='Attachment')['json']
return c.wait_ready(bob, att)
def thumbnail(att):
return hashlib.sha256(c.call('GET', '/api/v1/attachments/%s/content?variant=thumbnail' % att['id'], 200, actor=bob)['bytes']).hexdigest()
def version(att):
return sql("SELECT pipeline_version FROM attachments WHERE id = '%s'" % att['id'])
def by_version():
return ', '.join('v%s: %s' % tuple(r) for r in rows("SELECT pipeline_version, count(*) FROM attachments WHERE state = 'ready' GROUP BY 1 ORDER BY 1"))
old = upload('before-v2.png')
old_thumb = thumbnail(old)
check(version(old) == '1', 'expected v1 before rollout')
print('до выкатки: ready по версиям — %s; вложение %s v1' % (by_version(), old['id']))
try:
compose('up', '-d', '--no-deps', 'api', env={'PIPELINE_VERSION': '2'})
wait_for('api healthy with PIPELINE_VERSION=2', lambda: healthy('api'), 90)
new = upload('after-v2.png')
check(version(new) == '2' and thumbnail(new) != old_thumb, 'new upload is not v2')
print('api с PIPELINE_VERSION=2: новая загрузка %s сразу v2 (thumbnail отличается от v1)' % new['id'])
started = time.monotonic()
first = jobs('reprocess', '--version=2')[-1]
states = set()
while True:
states.add(c.call('GET', '/api/v1/attachments/' + old['id'], 200, actor=bob, schema='Attachment')['json']['status'])
thumbnail(old) # во время переобработки вариант доступен
if not int(sql("SELECT count(*) FROM jobs WHERE pipeline_version = 2 AND state IN ('queued', 'processing')")):
break
check(time.monotonic() - started < 600, 'reprocess did not finish')
time.sleep(0.5)
elapsed = time.monotonic() - started
second = jobs('reprocess', '--version=2')[-1]
check(states == {'ready'}, 'attachment left ready during reprocess: %s' % states)
check(second['enqueued'] == 0, 'second reprocess enqueued %s' % second)
print('reprocess --version=2: поставлено %d, все done за %.1f с (%.1f вложений/с); статус во время: %s; повтор: поставлено %d'
% (first['enqueued'], elapsed, first['enqueued'] / max(elapsed, 0.001), ', '.join(sorted(states)), second['enqueued']))
left = rows("SELECT id FROM attachments WHERE state = 'ready' AND pipeline_version < 2")
check(not left, 'ready attachments still below v2: %d' % len(left))
bad = rows("SELECT attachment_id, pipeline_version, count(*) FROM attachment_variants GROUP BY 1, 2 HAVING count(*) <> 3")
check(not bad, 'variant sets with count != 3: %s' % bad)
failed = rows("SELECT state, count(*) FROM jobs WHERE pipeline_version = 2 GROUP BY 1")
check(version(old) == '2' and thumbnail(old) == thumbnail(new) != old_thumb, 'reprocessed result differs from fresh v2')
print('итог: ready по версиям — %s; jobs v2: %s; у всех пар (вложение, версия) по 3 варианта;'
% (by_version(), ', '.join('%s %s' % tuple(r) for r in failed)))
print(' %s после reprocess отдаёт v2, thumbnail побайтно равен свежей загрузке v2 (детерминизм pipeline)' % old['id'])
finally:
compose('up', '-d', '--no-deps', 'api')
wait_for('api healthy', lambda: healthy('api'), 90)
print('PASS: v2 rollout — new uploads v2, reprocess idempotent, no rollback of ready, deterministic result')
if __name__ == '__main__':
run(main)
+31
View File
@@ -0,0 +1,31 @@
// Проба прав S3 изнутри контейнера сервиса (его же ключами из /run/secrets).
// Запуск: docker compose exec -T api node --input-type=module - <key> < student-tests/s3_probe.mjs
// Печатает по строке «операция: результат»; ключи и секреты не выводятся.
import { readFileSync } from 'node:fs';
import { CreateBucketCommand, GetObjectCommand, ListObjectsV2Command, PutObjectCommand, DeleteObjectCommand, S3Client } from '@aws-sdk/client-s3';
const key = process.argv[2];
const bucket = process.env.S3_BUCKET;
const s3 = new S3Client({
endpoint: process.env.S3_ENDPOINT, region: process.env.S3_REGION, forcePathStyle: true, maxAttempts: 1,
credentials: {
accessKeyId: readFileSync('/run/secrets/s3_access_key_id', 'utf8').trim(),
secretAccessKey: readFileSync('/run/secrets/s3_secret_access_key', 'utf8').trim(),
},
});
const probe = async (name, command) => {
try {
await s3.send(command);
console.log(`${name}: allowed`);
} catch (err) {
console.log(`${name}: denied (${err.$metadata?.httpStatusCode} ${err.name})`);
}
};
const scratch = `probe/${Date.now()}`;
await probe('GetObject own bucket', new GetObjectCommand({ Bucket: bucket, Key: key }));
await probe('ListObjectsV2 own bucket', new ListObjectsV2Command({ Bucket: bucket, MaxKeys: 1 }));
await probe('CreateBucket other', new CreateBucketCommand({ Bucket: `probe-${Date.now()}` }));
await probe('PutObject other bucket', new PutObjectCommand({ Bucket: 'other-bucket', Key: 'x', Body: 'x' }));
await probe('PutObject own bucket', new PutObjectCommand({ Bucket: bucket, Key: scratch, Body: 'x' }));
await probe('DeleteObject own bucket', new DeleteObjectCommand({ Bucket: bucket, Key: scratch }));
s3.destroy(); // keep-alive сокеты иначе держат процесс до idle-таймаута S3
+265
View File
@@ -0,0 +1,265 @@
#!/usr/bin/env python3
"""Сигналы наблюдаемости lab6 (уровни 3–4) на запущенном стенде; данные читаются через API Grafana (datasource proxy).
1. Контролируемый запрос с заданным traceparent: server span в Tempo (шаблон маршрута, X-Request-Id,
service.instance.id = X-Instance-Id, дочерние SQL-spans) и access-лог в Loki с тем же trace_id/span_id.
2. Ошибка 404: request_id из тела ошибки находит лог, а лог — trace.
3. Upload → один trace: SERVER (api) → PRODUCER publish → CONSUMER process (worker) → S3 и SQL; лог worker в trace.
4. Retry: S3 «зависает» (docker compose pause) на первую попытку → в том же trace две публикации и две обработки,
первая с ошибкой, вторая — ready. Шаг управляет Docker Compose этого каталога: только учебный стенд.
5. Метрики сигналов есть в Prometheus; в labels нет id пользователей/чатов/сообщений/вложений, request_id и сырых URL.
6. В spans и логах нет пароля, session token, текста сообщения и имени файла.
7. Dashboard загружен provisioning-ом из репозитория, его запросы к Prometheus/Loki/Tempo находят данные.
Запуск: python3 student-tests/telemetry_check.py --base-url http://localhost:8096 --grafana http://localhost:3096"""
import base64
import json
from pathlib import Path
import re
import secrets
import subprocess
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import SPEC, Client, ROOT, arguments, check, run # noqa: E402
UUID_RE = re.compile(r'[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}', re.I)
PNG = (ROOT / 'tests/fixtures/sample.png').read_bytes()
def hexid(b64): # Tempo отдаёт OTLP JSON: id spans в base64, в логах и traceparent — hex
return base64.b64decode(b64).hex()
class Grafana:
def __init__(self, base):
password = (ROOT / 'secrets/grafana_admin_password').read_text().strip() # не печатается
self.base = base.rstrip('/')
self.auth = 'Basic ' + base64.b64encode(f'admin:{password}'.encode()).decode()
def get(self, path, **params):
url = self.base + path + ('?' + urllib.parse.urlencode(params) if params else '')
req = urllib.request.Request(url, headers={'Authorization': self.auth, 'Accept': 'application/json'})
try:
with urllib.request.urlopen(req, timeout=15) as r:
return r.read().decode()
except urllib.error.HTTPError as e:
if e.code == 404:
return ''
raise
def trace(self, trace_id):
raw = self.get(f'/api/datasources/proxy/uid/tempo/api/traces/{trace_id}')
spans = []
for batch in json.loads(raw).get('batches', []) if raw else []:
res = {a['key']: next(iter(a['value'].values()), None) for a in batch['resource']['attributes']}
for scope in batch.get('scopeSpans', []):
for s in scope['spans']:
attrs = {a['key']: next(iter(a['value'].values()), None) for a in s.get('attributes', [])}
spans.append({'name': s['name'], 'kind': s.get('kind', '').replace('SPAN_KIND_', ''), 'id': hexid(s['spanId']),
'parent': hexid(s.get('parentSpanId', '')), 'status': s.get('status', {}).get('code', ''),
'start': int(s['startTimeUnixNano']), 'end': int(s['endTimeUnixNano']), 'attrs': attrs, 'resource': res})
return raw, spans
def logs(self, query, minutes=30):
raw = self.get('/api/datasources/proxy/uid/loki/loki/api/v1/query_range', query=query, limit=200,
start=str(int((time.time() - minutes * 60) * 1e9)), direction='forward')
rows = [{**stream['stream'], 'line': line} for stream in json.loads(raw)['data']['result'] for _, line in stream['values']]
return raw, rows
def prom(self, path, **params):
return json.loads(self.get('/api/datasources/proxy/uid/prometheus/api/v1/' + path, **params))['data']
def until(what, fn, ready=bool, seconds=45):
deadline = time.monotonic() + seconds
while True:
value = fn()
if ready(value):
return value
check(time.monotonic() < deadline, f'{what}: не дождались за {seconds} с')
time.sleep(1)
def has(kind, outcome=None):
return lambda x: any(s['kind'] == kind and (outcome is None or s['attrs'].get('messenger.job.outcome') == outcome) for s in x[1])
def traceparent():
tid, sid = secrets.token_hex(16), secrets.token_hex(8)
return tid, sid, f'00-{tid}-{sid}-01'
def compose(*args):
r = subprocess.run(['docker', 'compose', *args], cwd=ROOT, text=True, capture_output=True)
check(r.returncode == 0, f'docker compose {args[0]}: {r.stderr.strip()[-200:]}')
return r.stdout.strip()
def sql(query):
return compose('exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-tAc', query)
def main():
args = arguments('Сигналы наблюдаемости lab6', lambda p: p.add_argument('--grafana', default='http://localhost:3000'))
c, g = Client(args.base_url), Grafana(args.grafana)
raw_dump = [] # всё, что прочитано из Tempo/Loki, — для проверки отсутствия секретов (шаг 6)
alice, bob, eve, chat = c.bootstrap()
text = 'секретный текст ' + uuid.uuid4().hex
# 1. Контролируемый запрос: клиент сам задаёт trace_id, API продолжает этот trace.
tid, client_span, tp = traceparent()
r = c.call('POST', f'/api/v1/chats/{chat["id"]}/messages', 201, actor=alice, body={'text': text},
headers={'Idempotency-Key': uuid.uuid4().hex, 'traceparent': tp}, schema='Message')
rid, instance = r['headers']['X-Request-Id'], r['headers']['X-Instance-Id']
raw, spans = until('trace сообщения в Tempo', lambda: g.trace(tid), has('SERVER'))
raw_dump.append(raw)
server = [s for s in spans if s['kind'] == 'SERVER']
check(len(server) == 1, 'ожидался один server span')
srv = server[0]
check(srv['name'] == 'POST /api/v1/chats/{chat_id}/messages', f'имя span: {srv["name"]}')
check(srv['parent'] == client_span, 'server span не продолжает traceparent клиента')
check(srv['attrs'].get('http.route') == '/api/v1/chats/{chat_id}/messages', 'нет http.route')
check(srv['attrs'].get('messenger.request_id') == rid, 'request_id span ≠ X-Request-Id')
check(srv['resource'].get('service.name') == 'messenger-api', 'service.name')
check(srv['resource'].get('service.instance.id') == instance, 'service.instance.id ≠ X-Instance-Id')
check(srv['resource'].get('deployment.environment.name') == 'lab', 'deployment.environment.name')
check(srv['resource'].get('service.version'), 'service.version')
db_spans = [s for s in spans if s['parent'] == srv['id'] and s['name'].startswith('pg.query')]
check(db_spans, 'нет дочерних SQL-spans')
raw, logs = until('access-лог в Loki', lambda: g.logs(f'{{service_name="messenger-api"}} | trace_id="{tid}" | event="http.request"'),
lambda x: x[1])
raw_dump.append(raw)
log = logs[0]
check(log['request_id'] == rid and log['span_id'] == srv['id'], 'лог не связан с server span')
check(log['severity_text'] == 'INFO' and log['service_name'] == 'messenger-api', 'severity/service.name лога')
print(f'PASS 1 trace {tid}: server span {srv["name"]} ({len(db_spans)} SQL), лог request_id={rid}')
# 2. Ошибка клиента: по request_id из тела ответа находится лог, по trace_id лога — trace.
err = c.call('GET', f'/api/v1/chats/{chat["id"]}', 404, actor=eve)['json']['error']
raw, logs = until('лог ошибки по request_id', lambda: g.logs(f'{{service_name="messenger-api"}} | request_id="{err["request_id"]}"'),
lambda x: x[1])
raw_dump.append(raw)
err_tid = logs[0]['trace_id']
raw, spans = until('trace ошибки', lambda: g.trace(err_tid), has('SERVER'))
raw_dump.append(raw)
check(any(s['kind'] == 'SERVER' and s['attrs'].get('http.response.status_code') == '404' for s in spans), 'trace 404')
print(f'PASS 2 404 request_id={err["request_id"]} → лог → trace {err_tid}')
# 3. Upload → обработка worker-ом в одном trace.
filename = f'тайное-имя-{uuid.uuid4().hex[:8]}.png'
tid, client_span, tp = traceparent()
att = c.call('POST', f'/api/v1/chats/{chat["id"]}/attachments?filename={urllib.parse.quote(filename)}', 202, actor=alice,
raw=PNG, headers={'Content-Type': 'image/png', 'traceparent': tp}, schema='Attachment')['json']
c.wait_ready(alice, att)
raw, spans = until('trace upload → worker', lambda: g.trace(tid), has('CONSUMER', 'done'))
raw_dump.append(raw)
by_id = {s['id']: s for s in spans}
srv = next(s for s in spans if s['kind'] == 'SERVER')
prod = [s for s in spans if s['kind'] == 'PRODUCER']
cons = [s for s in spans if s['kind'] == 'CONSUMER']
check(len(prod) == 1 and prod[0]['parent'] == srv['id'], 'PRODUCER span не дочерний к upload')
check(len(cons) == 1 and cons[0]['parent'] == prod[0]['id'], 'CONSUMER span не дочерний к PRODUCER')
check(prod[0]['resource']['service.name'] == 'messenger-api' and cons[0]['resource']['service.name'] == 'messenger-worker', 'сервисы')
under = {s['name'] for s in spans if s['parent'] == cons[0]['id']}
check({'claim job', 'S3.GetObject', 'render variants', 'S3.PutObject', 'S3.CopyObject', 'commit result', 'S3.DeleteObject'} <= under,
f'шаги worker: {sorted(under)}')
check(any(by_id.get(s['parent'], {}).get('name') == 'commit result' and s['name'].startswith('pg.query') for s in spans),
'нет SQL фиксации результата')
raw, logs = until('лог worker в trace', lambda: g.logs(f'{{service_name="messenger-worker"}} | trace_id="{tid}" | event="job.ready"'),
lambda x: x[1])
raw_dump.append(raw)
check(logs[0]['span_id'] == cons[0]['id'], 'лог job.ready не связан с CONSUMER span')
print(f'PASS 3 trace {tid}: upload → publish → process ({len(spans)} spans), лог job.ready в том же trace')
# 4. Retry: первая попытка упирается в «зависший» S3 (requestTimeout 8 с), вторая после backoff — успешна.
# S3 размораживается сразу после первой ошибки: вторая попытка (backoff 1–2 с) застанет его рабочим.
compose('stop', 'worker')
tid, client_span, tp = traceparent()
try:
att = c.call('POST', f'/api/v1/chats/{chat["id"]}/attachments?filename=retry.png', 202, actor=alice,
raw=PNG, headers={'Content-Type': 'image/png', 'traceparent': tp}, schema='Attachment')['json']
compose('pause', 's3')
compose('up', '-d', '--no-deps', 'worker') # start ждал бы healthy у замороженного s3
until('первая попытка завершилась ошибкой',
lambda: sql(f"SELECT 1 FROM jobs WHERE attachment_id = '{att['id']}' AND error_code IS NOT NULL"), seconds=60)
finally:
compose('unpause', 's3')
compose('up', '-d', '--no-deps', 'worker')
c.wait_ready(alice, att, wait_seconds=60)
raw, spans = until('trace с повтором', lambda: g.trace(tid), has('CONSUMER', 'done'))
raw_dump.append(raw)
prod = sorted((s for s in spans if s['kind'] == 'PRODUCER'), key=lambda s: s['start'])
cons = sorted((s for s in spans if s['kind'] == 'CONSUMER'), key=lambda s: s['start'])
check(len(prod) == 2 and len(cons) == 2, f'ожидались 2 публикации и 2 обработки: {len(prod)}/{len(cons)}')
check(cons[0]['parent'] == prod[0]['id'] and prod[1]['parent'] == cons[0]['id'] and cons[1]['parent'] == prod[1]['id'],
'цепочка publish → process → publish → process нарушена')
check(cons[0]['status'] == 'STATUS_CODE_ERROR' and cons[0]['attrs'].get('messenger.job.outcome') == 'retry', 'первая попытка не retry')
check(cons[1]['attrs'].get('messenger.job.attempt') == '2', 'вторая попытка не attempt 2')
raw, logs = until('логи retry', lambda: g.logs(f'{{service_name="messenger-worker"}} | trace_id="{tid}"'),
lambda x: {'job.retry', 'job.ready'} <= {l['event'] for l in x[1]})
raw_dump.append(raw)
print(f'PASS 4 trace {tid}: publish#1 → process#1 (retry, S3 timeout) → publish#2 → process#2 (ready)')
# 5. Метрики контракта есть, labels — низкой кардинальности.
required = ['http_server_request_duration_seconds_bucket', 'messenger_job_duration_seconds_bucket',
'messenger_attachment_time_to_ready_seconds_bucket', 'messenger_jobs_backlog', 'messenger_jobs_oldest_age_seconds',
'messenger_outbox_pending', 'rabbitmq_detailed_queue_messages_ready', 'db_client_connection_count',
'db_client_connection_pending_requests', 'messenger_worker_busy', 'messenger_worker_capacity',
'process_cpu_time_seconds_total', 'process_memory_usage_bytes', 'nodejs_eventloop_delay_p99_seconds']
names = set(g.prom('label/__name__/values'))
missing = [m for m in required if m not in names]
check(not missing, f'нет метрик: {missing}')
# Labels метрик приложения (у otelcol_* есть url_path — постоянный путь экспортёра, не запрос пользователя).
forbidden = {'user_id', 'chat_id', 'message_id', 'attachment_id', 'request_id', 'url', 'url_path', 'url_full', 'url_query',
'filename', 'text', 'messenger_request_id', 'messenger_job_id', 'messenger_attachment_id'}
app_labels = set(g.prom('labels', **{'match[]': '{job=~"messenger-.+"}'}))
check(not app_labels & forbidden, f'запрещённые labels: {app_labels & forbidden}')
# Значения живых серий (instant query): label values API отдаёт и устаревшие серии всего head-блока TSDB.
labels = set(g.prom('labels'))
for label in labels - {'__name__'}:
values = [r['metric'].get(label, '') for r in g.prom('query', query=f'group by ({label}) ({{{label}!=""}})')['result']]
check(not any(UUID_RE.search(v) for v in values), f'UUID в значениях label {label}')
routes = set(g.prom('label/http_route/values'))
check(routes and routes <= set(SPEC['paths']), f'http_route не из шаблонов OpenAPI: {sorted(routes - set(SPEC["paths"]))}')
print(f'PASS 5 метрики: {len(required)} обязательных есть; {len(labels)} labels без id/URL; {len(routes)} шаблонов http_route')
# 6. Секреты и содержимое не экспортируются (поиск и в прочитанных trace/логах, и по всему Loki за 30 минут).
blob = '\n'.join(raw_dump)
for name, value in (('пароль', alice['registration']['password']), ('session token', alice['token']),
('текст сообщения', text), ('имя файла', filename), ('имя файла (urlencoded)', urllib.parse.quote(filename))):
check(value not in blob, f'{name} попал в telemetry')
check(not g.logs(f'{{service_name=~"messenger-.+"}} |= `{value}`')[1], f'{name} найден в Loki')
check('Bearer ' not in blob and 'Basic ' not in blob, 'заголовок Authorization попал в telemetry')
print(f'PASS 6 секреты/контент не найдены в {len(raw_dump)} ответах Tempo/Loki и во всём Loki за 30 мин')
# 7. Dashboard из репозитория загружен provisioning-ом, его запросы находят данные за последние 15 минут
# (пустыми допустимы только панели ошибок экспорта и alerts — в норме этих серий нет).
dash = json.loads(g.get('/api/dashboards/uid/messenger-lab6'))
check(dash['meta'].get('provisioned') and dash['meta'].get('folderTitle') == 'Messenger', 'dashboard не из provisioning')
targets = [(p['title'], p['datasource']['uid'], t) for p in dash['dashboard']['panels'] for t in p.get('targets', [])]
now, empty = int(time.time()), []
for title, ds, t in targets:
if ds == 'prometheus':
q = t['expr'].replace('$__rate_interval', '1m')
found = g.prom('query_range', query=q, start=now - 900, end=now, step=30)['result']
elif ds == 'loki':
found = g.logs(t['expr'], minutes=15)[1]
else:
found = json.loads(g.get('/api/datasources/proxy/uid/tempo/api/search', q=t['query'], start=now - 900, end=now))['traces']
if not found:
empty.append(title)
allowed = re.compile(r'потер|отказ|alert', re.I)
check(all(allowed.search(t) for t in empty), f'панели без данных: {empty}')
print(f'PASS 7 dashboard «{dash["dashboard"]["title"]}»: {len(dash["dashboard"]["panels"])} панелей, '
f'{len(targets) - len(empty)}/{len(targets)} запросов с данными (пусто: {sorted(set(empty))})')
print('PASS: сигналы lab6 (traces, logs, metrics, связь через очередь, retry, отсутствие секретов, dashboard)')
if __name__ == '__main__':
run(main)
+35
View File
@@ -0,0 +1,35 @@
#!/usr/bin/env python3
"""Сохранность истории telemetry после перезапуска хранилищ (scripts/restart.sh): trace, логи этого trace и метрики,
записанные ДО перезапуска, читаются ПОСЛЕ него. Запуск: telemetry_history.py --grafana URL --trace-id ID --before UNIX_TS"""
import json
from pathlib import Path
import sys
import time
sys.path.insert(0, str(Path(__file__).resolve().parent))
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import check, run # noqa: E402
from telemetry_check import Grafana # noqa: E402
def main():
import argparse
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('--grafana', default='http://localhost:3000')
p.add_argument('--trace-id', required=True)
p.add_argument('--before', type=int, required=True, help='unix-время до перезапуска')
a = p.parse_args()
g = Grafana(a.grafana)
_, spans = g.trace(a.trace_id)
check(spans, 'trace до перезапуска не найден в Tempo')
_, logs = g.logs(f'{{service_name=~"messenger-.+"}} | trace_id="{a.trace_id}"', minutes=int((time.time() - a.before) / 60) + 60)
check(logs, 'логи trace до перезапуска не найдены в Loki')
series = g.prom('query_range', query='sum(http_server_request_duration_seconds_count{job="messenger-api"})',
start=a.before - 600, end=a.before, step=60)['result']
check(series and len(series[0]['values']) >= 5, 'нет метрик API за 10 минут до перезапуска')
print(f'PASS история после перезапуска: trace {a.trace_id} ({len(spans)} spans), {len(logs)} строк лога, '
f'{len(series[0]["values"])} точек метрики API за 10 мин до перезапуска')
if __name__ == '__main__':
run(main)
+97
View File
@@ -0,0 +1,97 @@
#!/usr/bin/env python3
"""Уровень 3, сценарий защиты 2–3: worker остановлен → upload 202 → сообщение с вложением → content 409, другие
сообщения работают → перезапуск API и брокера с сохранением volumes → worker запущен → то же вложение ready,
thumbnail скачивается. Печатает порядок действий, ID и состояние очереди (без токенов).
Управляет Docker Compose этого каталога. Запуск: python3 student-tests/worker_outage.py --base-url http://localhost:8080"""
import hashlib
import time
import uuid
from failures import PNG, compose, sql, wait_ready
from client import Client, arguments, check, run
from image_probe import jpeg_size
def queue():
"""Глубина quorum-очереди: (сообщений всего, без ack, consumers); None — брокер ещё не готов."""
try:
out = compose('exec', '-T', 'rabbitmq', 'rabbitmqctl', '-q', 'list_queues', '-p', 'messenger',
'name', 'messages', 'messages_unacknowledged', 'consumers', capture=True)
except AssertionError:
return None
for line in out.splitlines():
f = line.split()
if f and f[0] == 'attachments.process':
return tuple(map(int, f[1:4]))
return None
def main():
args = arguments('Worker outage: accepted job survives API and broker restart')
c = Client(args.base_url, args.ca_file, timeout=30)
alice, bob, _, chat = c.bootstrap()
t0 = time.monotonic()
def step(text):
print('%6.1f s %s' % (time.monotonic() - t0, text))
compose('stop', 'worker')
step('docker compose stop worker')
try:
att = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=outage.png', 202, actor=alice, raw=PNG,
headers={'Content-Type': 'image/png'}, schema='Attachment')['json']
check(att['status'] == 'queued' and att['variants'] == [], 'upload snapshot is not queued')
step('upload → 202 queued, attachment %s' % att['id'])
m = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=alice, schema='Message',
body={'text': 'файл ещё в очереди', 'attachment_ids': [att['id']]}, headers={'Idempotency-Key': uuid.uuid4().hex})['json']
step('сообщение с queued-вложением → 201, message %s' % m['id'])
content = '/api/v1/attachments/' + att['id'] + '/content'
for variant in ('', '?variant=thumbnail'):
check(c.call('GET', content + variant, 409, actor=bob)['json']['error']['code'] == 'conflict', 'content must be 409')
step('content и content?variant=thumbnail → 409 conflict')
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=bob, body={'text': 'обычное сообщение'},
headers={'Idempotency-Key': uuid.uuid4().hex}, schema='Message')
c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=10', 200, actor=bob, schema='MessagePage')
step('другие сообщения без worker: POST 201, история 200')
deadline = time.monotonic() + 10
while sql("SELECT count(*) FROM outbox o JOIN jobs j ON j.job_id = o.job_id WHERE j.attachment_id = '%s' "
"AND o.published_at IS NOT NULL" % att['id']) != '1':
check(time.monotonic() < deadline, 'outbox row was not published')
time.sleep(0.3)
job = sql("SELECT job_id || ' ' || state || ' attempts=' || attempts FROM jobs WHERE attachment_id = '%s'" % att['id'])
step('job %s; outbox опубликован (publisher confirm); очередь (messages, unacked, consumers) = %s' % (job, queue()))
compose('restart', 'api')
step('docker compose restart api (обе реплики, SIGTERM)')
compose('restart', 'rabbitmq')
deadline = time.monotonic() + 90
while (q := queue()) is None:
check(time.monotonic() < deadline, 'broker did not come back')
time.sleep(1)
wait_ready(c)
step('docker compose restart rabbitmq; после рестарта очередь = %s' % (q,))
check(q[0] >= 1, 'accepted job disappeared from the durable queue')
same = c.call('GET', '/api/v1/attachments/' + att['id'], 200, actor=bob, schema='Attachment')['json']
check(same['status'] == 'queued', 'attachment state lost after restart')
step('вложение после рестартов: %s (прежний токен)' % same['status'])
finally:
compose('start', 'worker')
started = time.monotonic()
step('docker compose start worker')
ready = c.wait_ready(bob, att, 90)
step('ready через %.1f s после старта worker; job: %s' % (time.monotonic() - started,
sql("SELECT state || ' attempts=' || attempts FROM jobs WHERE attachment_id = '%s'" % att['id'])))
thumb = [v for v in ready['variants'] if v['name'] == 'thumbnail']
check(len(thumb) == 1, 'expected exactly one thumbnail')
r = c.call('GET', content + '?variant=thumbnail', 200, actor=bob)
check(r['headers'].get_content_type() == 'image/jpeg' and jpeg_size(r['bytes']) == (256, 160), 'thumbnail is not 256x160 JPEG')
check(hashlib.sha256(r['bytes']).hexdigest() == thumb[0]['sha256'], 'thumbnail checksum mismatch')
original = c.call('GET', content, 200, actor=bob)['bytes']
check(original == PNG and hashlib.sha256(original).hexdigest() == ready['sha256'], 'original changed')
step('thumbnail 256x160 JPEG (sha256 = метаданным), оригинал совпадает побайтно; варианты: %s'
% ', '.join('%s %dx%d' % (v['name'], v['width'], v['height']) for v in ready['variants']))
print('PASS: job accepted while worker was down survived API + broker restart and reached ready')
if __name__ == '__main__':
run(main)