lab6: OpenTelemetry (traces, metrics, logs), Collector, Prometheus, Loki, Tempo, Grafana; перенос trace context через outbox и AMQP
This commit is contained in:
@@ -0,0 +1,143 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Негативные и граничные сценарии вложений (уровень 4).
|
||||
|
||||
Покрывает: слишком большой файл (по Content-Length и по пикселям), «бомбу»,
|
||||
повреждённое изображение, подмену MIME, чужой формат, опасные filename,
|
||||
чужое attachment_id, вложение другого чата, правила text/attachment_ids,
|
||||
идемпотентность с вложениями, варианты. Любой 500 — провал (Client проверяет код).
|
||||
"""
|
||||
import hashlib
|
||||
import uuid
|
||||
from labutil import bomb_png, fixture, noise_png, png, raw_post, wait_status
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
MAX = 10 * 1024 * 1024
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Attachment negative suite (lab4 level 4)')
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
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']
|
||||
path = '/api/v1/chats/' + chat['id'] + '/attachments?filename='
|
||||
results = []
|
||||
|
||||
def up(name, data, ctype, expected, chat_path=path, actor=alice):
|
||||
r = c.call('POST', chat_path + name, expected, actor=actor, raw=data, headers={'Content-Type': ctype},
|
||||
schema='Attachment' if expected == 202 else None)
|
||||
results.append((name[:40], ctype, len(data), r['status']))
|
||||
return r
|
||||
|
||||
small_png, small_jpg = fixture('small.png'), fixture('small.jpg')
|
||||
|
||||
# --- корректные файлы ---
|
||||
a_png = up('ok.png', small_png, 'image/png', 202)['json']
|
||||
a_jpg = up('ok.jpg', small_jpg, 'image/jpeg', 202)['json']
|
||||
check(a_jpg['content_type'] == 'image/jpeg' and a_jpg['sha256'] == hashlib.sha256(small_jpg).hexdigest(), 'jpeg metadata')
|
||||
uni = up('%D1%84%D0%BE%D1%82%D0%BE%20%F0%9F%98%80.png', small_png, 'image/png', 202)['json']
|
||||
check(uni['filename'] == 'фото 😀.png', 'unicode filename not preserved')
|
||||
up('params.png', small_png, 'image/png; charset=binary', 202)
|
||||
near = noise_png(MAX - 200_000)
|
||||
check(len(near) <= MAX, 'generator produced too large file')
|
||||
big_ok = up('near-limit.png', near, 'image/png', 202)['json']
|
||||
wait_status(c, bob, big_ok['id'], ('ready',), timeout=180)
|
||||
got = c.call('GET', '/api/v1/attachments/' + big_ok['id'] + '/content', actor=bob)
|
||||
check(got['bytes'] == near, 'near-limit file changed on download')
|
||||
|
||||
# --- размер и пиксели ---
|
||||
# Content-Length больше лимита: 413 сразу, без чтения тела.
|
||||
hdr = {'Authorization': 'Bearer ' + alice['token'], 'Content-Type': 'image/png'}
|
||||
st, _ = raw_post(c.base, path + 'too-big.png', dict(hdr, **{'Content-Length': str(MAX + 1)}),
|
||||
(b'\x89PNG\r\n\x1a\n' + b'\0' * 65528 for _ in range(1)))
|
||||
check(st == 413, 'Content-Length > limit: expected 413, got %s' % st)
|
||||
results.append(('too-big.png (Content-Length)', 'image/png', MAX + 1, st))
|
||||
# Без Content-Length (chunked), реально 11 MiB: сервер читает не больше лимита + 1 байт.
|
||||
def chunked(total=11 * 1024 * 1024, part=256 * 1024):
|
||||
yield b'%x\r\n\x89PNG\r\n\x1a\n\r\n' % 8
|
||||
sent = 8
|
||||
while sent < total:
|
||||
yield b'%x\r\n' % part + b'\0' * part + b'\r\n'
|
||||
sent += part
|
||||
yield b'0\r\n\r\n'
|
||||
st, _ = raw_post(c.base, path + 'too-big-chunked.png', dict(hdr, **{'Transfer-Encoding': 'chunked'}), chunked())
|
||||
check(st == 413, 'chunked > limit: expected 413, got %s' % st)
|
||||
results.append(('too-big-chunked.png (no Content-Length)', 'image/png', 11 * 1024 * 1024, st))
|
||||
up('bomb.png', bomb_png(), 'image/png', 413)
|
||||
up('over-pixels.png', bomb_png(8000, 5001), 'image/png', 413)
|
||||
|
||||
# --- содержимое и MIME ---
|
||||
up('truncated.png', small_png[:len(small_png) // 2], 'image/png', 415)
|
||||
broken = bytearray(small_png)
|
||||
broken[len(broken) // 2] ^= 0xFF
|
||||
up('corrupt.png', bytes(broken), 'image/png', 415)
|
||||
up('truncated.jpg', small_jpg[:len(small_jpg) - 2], 'image/jpeg', 415)
|
||||
up('mime-swap.png', small_png, 'image/jpeg', 415) # PNG, объявлен как JPEG
|
||||
up('mime-swap.jpg', small_jpg, 'image/png', 415)
|
||||
up('text.png', b'definitely not an image', 'image/png', 415)
|
||||
up('gif.gif', b'GIF89a\x01\x00\x01\x00\x00\x00\x00;', 'image/gif', 415)
|
||||
up('ctype-missing.png', small_png, 'application/octet-stream', 415)
|
||||
up('empty.png', b'', 'image/png', 415)
|
||||
up('short-data.png', png(8, 8, raw=b'\x00' * 10), 'image/png', 415)
|
||||
|
||||
# --- filename ---
|
||||
for bad in ('..%2Fetc%2Fpasswd', 'a%5Cb.png', 'nul%00.png', 'bell%07.png', '%20%20%20', 'x' * 256, ''):
|
||||
up(bad, small_png, 'image/png', 400)
|
||||
c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments', 400, actor=alice, raw=small_png,
|
||||
headers={'Content-Type': 'image/png'})
|
||||
c.call('POST', path + 'a.png&filename=b.png', 400, actor=alice, raw=small_png, headers={'Content-Type': 'image/png'})
|
||||
|
||||
# --- доступ ---
|
||||
up('eve.png', small_png, 'image/png', 404, actor=eve)
|
||||
c.call('POST', path + 'anon.png', 401, raw=small_png, headers={'Content-Type': 'image/png'})
|
||||
for suffix in ('', '/content'):
|
||||
c.call('GET', '/api/v1/attachments/' + a_png['id'] + suffix, 404, actor=eve)
|
||||
c.call('GET', '/api/v1/attachments/' + str(uuid.uuid4()) + suffix, 404, actor=alice)
|
||||
c.call('GET', '/api/v1/attachments/not-a-uuid' + suffix, 400, actor=alice)
|
||||
wait_status(c, bob, a_png['id'], ('ready',))
|
||||
wait_status(c, bob, a_jpg['id'], ('ready',))
|
||||
th = c.call('GET', '/api/v1/attachments/' + a_png['id'] + '/content?variant=thumbnail', actor=bob)
|
||||
check(th['headers'].get_content_type() == 'image/jpeg', 'thumbnail of small png')
|
||||
c.call('GET', '/api/v1/attachments/' + a_png['id'] + '/content?variant=bogus', 400, actor=bob)
|
||||
orig = c.call('GET', '/api/v1/attachments/' + a_png['id'] + '/content?variant=original', actor=bob)
|
||||
check(orig['bytes'] == small_png and orig['headers'].get_content_type() == 'image/png', 'original variant')
|
||||
|
||||
# --- сообщения с вложениями ---
|
||||
foreign = up('foreign.png', small_png, 'image/png', 202,
|
||||
chat_path='/api/v1/chats/' + other['id'] + '/attachments?filename=')['json']
|
||||
mpath = '/api/v1/chats/' + chat['id'] + '/messages'
|
||||
|
||||
def msg(body, expected, key=None, actor=alice):
|
||||
return c.call('POST', mpath, expected, actor=actor, body=body,
|
||||
headers={'Idempotency-Key': key or uuid.uuid4().hex},
|
||||
schema='Message' if expected == 201 else None)
|
||||
|
||||
msg({'text': '', 'attachment_ids': [foreign['id']]}, 404) # вложение другого чата
|
||||
msg({'text': '', 'attachment_ids': [str(uuid.uuid4())]}, 404) # неизвестное
|
||||
msg({'text': 'x', 'attachment_ids': ['nope']}, 400)
|
||||
msg({'text': 'x', 'attachment_ids': [a_png['id'], a_png['id']]}, 400)
|
||||
msg({'text': 'x', 'attachment_ids': [str(uuid.uuid4()) for _ in range(11)]}, 400)
|
||||
msg({'text': ''}, 400)
|
||||
msg({'text': ' ', 'attachment_ids': []}, 400)
|
||||
msg({'attachment_ids': [a_png['id']]}, 400) # text обязателен
|
||||
msg({'text': '', 'attachment_ids': [a_png['id']]}, 404, actor=eve)
|
||||
key = uuid.uuid4().hex
|
||||
m1 = msg({'text': '', 'attachment_ids': [a_png['id'], a_jpg['id']]}, 201, key=key)['json']
|
||||
check(m1['attachment_ids'] == [a_png['id'], a_jpg['id']] and m1['text'] == '', 'attachment order/text')
|
||||
m2 = msg({'attachment_ids': [a_png['id'], a_jpg['id']], 'text': ''}, 201, key=key)['json']
|
||||
check(m2 == m1, 'idempotent replay with attachments differs')
|
||||
msg({'text': '', 'attachment_ids': [a_jpg['id'], a_png['id']]}, 409, key=key) # другой порядок = другое тело
|
||||
plain = msg({'text': 'без вложений'}, 201)['json']
|
||||
check(plain['attachment_ids'] == [], 'missing attachment_ids must be []')
|
||||
hist = c.call('GET', mpath + '?limit=100', actor=bob, schema='MessagePage')['json']['items']
|
||||
check(any(m == m1 for m in hist), 'message with attachments not in history')
|
||||
# Bob (участник) прикрепляет вложение Alice — допустимо.
|
||||
msg({'text': 'и я', 'attachment_ids': [a_png['id']]}, 201, actor=bob)
|
||||
|
||||
for row in results:
|
||||
print('%-42s %-28s %9d -> %d' % row)
|
||||
print('PASS: attachment negative suite (%d upload cases, no 5xx)' % len(results))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,282 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Операционные сценарии вложений на Docker-стенде (уровни 3–4).
|
||||
|
||||
failover upload → остановить обслужившую реплику → download через другую
|
||||
s3-outage остановить S3: загрузка/скачивание 503, текстовый чат и readiness работают
|
||||
interrupt обрыв клиента посреди тела: ни ready-вложения, ни намерения, ни объекта
|
||||
db-gap PUT в S3 прошёл, PostgreSQL недоступен на MarkReady: объект удалён
|
||||
компенсацией, намерение осталось → убирает reconciler
|
||||
security bucket приватен (анонимно 403), у API-ключа нет прав вне bucket,
|
||||
bootstrap идемпотентен, консоль/порты S3 не опубликованы
|
||||
memory N одновременных загрузок ~9.8 MiB: пик памяти (cgroup memory.peak) реплик
|
||||
|
||||
Каждый сценарий печатает JSON-итог и PASS/FAIL.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from labutil import (BUCKET, api_container, bucket_count, compose, fixture, mc, noise_png, object_key, psql,
|
||||
raw_post, sh, wait_status)
|
||||
from client import Client, Failure, arguments, check, run
|
||||
|
||||
|
||||
def upload(c, actor, chat, data, name='f.png', ctype='image/png', expected=202):
|
||||
return c.call('POST', '/api/v1/chats/%s/attachments?filename=%s' % (chat['id'], name), expected,
|
||||
actor=actor, raw=data, headers={'Content-Type': ctype},
|
||||
schema='Attachment' if expected == 202 else None)
|
||||
|
||||
|
||||
def wait_ready(c, timeout=90):
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
try:
|
||||
c.call('GET', '/health/ready')
|
||||
return
|
||||
except Failure:
|
||||
time.sleep(1)
|
||||
raise Failure('stack not ready')
|
||||
|
||||
|
||||
def scenario_failover(c):
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
data = noise_png(2 * 1024 * 1024)
|
||||
r = upload(c, alice, chat, data)
|
||||
att, served_by = r['json'], r['headers']['X-Instance-Id']
|
||||
wait_status(c, bob, att['id'], ('ready',))
|
||||
cid = api_container(served_by)
|
||||
sh('docker', 'stop', '-t', '15', cid)
|
||||
try:
|
||||
seen = set()
|
||||
for _ in range(6):
|
||||
d = c.call('GET', '/api/v1/attachments/%s/content' % att['id'], actor=bob)
|
||||
check(d['bytes'] == data, 'downloaded bytes differ after failover')
|
||||
seen.add(d['headers']['X-Instance-Id'])
|
||||
check(served_by not in seen, 'stopped replica still serving')
|
||||
finally:
|
||||
sh('docker', 'start', cid)
|
||||
sh('sh', 'scripts/restore.sh')
|
||||
return {'uploaded_by': served_by, 'downloaded_by': sorted(seen), 'sha256': hashlib.sha256(data).hexdigest(),
|
||||
'stopped_container': cid[:12]}
|
||||
|
||||
|
||||
def scenario_s3_outage(c):
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
small = fixture('small.png')
|
||||
att = upload(c, alice, chat, small)['json']
|
||||
wait_status(c, bob, att['id'], ('ready',))
|
||||
compose('stop', 's3')
|
||||
try:
|
||||
t0 = time.time()
|
||||
up = upload(c, alice, chat, small, expected=503)
|
||||
up_s = time.time() - t0
|
||||
c.call('GET', '/api/v1/attachments/%s/content' % att['id'], 503, actor=bob)
|
||||
meta = c.call('GET', '/api/v1/attachments/%s' % att['id'], actor=bob, schema='Attachment')['json']
|
||||
msg = c.message(alice, chat, 'S3 лежит, а чат работает')['json']
|
||||
c.call('GET', '/health/ready', schema='Health')
|
||||
leftovers = psql("SELECT count(*) FROM attachments WHERE chat_id = '%s' AND status = 'uploading'" % chat['id'])
|
||||
finally:
|
||||
compose('start', 's3')
|
||||
compose('run', '--rm', 's3-init')
|
||||
for _ in range(30):
|
||||
try:
|
||||
again = upload(c, alice, chat, small)['json']
|
||||
break
|
||||
except Failure:
|
||||
time.sleep(1)
|
||||
else:
|
||||
raise Failure('upload did not recover after S3 start')
|
||||
d = c.call('GET', '/api/v1/attachments/%s/content' % att['id'], actor=bob)
|
||||
check(d['bytes'] == small, 'old attachment changed after S3 restart')
|
||||
check(leftovers == '0', 'intent rows left after failed upload: ' + leftovers)
|
||||
return {'upload_status_during_outage': up['status'], 'upload_error_seconds': round(up_s, 2),
|
||||
'download_status_during_outage': 503, 'metadata_during_outage': meta['status'],
|
||||
'text_message_during_outage': 201, 'readiness_during_outage': 200,
|
||||
'intents_left': int(leftovers), 'upload_after_recovery': again['status']}
|
||||
|
||||
|
||||
def scenario_interrupt(c):
|
||||
alice, _, _, chat = c.bootstrap()
|
||||
data = noise_png(4 * 1024 * 1024)
|
||||
hdr = {'Authorization': 'Bearer ' + alice['token'], 'Content-Type': 'image/png',
|
||||
'Content-Length': str(len(data))}
|
||||
# Отправляем 1 MiB из 4 и обрываем соединение.
|
||||
import socket
|
||||
from urllib.parse import urlsplit
|
||||
u = urlsplit(c.base)
|
||||
s = socket.create_connection((u.hostname, u.port or 80))
|
||||
head = 'POST /api/v1/chats/%s/attachments?filename=cut.png HTTP/1.1\r\nHost: %s\r\n' % (chat['id'], u.netloc)
|
||||
s.sendall((head + ''.join('%s: %s\r\n' % kv for kv in hdr.items()) + '\r\n').encode())
|
||||
s.sendall(data[:1024 * 1024])
|
||||
time.sleep(1)
|
||||
s.close()
|
||||
time.sleep(3)
|
||||
rows = psql("SELECT status FROM attachments WHERE chat_id = '%s'" % chat['id'])
|
||||
objs = str(sum(bucket_count(p + chat['id'] + '/') for p in ('s/', 'o/', 'v/')))
|
||||
check(rows == '', 'rows left after interrupted upload: %r' % rows)
|
||||
check(objs == '0', 'objects left after interrupted upload: ' + objs)
|
||||
return {'sent_bytes': 1024 * 1024, 'declared_bytes': len(data), 'rows_after': 0, 'objects_after': 0}
|
||||
|
||||
|
||||
def scenario_db_gap(c):
|
||||
"""PUT прошёл, а PostgreSQL «пропал» до MarkReady (docker pause)."""
|
||||
alice, _, _, chat = c.bootstrap()
|
||||
data = noise_png(3 * 1024 * 1024)
|
||||
hdr = {'Authorization': 'Bearer ' + alice['token'], 'Content-Type': 'image/png', 'Content-Length': str(len(data))}
|
||||
state = {}
|
||||
|
||||
def body():
|
||||
yield data[:512 * 1024] # намерение уже записано, PUT идёт
|
||||
time.sleep(2)
|
||||
compose('pause', 'postgres') # БД «пропала» до MarkReady
|
||||
state['paused_at'] = time.time()
|
||||
yield data[512 * 1024:]
|
||||
t0 = time.time()
|
||||
try:
|
||||
st, _ = raw_post(c.base, '/api/v1/chats/%s/attachments?filename=gap.png' % chat['id'], hdr, body(), read_timeout=60)
|
||||
finally:
|
||||
# Дольше таймаута запроса (30 s) и компенсации (10 s): DeleteIntent тоже не пройдёт.
|
||||
time.sleep(max(0, 45 - (time.time() - state.get('paused_at', time.time()))))
|
||||
compose('unpause', 'postgres')
|
||||
wait_ready(c)
|
||||
time.sleep(3) # отложенный UPDATE (если был) успевает закоммититься после unpause
|
||||
rows = psql("SELECT id || ' ' || status FROM attachments WHERE chat_id = '%s'" % chat['id'])
|
||||
staged = bucket_count('s/' + chat['id'] + '/')
|
||||
status_after = rows.split()[-1] if rows else 'none'
|
||||
check(st != 202, 'upload must not report success when the job was not committed (got %s)' % st)
|
||||
# Инвариант: нет строки queued/ready без исходника.
|
||||
check(not (status_after in ('queued', 'processing') and staged == 0 and bucket_count('o/' + chat['id'] + '/') == 0),
|
||||
'job without source: %r' % rows)
|
||||
if status_after in ('queued', 'processing', 'ready'):
|
||||
# COMMIT всё-таки прошёл: pipeline доводит работу до ready.
|
||||
aid = rows.split()[0]
|
||||
for _ in range(120):
|
||||
if psql("SELECT status FROM attachments WHERE id='%s'" % aid) == 'ready':
|
||||
break
|
||||
time.sleep(1)
|
||||
else:
|
||||
psql("UPDATE attachments SET updated_at = now() - interval '30 minutes' WHERE chat_id = '%s'" % chat['id'])
|
||||
for _ in range(10):
|
||||
r = compose('run', '--rm', '--no-deps', '-T', '--entrypoint', '/app/reconcile', 'reconciler',
|
||||
'--apply', '--grace', '10m', check=False)
|
||||
if r.returncode != 3:
|
||||
break
|
||||
time.sleep(2)
|
||||
check(r.returncode in (0, 4), 'reconcile failed: ' + r.stderr[-300:])
|
||||
final = psql("SELECT status FROM attachments WHERE chat_id = '%s'" % chat['id'])
|
||||
check(final in ('ready', ''), 'inconsistent final state: %r' % final)
|
||||
return {'client_status': st, 'seconds': round(time.time() - t0, 1),
|
||||
'after_gap': {'row_status': status_after, 'staging_objects': staged},
|
||||
'final': {'row_status': final or 'none'}}
|
||||
|
||||
|
||||
def scenario_security(c):
|
||||
alice, _, _, chat = c.bootstrap()
|
||||
att = upload(c, alice, chat, fixture('small.png'))['json']
|
||||
key = object_key(att['id'])
|
||||
url = 'http://s3:9000/%s/%s' % (BUCKET, key)
|
||||
# Анонимно изнутри сети стенда (из контейнера API): объект и листинг закрыты.
|
||||
anon_get = compose('exec', '-T', 'api', 'wget', '-q', '-S', '-O', '/dev/null', url, check=False)
|
||||
anon_list = compose('exec', '-T', 'api', 'wget', '-q', '-S', '-O', '/dev/null',
|
||||
'http://s3:9000/%s?list-type=2' % BUCKET, check=False)
|
||||
check(anon_get.returncode != 0 and '403' in anon_get.stderr, 'anonymous GET must be 403')
|
||||
check(anon_list.returncode != 0 and '403' in anon_list.stderr, 'anonymous LIST must be 403')
|
||||
# Ключ API: свой bucket — да, остальное — нет.
|
||||
own = mc('mc stat s3/%s/%s >/dev/null && echo ok' % (BUCKET, key), as_user='api').stdout.strip()
|
||||
mb = mc('mc mb s3/evil-bucket-%s' % uuid.uuid4().hex[:6], check=False, as_user='api')
|
||||
admin = mc('mc admin user list s3', check=False, as_user='api')
|
||||
buckets = mc('mc ls s3', check=False, as_user='api')
|
||||
check(own == 'ok', 'api key cannot read own bucket')
|
||||
check(mb.returncode != 0, 'api key must not create buckets')
|
||||
check(admin.returncode != 0, 'api key must not use admin API')
|
||||
check(buckets.returncode != 0 or 'evil' not in buckets.stdout, 'api key sees a bucket it created?!')
|
||||
# Bootstrap идемпотентен: повторный запуск успешен, объект на месте.
|
||||
before = mc('mc ls --recursive s3/%s | wc -l' % BUCKET).stdout.strip()
|
||||
r1 = compose('run', '--rm', 's3-init')
|
||||
r2 = compose('run', '--rm', 's3-init')
|
||||
after = mc('mc ls --recursive s3/%s | wc -l' % BUCKET).stdout.strip()
|
||||
check(before == after, 'bootstrap changed objects')
|
||||
ports = compose('ps', 's3', '--format', '{{.Ports}}').stdout.strip()
|
||||
check('0.0.0.0' not in ports and '127.0.0.1' not in ports, 's3 port is published: ' + ports)
|
||||
return {'anonymous_get': '403', 'anonymous_list': '403', 'api_key_own_bucket': 'allowed',
|
||||
'api_key_make_bucket': 'denied', 'api_key_admin': 'denied',
|
||||
'api_key_visible_buckets': sorted(l.split()[-1].rstrip('/') for l in buckets.stdout.splitlines() if l.strip())
|
||||
if buckets.returncode == 0 else 'denied',
|
||||
'bootstrap_runs': [r1.returncode, r2.returncode], 'objects_before_after': [int(before), int(after)],
|
||||
's3_published_ports': ports or 'none'}
|
||||
|
||||
|
||||
def read_peak(cid):
|
||||
r = sh('docker', 'exec', cid, 'cat', '/sys/fs/cgroup/memory.peak', check=False)
|
||||
return int(r.stdout.strip()) if r.returncode == 0 and r.stdout.strip().isdigit() else None
|
||||
|
||||
|
||||
def read_current(cid):
|
||||
r = sh('docker', 'exec', cid, 'cat', '/sys/fs/cgroup/memory.current', check=False)
|
||||
return int(r.stdout.strip()) if r.returncode == 0 and r.stdout.strip().isdigit() else None
|
||||
|
||||
|
||||
def scenario_memory(c, parallel_levels=(10, 20)):
|
||||
alice, _, _, chat = c.bootstrap()
|
||||
data = noise_png(10 * 1024 * 1024 - 300_000)
|
||||
out = {'file_bytes': len(data), 'runs': []}
|
||||
for n in parallel_levels:
|
||||
compose('restart', 'api') # новый cgroup → memory.peak с нуля
|
||||
sh('sh', 'scripts/restore.sh')
|
||||
wait_ready(c)
|
||||
cids = compose('ps', '-q', 'api').stdout.split()
|
||||
upload(c, alice, chat, fixture('small.png')) # прогрев пулов/соединений
|
||||
base = {cid[:12]: read_peak(cid) for cid in cids}
|
||||
barrier = threading.Barrier(n)
|
||||
res = []
|
||||
|
||||
def worker():
|
||||
local = Client(c.base, timeout=60)
|
||||
barrier.wait()
|
||||
t0 = time.time()
|
||||
try:
|
||||
upload(local, alice, chat, data, name='mem.png')
|
||||
res.append(('ok', time.time() - t0))
|
||||
except Failure as e:
|
||||
res.append(('fail:' + str(e)[:60], time.time() - t0))
|
||||
ths = [threading.Thread(target=worker) for _ in range(n)]
|
||||
for t in ths:
|
||||
t.start()
|
||||
for t in ths:
|
||||
t.join()
|
||||
peak = {cid[:12]: read_peak(cid) for cid in cids}
|
||||
ok = sum(1 for r in res if r[0] == 'ok')
|
||||
mib = lambda v: round(v / 1048576, 1) if v else None
|
||||
run = {'parallel': n, 'ok': ok, 'failed': [r[0] for r in res if r[0] != 'ok'],
|
||||
'max_seconds': round(max(r[1] for r in res), 2),
|
||||
'baseline_peak_mib': {k: mib(v) for k, v in base.items()},
|
||||
'peak_mib': {k: mib(v) for k, v in peak.items()},
|
||||
'payload_total_mib': round(n * len(data) / 1048576, 1)}
|
||||
growth = [peak[k] - base[k] for k in peak if peak[k] and base[k]]
|
||||
run['max_peak_growth_mib'] = mib(max(growth)) if growth else None
|
||||
out['runs'].append(run)
|
||||
check(ok == n, '%d of %d concurrent uploads failed: %s' % (n - ok, n, run['failed'][:3]))
|
||||
return out
|
||||
|
||||
|
||||
SCENARIOS = {'failover': scenario_failover, 's3-outage': scenario_s3_outage, 'interrupt': scenario_interrupt,
|
||||
'db-gap': scenario_db_gap, 'security': scenario_security, 'memory': scenario_memory}
|
||||
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument('scenario', choices=sorted(SCENARIOS))
|
||||
p.add_argument('--output', default=None)
|
||||
args = arguments('Docker-level attachment scenarios (lab4)', configure)
|
||||
c = Client(args.base_url, args.ca_file, timeout=60)
|
||||
result = SCENARIOS[args.scenario](c)
|
||||
text = json.dumps({'scenario': args.scenario, 'result': result}, ensure_ascii=False, indent=2)
|
||||
if args.output:
|
||||
open(args.output, 'w', encoding='utf-8').write(text + '\n')
|
||||
print(text)
|
||||
print('PASS: ' + args.scenario)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,174 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Серия отказов под нагрузкой (уровень 4): поочерёдно останавливает КАЖДУЮ
|
||||
API-реплику (docker stop → SIGTERM → drain), восстанавливает её и переходит
|
||||
к следующей. Во время всей серии идёт closed-loop нагрузка через LB:
|
||||
POST сообщения (при ошибке повтор с тем же Idempotency-Key) и GET истории.
|
||||
|
||||
Измеряется на каждую реплику: RPS до/во время/после, число ошибок, время от
|
||||
начала остановки до последней ошибки (recovery), время до исчезновения реплики
|
||||
из ответов LB и время восстановления реплики после docker start.
|
||||
В конце проверяется: все подтверждённые сообщения на месте, дублей нет.
|
||||
|
||||
Скрипт сам вызывает docker CLI (это не публичный тест), запускать из корня репозитория.
|
||||
"""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
import sys
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests')) # публичный client.py
|
||||
from client import Client, Failure, arguments, check, run
|
||||
from resilience import history
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def docker(*args):
|
||||
return subprocess.run(['docker', *args], cwd=ROOT, check=True, capture_output=True, text=True).stdout.strip()
|
||||
|
||||
|
||||
def api_containers():
|
||||
return docker('compose', 'ps', '-q', 'api').split()
|
||||
|
||||
|
||||
def health(cid):
|
||||
return docker('inspect', '-f', '{{.State.Health.Status}}', cid)
|
||||
|
||||
|
||||
class Load:
|
||||
def __init__(self, args, actor, reader, chat, concurrency):
|
||||
self.args, self.actor, self.reader, self.chat = args, actor, reader, chat
|
||||
self.concurrency = concurrency
|
||||
self.events = [] # (t, kind, ok, instance)
|
||||
self.confirmed = [] # подтверждённые Message
|
||||
self.lock = threading.Lock()
|
||||
self.stop = threading.Event()
|
||||
|
||||
def record(self, kind, ok, instance=None):
|
||||
with self.lock:
|
||||
self.events.append((time.monotonic(), kind, ok, instance))
|
||||
|
||||
def worker(self, n):
|
||||
c = Client(self.args.base_url, self.args.ca_file, timeout=3)
|
||||
path = '/api/v1/chats/' + self.chat['id'] + '/messages?limit=20'
|
||||
key, text, i = None, None, 0
|
||||
while not self.stop.is_set():
|
||||
if key is None:
|
||||
key = uuid.uuid4().hex
|
||||
text = 'series-%d-%d-%s' % (n, i, key)
|
||||
i += 1
|
||||
try:
|
||||
r = c.message(self.actor, self.chat, text, key=key)
|
||||
self.record('write', True, r['headers'].get('X-Instance-Id'))
|
||||
with self.lock:
|
||||
self.confirmed.append(r['json'])
|
||||
key = None
|
||||
except Failure:
|
||||
self.record('write', False) # неопределённый результат: тот же ключ
|
||||
try:
|
||||
r = c.call('GET', path, actor=self.reader, schema='MessagePage')
|
||||
self.record('read', True, r['headers'].get('X-Instance-Id'))
|
||||
except Failure:
|
||||
self.record('read', False)
|
||||
|
||||
def __enter__(self):
|
||||
self.pool = ThreadPoolExecutor(max_workers=self.concurrency)
|
||||
self.futures = [self.pool.submit(self.worker, n) for n in range(self.concurrency)]
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
self.stop.set()
|
||||
for f in self.futures:
|
||||
f.result()
|
||||
self.pool.shutdown()
|
||||
|
||||
def window(self, a, b):
|
||||
with self.lock:
|
||||
ev = [e for e in self.events if a <= e[0] < b]
|
||||
ok = sum(1 for e in ev if e[2])
|
||||
return {'seconds': round(b - a, 2), 'ok': ok, 'errors': len(ev) - ok,
|
||||
'ok_rps': round(ok / (b - a), 1) if b > a else None}
|
||||
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument('--concurrency', type=int, default=4)
|
||||
p.add_argument('--warmup', type=float, default=5)
|
||||
p.add_argument('--observe', type=float, default=15)
|
||||
p.add_argument('--output', default=None)
|
||||
args = arguments('Stop each API replica in turn under load; collect RPS/errors/recovery', configure)
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
replicas = api_containers()
|
||||
check(len(replicas) >= 2, 'need at least 2 api containers')
|
||||
results = []
|
||||
with Load(args, alice, bob, chat, args.concurrency) as load:
|
||||
time.sleep(args.warmup)
|
||||
for cid in replicas:
|
||||
target = cid[:12]
|
||||
before_start = time.monotonic() - args.warmup
|
||||
t0 = time.monotonic()
|
||||
docker('stop', '-t', '15', cid)
|
||||
stop_seconds = time.monotonic() - t0
|
||||
time.sleep(max(0.0, args.observe - stop_seconds))
|
||||
t_end = time.monotonic()
|
||||
with load.lock:
|
||||
after = [e for e in load.events if e[0] >= t0]
|
||||
errs = [e[0] for e in after if not e[2]]
|
||||
served = [e[0] for e in after if e[2] and e[3] == target]
|
||||
row = {
|
||||
'target_instance': target,
|
||||
'docker_stop_seconds': round(stop_seconds, 2),
|
||||
'before': load.window(before_start, t0),
|
||||
'during_stop_and_observe': load.window(t0, t_end),
|
||||
'errors_after_stop': len(errs),
|
||||
'recovery_seconds': round(max(errs) - t0, 2) if errs else 0.0,
|
||||
'target_last_served_after_stop_seconds': round(max(served) - t0, 2) if served else None,
|
||||
'other_instances_after': sorted({e[3] for e in after if e[2] and e[3] != target}),
|
||||
}
|
||||
# Восстановление реплики и её возврат в балансировку.
|
||||
r0 = time.monotonic()
|
||||
docker('start', cid)
|
||||
while health(cid) != 'healthy':
|
||||
check(time.monotonic() - r0 < 60, 'replica did not become healthy')
|
||||
time.sleep(0.5)
|
||||
healthy_at = time.monotonic() - r0
|
||||
while True:
|
||||
with load.lock:
|
||||
seen = any(e[0] > r0 and e[2] and e[3] == target for e in load.events)
|
||||
if seen:
|
||||
break
|
||||
check(time.monotonic() - r0 < 60, 'replica not seen behind LB after restore')
|
||||
time.sleep(0.2)
|
||||
row['restore_healthy_seconds'] = round(healthy_at, 2)
|
||||
row['restore_serving_via_lb_seconds'] = round(time.monotonic() - r0, 2)
|
||||
results.append(row)
|
||||
print(json.dumps(row, ensure_ascii=False))
|
||||
time.sleep(3)
|
||||
total = load.window(load.events[0][0], time.monotonic())
|
||||
confirmed = list(load.confirmed)
|
||||
|
||||
messages = history(c, bob, chat)
|
||||
ids = [m['id'] for m in messages]
|
||||
texts = [m['text'] for m in messages]
|
||||
check(len(ids) == len(set(ids)), 'duplicated message IDs')
|
||||
check(len(texts) == len(set(texts)), 'retry with same key created a duplicate')
|
||||
by_id = {m['id']: m for m in messages}
|
||||
lost = [m for m in confirmed if by_id.get(m['id']) != m]
|
||||
check(not lost, '%d confirmed messages lost/changed' % len(lost))
|
||||
summary = {'concurrency': args.concurrency, 'replicas': len(replicas), 'total': total,
|
||||
'confirmed_writes': len(confirmed), 'stored_messages': len(messages),
|
||||
'duplicates': 0, 'lost_confirmed': 0, 'per_replica': results}
|
||||
text = json.dumps(summary, ensure_ascii=False, indent=2)
|
||||
if args.output:
|
||||
Path(args.output).write_text(text + '\n', encoding='utf-8')
|
||||
print(text)
|
||||
print('PASS: every replica stopped and restored under load; no lost or duplicated messages.')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 900 B |
Binary file not shown.
|
After Width: | Height: | Size: 106 B |
@@ -0,0 +1,47 @@
|
||||
// Command genfixtures пишет маленькие синтетические изображения для собственных
|
||||
// тестов (student-tests/fixtures). Большие и вредоносные файлы тесты генерируют
|
||||
// сами в памяти — в Git они не хранятся.
|
||||
//
|
||||
// go run ./student-tests/genfixtures
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
func img(w, h int) *image.RGBA {
|
||||
m := image.NewRGBA(image.Rect(0, 0, w, h))
|
||||
for y := 0; y < h; y++ {
|
||||
for x := 0; x < w; x++ {
|
||||
m.Set(x, y, color.RGBA{uint8(x * 4), uint8(y * 4), 128, 255})
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func main() {
|
||||
dir := filepath.Join("student-tests", "fixtures")
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
var j bytes.Buffer
|
||||
if err := jpeg.Encode(&j, img(64, 48), &jpeg.Options{Quality: 85}); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
var p bytes.Buffer
|
||||
if err := png.Encode(&p, img(40, 30)); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
for name, data := range map[string][]byte{"small.jpg": j.Bytes(), "small.png": p.Bytes()} {
|
||||
if err := os.WriteFile(filepath.Join(dir, name), data, 0o644); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Конкурентный повтор POST сообщения с одним Idempotency-Key через LB (lab3).
|
||||
|
||||
Каждый раунд: N потоков (каждый со своим соединением) по барьеру одновременно
|
||||
отправляют одинаковый body с одинаковым ключом. Ожидаем: все ответы 201 с одним
|
||||
и тем же Message, запросы обслужены ≥2 репликами, в истории ровно одно сообщение.
|
||||
Затем тот же ключ с другим body — 409; тот же ключ в другом чате — новое сообщение.
|
||||
"""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import threading
|
||||
import uuid
|
||||
import sys
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests')) # публичный client.py
|
||||
from client import Client, Failure, arguments, check, run
|
||||
from resilience import history
|
||||
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument('--rounds', type=int, default=10)
|
||||
p.add_argument('--parallel', type=int, default=16)
|
||||
p.add_argument('--output', default=None)
|
||||
args = arguments('Concurrent Idempotency-Key replay across replicas', configure)
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
other = c.call('POST', '/api/v1/chats', 201, actor=alice,
|
||||
body={'title': 'Второй чат', 'member_ids': [alice['id'], bob['id']]}, schema='Chat')['json']
|
||||
|
||||
rounds = []
|
||||
all_instances = set()
|
||||
for r in range(args.rounds):
|
||||
key = 'conc-' + uuid.uuid4().hex
|
||||
text = 'Конкурентный повтор %d %s' % (r, key)
|
||||
barrier = threading.Barrier(args.parallel)
|
||||
|
||||
def worker(_):
|
||||
local = Client(args.base_url, args.ca_file, timeout=10)
|
||||
barrier.wait()
|
||||
try:
|
||||
resp = local.message(alice, chat, text, key=key)
|
||||
return resp['status'], resp['json'], resp['headers'].get('X-Instance-Id')
|
||||
except Failure as exc:
|
||||
return 'fail', str(exc), None
|
||||
|
||||
with ThreadPoolExecutor(max_workers=args.parallel) as pool:
|
||||
results = list(pool.map(worker, range(args.parallel)))
|
||||
statuses = [s for s, _, _ in results]
|
||||
check(all(s == 201 for s in statuses), 'round %d: not all 201: %s' % (r, statuses))
|
||||
bodies = {json.dumps(b, sort_keys=True) for _, b, _ in results}
|
||||
check(len(bodies) == 1, 'round %d: replays returned different messages' % r)
|
||||
instances = {i for _, _, i in results}
|
||||
all_instances |= instances
|
||||
stored = [m for m in history(c, bob, chat) if m['text'] == text]
|
||||
check(len(stored) == 1, 'round %d: %d messages stored for one key' % (r, len(stored)))
|
||||
# Другой body с тем же ключом — 409, не новое сообщение.
|
||||
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=alice,
|
||||
body={'text': text + ' (изменён)'}, headers={'Idempotency-Key': key})
|
||||
rounds.append({'round': r, 'requests': args.parallel, 'status_201': statuses.count(201),
|
||||
'distinct_messages': len(bodies), 'stored': len(stored), 'instances': len(instances)})
|
||||
|
||||
# Ключ уникален в пределах чата: тот же ключ в другом чате создаёт своё сообщение.
|
||||
key = 'scope-' + uuid.uuid4().hex
|
||||
a = c.message(alice, chat, 'scope', key=key)['json']
|
||||
b = c.message(alice, other, 'scope', key=key)['json']
|
||||
check(a['id'] != b['id'], 'key leaked across chats')
|
||||
# Другой пользователь с тем же ключом — тоже независим.
|
||||
d = c.message(bob, chat, 'scope', key=key)['json']
|
||||
check(d['id'] != a['id'], 'key leaked across users')
|
||||
# Без ключа и с неверным ключом — 400.
|
||||
path = '/api/v1/chats/' + chat['id'] + '/messages'
|
||||
c.call('POST', path, 400, actor=alice, body={'text': 'x'})
|
||||
c.call('POST', path, 400, actor=alice, body={'text': 'x'}, headers={'Idempotency-Key': 'bad key!'})
|
||||
c.call('POST', path, 400, actor=alice, body={'text': 'x'}, headers={'Idempotency-Key': 'k' * 129})
|
||||
# Повтор проверяет доступ: посторонний с тем же ключом получает 404.
|
||||
c.call('POST', path, 404, actor=eve, body={'text': 'scope'}, headers={'Idempotency-Key': key})
|
||||
|
||||
check(len(all_instances) >= 2, 'concurrent requests were served by fewer than 2 replicas')
|
||||
summary = {'rounds': args.rounds, 'parallel_per_round': args.parallel,
|
||||
'distinct_instances_seen': len(all_instances),
|
||||
'duplicates_found': sum(x['stored'] - 1 for x in rounds), 'per_round': rounds}
|
||||
text = json.dumps(summary, ensure_ascii=False, indent=2)
|
||||
if args.output:
|
||||
with open(args.output, 'w', encoding='utf-8') as f:
|
||||
f.write(text + '\n')
|
||||
print(text)
|
||||
print('PASS: concurrent Idempotency-Key replay produced exactly one message per key.')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,156 @@
|
||||
"""Общие помощники собственных тестов lab4: изображения, docker compose, psql, mc.
|
||||
|
||||
Только stdlib. Секреты не печатаются: mc получает их внутри контейнера из /run/secrets.
|
||||
"""
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests')) # публичный client.py
|
||||
FIXTURES = Path(__file__).resolve().parent / 'fixtures'
|
||||
BUCKET = 'messenger-attachments'
|
||||
|
||||
|
||||
def chunk(typ, data):
|
||||
return struct.pack('>I', len(data)) + typ + data + struct.pack('>I', zlib.crc32(typ + data) & 0xffffffff)
|
||||
|
||||
|
||||
def png(w, h, raw=None, color_type=2, interlace=0, level=6):
|
||||
"""PNG из сырых строк; по умолчанию RGB 8 bit, все пиксели чёрные."""
|
||||
if raw is None:
|
||||
raw = (b'\x00' + b'\x00' * (w * 3)) * h
|
||||
ihdr = struct.pack('>IIBBBBB', w, h, 8, color_type, 0, 0, interlace)
|
||||
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(target_bytes):
|
||||
"""Почти несжимаемый PNG размером около target_bytes (шум из детерминированного PRNG)."""
|
||||
w = 1024
|
||||
h = max(1, target_bytes // (w * 3 + 1))
|
||||
seed = 0x2545F491
|
||||
rows = bytearray()
|
||||
for _ in range(h):
|
||||
rows.append(0)
|
||||
row = bytearray(w * 3)
|
||||
for i in range(0, w * 3, 4):
|
||||
seed = (seed * 1103515245 + 12345) & 0xffffffff
|
||||
row[i:i + 4] = seed.to_bytes(4, 'little')[:len(row) - i]
|
||||
rows += row
|
||||
return png(w, h, bytes(rows), level=1)
|
||||
|
||||
|
||||
def bomb_png(w=100_000, h=100_000):
|
||||
"""Маленький файл, огромные размеры в IHDR."""
|
||||
return png(w, h, raw=b'\x00')
|
||||
|
||||
|
||||
def raw_post(base_url, path, headers, body_iter, read_timeout=30):
|
||||
"""POST на сыром сокете: тело отправляется в фоне, ответ читается параллельно.
|
||||
|
||||
Нужен, когда сервер отвечает (413) до чтения тела и закрывает соединение:
|
||||
urllib в этом случае падает на отправке, не увидев ответа.
|
||||
Возвращает (status, body_bytes) или (None, b'') если ответа не было.
|
||||
"""
|
||||
import socket
|
||||
import threading
|
||||
from urllib.parse import urlsplit
|
||||
u = urlsplit(base_url)
|
||||
s = socket.create_connection((u.hostname, u.port or 80), timeout=read_timeout)
|
||||
head = 'POST %s HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n' % (path, u.netloc)
|
||||
head += ''.join('%s: %s\r\n' % kv for kv in headers.items()) + '\r\n'
|
||||
s.sendall(head.encode())
|
||||
|
||||
def send():
|
||||
try:
|
||||
for part in body_iter:
|
||||
s.sendall(part)
|
||||
except OSError:
|
||||
pass # сервер уже ответил и закрыл соединение — ожидаемо
|
||||
t = threading.Thread(target=send, daemon=True)
|
||||
t.start()
|
||||
data = b''
|
||||
try:
|
||||
while True:
|
||||
b = s.recv(65536)
|
||||
if not b:
|
||||
break
|
||||
data += b
|
||||
if b'\r\n\r\n' in data and len(data) > 4096:
|
||||
break
|
||||
except OSError:
|
||||
pass
|
||||
finally:
|
||||
s.close()
|
||||
if not data.startswith(b'HTTP/1.'):
|
||||
return None, b''
|
||||
status = int(data.split(b' ', 2)[1])
|
||||
return status, data.split(b'\r\n\r\n', 1)[-1]
|
||||
|
||||
|
||||
def fixture(name):
|
||||
return (FIXTURES / name).read_bytes()
|
||||
|
||||
|
||||
def sh(*args, check=True, timeout=300, input=None, env=None):
|
||||
full_env = None
|
||||
if env:
|
||||
import os
|
||||
full_env = dict(os.environ, **env)
|
||||
r = subprocess.run(list(args), cwd=ROOT, capture_output=True, text=True, timeout=timeout, input=input, env=full_env)
|
||||
if check and r.returncode != 0:
|
||||
raise RuntimeError('%s failed (%d): %s' % (' '.join(args[:4]), r.returncode, (r.stderr or r.stdout)[-800:]))
|
||||
return r
|
||||
|
||||
|
||||
def compose(*args, **kw):
|
||||
return sh('docker', 'compose', *args, **kw)
|
||||
|
||||
|
||||
def psql(sql):
|
||||
"""Одно значение/таблица из PostgreSQL стенда (через docker compose exec)."""
|
||||
return compose('exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger',
|
||||
'-v', 'ON_ERROR_STOP=1', '-tAc', sql).stdout.strip()
|
||||
|
||||
|
||||
def mc(script, check=True, as_user='root'):
|
||||
"""Скрипт mc в одноразовом контейнере s3-init. Алиас `s3` — root или API-пользователь."""
|
||||
creds = {'root': ('s3_root_user', 's3_root_password'),
|
||||
'api': ('s3_access_key_id', 's3_secret_access_key')}[as_user]
|
||||
prelude = ('mc alias set s3 http://s3:9000 "$(cat /run/secrets/%s)" "$(cat /run/secrets/%s)" >/dev/null; '
|
||||
% creds)
|
||||
return compose('run', '--rm', '--no-deps', '-T', '--entrypoint', 'sh', 's3-init', '-c', prelude + script,
|
||||
check=check)
|
||||
|
||||
|
||||
def api_container(instance_id):
|
||||
for cid in compose('ps', '-q', 'api').stdout.split():
|
||||
if cid.startswith(instance_id):
|
||||
return cid
|
||||
raise RuntimeError('no api container for ' + instance_id)
|
||||
|
||||
|
||||
def object_key(attachment_id):
|
||||
return psql("SELECT object_key FROM attachments WHERE id = '%s'" % attachment_id)
|
||||
|
||||
|
||||
def wait_status(c, actor, att_id, statuses=('ready',), timeout=90):
|
||||
"""Опрос GET метаданных до одного из статусов; возвращает метаданные."""
|
||||
import time
|
||||
from client import Failure
|
||||
end = time.time() + timeout
|
||||
last = None
|
||||
while time.time() < end:
|
||||
last = c.call('GET', '/api/v1/attachments/' + att_id, actor=actor, schema='Attachment')['json']
|
||||
if last['status'] in statuses:
|
||||
return last
|
||||
time.sleep(0.5)
|
||||
raise Failure('attachment %s did not reach %s, last=%s' % (att_id, statuses, last and last['status']))
|
||||
|
||||
|
||||
def bucket_count(prefix):
|
||||
"""Число объектов под префиксом bucket (s/, o/, v/, a/ + chat)."""
|
||||
return int(mc('mc ls --recursive s3/%s/%s 2>/dev/null | wc -l' % (BUCKET, prefix)).stdout.strip() or 0)
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Closed-loop генератор POST сообщений с записью каждого запроса.
|
||||
|
||||
В отличие от tests/load.py, сохраняет для каждого запроса X-Request-Id, время начала,
|
||||
длительность и исход — чтобы потом проверить, попала ли именно эта трасса в Tempo
|
||||
(трек 1: какие ошибки и медленные запросы теряет sampling). Токены не сохраняются.
|
||||
"""
|
||||
import math
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
from client import Client, Failure
|
||||
|
||||
|
||||
class Load:
|
||||
def __init__(self, base_url, ca_file, actor, chat, concurrency=4, timeout=10, prefix='load'):
|
||||
self.base_url, self.ca_file = base_url, ca_file
|
||||
self.actor, self.chat = actor, chat
|
||||
self.concurrency, self.timeout, self.prefix = concurrency, timeout, prefix
|
||||
self.records = [] # (rid, t_start_epoch, seconds, status) status: int или 'error'
|
||||
self._lock = threading.Lock()
|
||||
self._stop = threading.Event()
|
||||
self._pool = None
|
||||
self._futures = []
|
||||
|
||||
def _worker(self, wid):
|
||||
c = Client(self.base_url, self.ca_file, timeout=self.timeout)
|
||||
i = 0
|
||||
while not self._stop.is_set():
|
||||
rid = '%s-%s' % (self.prefix, uuid.uuid4().hex[:20])
|
||||
t0, m0 = time.time(), time.monotonic()
|
||||
status = 'error'
|
||||
try:
|
||||
r = c.call('POST', '/api/v1/chats/%s/messages' % self.chat['id'], 201, actor=self.actor,
|
||||
body={'text': 'load %d-%d' % (wid, i)},
|
||||
headers={'Idempotency-Key': uuid.uuid4().hex, 'X-Request-Id': rid})
|
||||
status = r['status']
|
||||
except Failure as e:
|
||||
msg = str(e)
|
||||
status = 'error'
|
||||
for code in (500, 502, 503, 504):
|
||||
if str(code) in msg:
|
||||
status = code
|
||||
break
|
||||
except Exception:
|
||||
status = 'error'
|
||||
with self._lock:
|
||||
self.records.append((rid, t0, time.monotonic() - m0, status))
|
||||
i += 1
|
||||
|
||||
def start(self):
|
||||
self._pool = ThreadPoolExecutor(max_workers=self.concurrency)
|
||||
self._futures = [self._pool.submit(self._worker, w) for w in range(self.concurrency)]
|
||||
self.started = time.time()
|
||||
return self
|
||||
|
||||
def stop(self):
|
||||
self._stop.set()
|
||||
for f in self._futures:
|
||||
f.result()
|
||||
self._pool.shutdown()
|
||||
self.stopped = time.time()
|
||||
return self
|
||||
|
||||
def summary(self, exclude=()):
|
||||
"""exclude: [(t_from, t_to)] — окна внедрённых сбоев для «нормальной» задержки."""
|
||||
recs = self.records
|
||||
ok = sorted(d for _, t, d, s in recs if s == 201)
|
||||
normal = sorted(d for _, t, d, s in recs if s == 201 and not any(a <= t <= b for a, b in exclude))
|
||||
err = sum(1 for r in recs if r[3] != 201)
|
||||
elapsed = max(1e-9, self.stopped - self.started)
|
||||
|
||||
def pct(v, p):
|
||||
return round(1000 * v[max(0, math.ceil(p * len(v)) - 1)], 2) if v else None
|
||||
return {
|
||||
'requests': len(recs), 'ok': len(ok), 'errors': err,
|
||||
'error_ratio': round(err / len(recs), 5) if recs else None,
|
||||
'ok_rps': round(len(ok) / elapsed, 1), 'seconds': round(elapsed, 1),
|
||||
'latency_ms_all_ok': {'p50': pct(ok, .5), 'p95': pct(ok, .95), 'p99': pct(ok, .99)},
|
||||
'latency_ms_outside_faults': {'p50': pct(normal, .5), 'p95': pct(normal, .95), 'p99': pct(normal, .99)},
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import base64
|
||||
import json
|
||||
import sys
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
|
||||
BASE = (sys.argv[sys.argv.index("--base-url") + 1] if "--base-url" in sys.argv else "http://localhost:8080").rstrip("/")
|
||||
PASSWORD = "Example-only-not-a-real-secret-123"
|
||||
|
||||
def post(path, body, headers=None):
|
||||
req = urllib.request.Request(BASE + path, method="POST",
|
||||
data=json.dumps(body).encode(),
|
||||
headers={"Content-Type": "application/json", **(headers or {})})
|
||||
try:
|
||||
with urllib.request.urlopen(req) as r:
|
||||
return r.status, json.loads(r.read())
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, json.loads(e.read())
|
||||
|
||||
def get(path, headers=None):
|
||||
req = urllib.request.Request(BASE + path, headers=headers or {})
|
||||
try:
|
||||
with urllib.request.urlopen(req) as r:
|
||||
return r.status, json.loads(r.read())
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, json.loads(e.read())
|
||||
|
||||
def main():
|
||||
failures = []
|
||||
|
||||
# 1. Неверный JSON → 400
|
||||
status, _ = post("/api/v1/users", "not-json")
|
||||
if status != 400:
|
||||
failures.append(f"invalid JSON: expected 400, got {status}")
|
||||
|
||||
# 2. Невалидный username → 400
|
||||
status, _ = post("/api/v1/users", {"username": "AB", "display_name": "Test", "password": PASSWORD})
|
||||
if status != 400:
|
||||
failures.append(f"invalid username: expected 400, got {status}")
|
||||
|
||||
# 3. Отсутствие Bearer на /users/me → 401
|
||||
status, _ = get("/api/v1/users/me")
|
||||
if status != 401:
|
||||
failures.append(f"no auth: expected 401, got {status}")
|
||||
|
||||
# 4. X-User-Id не даёт доступ → 401
|
||||
status, _ = get("/api/v1/users/me", {"X-User-Id": "00000000-0000-0000-0000-000000000000"})
|
||||
if status != 401:
|
||||
failures.append(f"X-User-Id bypass: expected 401, got {status}")
|
||||
|
||||
if failures:
|
||||
for f in failures:
|
||||
print(f"FAIL: {f}")
|
||||
sys.exit(1)
|
||||
print("PASS: negative checks")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,449 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Проверки наблюдаемости lab6 на Docker-стенде (только по сохранённым наблюдениям).
|
||||
|
||||
signals уровень 3–4: метрики контракта есть и с правильными метками; запрос →
|
||||
трасса (Tempo) → лог с тем же trace_id (Loki); upload → API → relay (producer)
|
||||
→ worker (consumer) → S3/DB в одной трассе; нет утечек пароля, токена,
|
||||
текста сообщения; dashboard из provisioning, его запросы возвращают данные
|
||||
retry-trace S3 недоступен во время обработки: попытки с retry в той же трассе upload
|
||||
incident-worker инцидент 1: worker остановлен → возраст задач растёт → alert firing →
|
||||
worker запущен → backlog уходит → resolved; диагностика по метрикам/логам/трассам
|
||||
incident-db инцидент 2: блокировка таблицы messages (БД «зависла») под нагрузкой →
|
||||
5xx → MessengerHighErrorRate firing → resolved; трасса показывает, что время
|
||||
ушло в запрос к БД, а не в обработчик (сравнение с медленным upload)
|
||||
backend-down Tempo и Loki остановлены под нагрузкой: API без ошибок, память Collector
|
||||
ограничена, потери считаются; затем остановлен сам Collector
|
||||
|
||||
Печатает JSON-итог и PASS/FAIL. Токены и пароли не печатаются.
|
||||
"""
|
||||
import json
|
||||
import re
|
||||
import statistics
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
from client import Client, Failure, arguments, check, run
|
||||
from labutil import ROOT, compose, psql, sh, wait_status
|
||||
from loadgen import Load
|
||||
import obsutil as o
|
||||
|
||||
SAMPLE = (Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png').read_bytes()
|
||||
FORBIDDEN_LABELS = {'user_id', 'chat_id', 'message_id', 'attachment_id', 'request_id', 'url', 'url_full',
|
||||
'http_target', 'filename', 'text', 'username'}
|
||||
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}')
|
||||
|
||||
|
||||
def upload(c, actor, chat, rid=None, data=SAMPLE, name='p.png'):
|
||||
h = {'Content-Type': 'image/png'}
|
||||
if rid:
|
||||
h['X-Request-Id'] = rid
|
||||
return c.call('POST', '/api/v1/chats/%s/attachments?filename=%s' % (chat['id'], name), 202, actor=actor,
|
||||
raw=data, headers=h, schema='Attachment')['json']
|
||||
|
||||
|
||||
def tree(spans):
|
||||
"""Краткое дерево трассы: сервис, имя, родитель (по имени), длительность."""
|
||||
by_id = {s['span_id']: s for s in spans}
|
||||
out = []
|
||||
for s in spans:
|
||||
p = by_id.get(s['parent'])
|
||||
out.append({'service': s['service'], 'name': s['name'], 'kind': s['kind'], 'ms': s['ms'],
|
||||
'parent': (p['service'] + ': ' + p['name']) if p else None,
|
||||
'outcome': s['attrs'].get('messenger.job.outcome'),
|
||||
'attempt': s['attrs'].get('messenger.job.attempt'),
|
||||
'status': s['status']})
|
||||
return out
|
||||
|
||||
|
||||
def chain_ok(spans, child_name, parent_name):
|
||||
by_id = {s['span_id']: s for s in spans}
|
||||
for s in spans:
|
||||
if s['name'] == child_name and by_id.get(s['parent'], {}).get('name') == parent_name:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def wait_alert(name, state, timeout):
|
||||
t0 = time.time()
|
||||
got = o.wait_until(lambda: (o.alerts().get(name) == state) if state else (name not in o.alerts()), timeout, 2)
|
||||
return round(time.time() - t0, 1) if got else None
|
||||
|
||||
|
||||
# ---------------- signals ----------------
|
||||
|
||||
METRICS = {
|
||||
'http requests (counter = _count)': 'http_server_request_duration_seconds_count{job="messenger-api"}',
|
||||
'http duration histogram (s)': 'http_server_request_duration_seconds_bucket{job="messenger-api"}',
|
||||
'jobs processed by outcome': 'messenger_jobs_processed_total',
|
||||
'job duration histogram (s)': 'messenger_job_duration_seconds_bucket',
|
||||
'time to ready histogram (s)': 'messenger_attachment_time_to_ready_seconds_bucket',
|
||||
'queue backlog by state': 'messenger_jobs_backlog',
|
||||
'oldest job age (s)': 'messenger_jobs_oldest_age_seconds',
|
||||
'outbox pending': 'messenger_outbox_pending',
|
||||
'rabbitmq queue messages': '{__name__=~"rabbitmq_detailed_queue_messages_ready|rabbitmq_queue_messages_ready"}',
|
||||
'worker busy': 'messenger_worker_busy',
|
||||
'worker capacity': 'messenger_worker_capacity',
|
||||
'db pool acquired': '{__name__=~"pgxpool_acquired_connections.*"}',
|
||||
'db pool waits': '{__name__=~"pgxpool_empty_acquire.*"}',
|
||||
'process cpu': '{__name__=~"process_cpu_time.*"}',
|
||||
'go memory': '{__name__=~"go_memory_used.*"}',
|
||||
}
|
||||
|
||||
|
||||
def scenario_signals(c):
|
||||
o.wait_grafana()
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
t0 = time.time() - 5
|
||||
secret_text = 'секрет-текст-' + uuid.uuid4().hex
|
||||
rid_msg = 'obs-msg-' + uuid.uuid4().hex[:16]
|
||||
c.call('POST', '/api/v1/chats/%s/messages' % chat['id'], 201, actor=alice, body={'text': secret_text},
|
||||
headers={'Idempotency-Key': uuid.uuid4().hex, 'X-Request-Id': rid_msg})
|
||||
rid_up = 'obs-upload-' + uuid.uuid4().hex[:16]
|
||||
att = upload(c, alice, chat, rid_up)
|
||||
meta = wait_status(c, bob, att['id'], ('ready',))
|
||||
c.call('GET', '/api/v1/chats/%s/messages' % chat['id'], actor=bob)
|
||||
res = {}
|
||||
|
||||
# 1. Контролируемый запрос → трасса → лог API с тем же trace_id
|
||||
tid = o.find_trace('{span.request_id="%s"}' % rid_msg, t0)
|
||||
check(tid, 'trace for controlled request not found in Tempo')
|
||||
spans, _ = o.tempo_trace(tid)
|
||||
server = [s for s in spans if s['kind'] in ('SPAN_KIND_SERVER', 2, '2') or s['name'].startswith('POST /api')]
|
||||
check(server, 'no server span')
|
||||
logs = o.wait_until(lambda: o.loki('{service_name="messenger-api"} | trace_id="%s"' % tid, t0), 60)
|
||||
check(logs, 'no API log with trace_id ' + tid)
|
||||
log_line = logs[0][1]
|
||||
res['request'] = {'request_id': rid_msg, 'trace_id': tid, 'spans': tree(spans)[:12],
|
||||
'log': {'line': log_line[:300], 'labels': {k: v for k, v in logs[0][2].items()
|
||||
if k in ('service_name', 'event', 'route', 'status', 'trace_id', 'span_id',
|
||||
'detected_level', 'severity_text', 'request_id')}}}
|
||||
|
||||
# 2. Upload → relay → worker → S3/DB в одной трассе (W3C через outbox и AMQP)
|
||||
tid2 = o.find_trace('{span.request_id="%s"}' % rid_up, t0)
|
||||
check(tid2, 'upload trace not found')
|
||||
|
||||
def full():
|
||||
sp, _ = o.tempo_trace(tid2)
|
||||
return sp if any(s['service'] == 'messenger-worker' for s in sp) else None
|
||||
spans2 = o.wait_until(full, 60)
|
||||
check(spans2, 'worker spans not in the upload trace')
|
||||
services = sorted({s['service'] for s in spans2})
|
||||
links = {
|
||||
'api server → relay producer': chain_ok(spans2, 'attachment.process publish', 'POST /api/v1/chats/{chat_id}/attachments'),
|
||||
'relay producer → worker consumer': chain_ok(spans2, 'attachment.process process', 'attachment.process publish'),
|
||||
'worker consumer → S3 PUT': any(s['name'] == 'S3 PUT' for s in spans2),
|
||||
'worker consumer → image.decode': chain_ok(spans2, 'image.decode', 'attachment.process process'),
|
||||
}
|
||||
db_in_worker = sorted({s['name'] for s in spans2 if s['service'] == 'messenger-worker' and s['name'] not in
|
||||
('attachment.process process', 'image.decode', 'image.variants') and not s['name'].startswith('S3')})
|
||||
check(all(links.values()), 'broken causal chain: %s' % links)
|
||||
wlogs = o.wait_until(lambda: o.loki('{service_name="messenger-worker"} | trace_id="%s"' % tid2, t0), 60)
|
||||
check(wlogs, 'no worker log with the upload trace_id')
|
||||
res['upload'] = {'request_id': rid_up, 'trace_id': tid2, 'services': services, 'links': links,
|
||||
'span_count': len(spans2), 'worker_db_spans': db_in_worker[:10], 'tree': tree(spans2)[:40],
|
||||
'worker_log_events': sorted({l[2].get('event', '') for l in wlogs})}
|
||||
|
||||
# 3. Метрики контракта и метки
|
||||
time.sleep(12) # период экспорта метрик 5 s + scrape 5 s
|
||||
found = {}
|
||||
for title, sel in METRICS.items():
|
||||
r = o.prom(sel)
|
||||
names = sorted({x['metric'].get('__name__') for x in r})
|
||||
found[title] = {'series': len(r), 'names': names[:4]}
|
||||
missing = [k for k, v in found.items() if v['series'] == 0]
|
||||
check(not missing, 'metrics missing: %s' % missing)
|
||||
labels = set(o.prom_labels())
|
||||
bad = sorted(labels & FORBIDDEN_LABELS)
|
||||
check(not bad, 'forbidden metric labels: %s' % bad)
|
||||
routes = o.prom_label_values('http_route')
|
||||
check(not [r for r in routes if UUID_RE.search(r)], 'raw ids in http_route: %s' % routes)
|
||||
sample_series = o.prom('http_server_request_duration_seconds_count{job="messenger-api"}')[0]['metric']
|
||||
res['metrics'] = {'found': found, 'labels_total': len(labels), 'forbidden_labels': bad,
|
||||
'http_route_values': routes, 'example_series_labels': sorted(sample_series)}
|
||||
|
||||
# 4. Утечки: пароль, токен, текст сообщения, Authorization — ни в логах (Loki, stdout), ни в трассах
|
||||
needles = {'password': alice['registration']['password'], 'session_token': alice['token'],
|
||||
'message_text': secret_text, 'bearer_header': 'Bearer ' + alice['token'][:12]}
|
||||
leaks = {}
|
||||
for k, v in needles.items():
|
||||
hits = o.loki('{service_name=~"messenger-.+"} |= `%s`' % v.replace('`', ''), t0, limit=5)
|
||||
leaks['loki:' + k] = len(hits)
|
||||
raw_traces = json.dumps(o.tempo_trace(tid)[1]) + json.dumps(o.tempo_trace(tid2)[1])
|
||||
for k, v in needles.items():
|
||||
leaks['tempo:' + k] = raw_traces.count(v)
|
||||
api_stdout = compose('logs', '--no-color', '--since', '15m', 'api', 'worker', 'relay').stdout
|
||||
for k, v in needles.items():
|
||||
leaks['stdout:' + k] = api_stdout.count(v)
|
||||
check(sum(leaks.values()) == 0, 'telemetry leak: %s' % {k: v for k, v in leaks.items() if v})
|
||||
res['leak_check'] = leaks
|
||||
|
||||
# 5. Provisioning: datasources и dashboard из Git; каждый Prometheus-запрос панели возвращает данные
|
||||
ds = sorted(d['type'] + ':' + d['uid'] for d in o.grafana('/api/datasources'))
|
||||
found_d = o.grafana('/api/search', {'query': 'Messenger'})
|
||||
check(any(d.get('uid') == 'messenger-overview' for d in found_d), 'dashboard not provisioned')
|
||||
dash = o.grafana('/api/dashboards/uid/messenger-overview')['dashboard']
|
||||
panel_check = []
|
||||
for p in dash['panels']:
|
||||
for t in p.get('targets', []):
|
||||
if t.get('datasource', {}).get('uid') != 'prometheus':
|
||||
continue
|
||||
expr = t['expr'].replace('$__rate_interval', '1m')
|
||||
try:
|
||||
n = len(o.prom(expr))
|
||||
except Exception as e:
|
||||
n = 'error: %s' % type(e).__name__
|
||||
panel_check.append({'panel': p['title'], 'legend': t.get('legendFormat', ''), 'series': n})
|
||||
empty = [x for x in panel_check if x['series'] == 0]
|
||||
res['grafana'] = {'datasources': ds, 'dashboard': dash['title'], 'panels': len(dash['panels']),
|
||||
'prometheus_targets': len(panel_check), 'targets_without_data_now': empty,
|
||||
'targets': panel_check}
|
||||
errors = [x for x in panel_check if isinstance(x['series'], str)]
|
||||
check(not errors, 'dashboard queries failed: %s' % errors)
|
||||
res['attachment'] = {'id': att['id'], 'status': meta['status']}
|
||||
return res
|
||||
|
||||
|
||||
# ---------------- retry в трассе ----------------
|
||||
|
||||
def scenario_retry_trace(c):
|
||||
o.wait_grafana()
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
t0 = time.time() - 5
|
||||
worker = compose('ps', '-q', 'worker').stdout.split()[0]
|
||||
s3 = compose('ps', '-q', 's3').stdout.split()[0]
|
||||
compose('stop', 'worker')
|
||||
rid = 'obs-retry-' + uuid.uuid4().hex[:16]
|
||||
att = upload(c, alice, chat, rid)
|
||||
time.sleep(2)
|
||||
sh('docker', 'stop', s3)
|
||||
sh('docker', 'start', worker)
|
||||
time.sleep(6) # 1–2 попытки упадут на недоступном S3
|
||||
sh('docker', 'start', s3)
|
||||
meta = wait_status(c, bob, att['id'], ('ready',), timeout=150)
|
||||
tid = o.find_trace('{span.request_id="%s"}' % rid, t0)
|
||||
check(tid, 'trace not found')
|
||||
|
||||
def done():
|
||||
sp, _ = o.tempo_trace(tid)
|
||||
return sp if any(s['attrs'].get('messenger.job.outcome') == 'done' for s in sp) else None
|
||||
spans = o.wait_until(done, 90)
|
||||
check(spans, 'final attempt not in trace')
|
||||
attempts = [(s['attrs'].get('messenger.job.attempt'), s['attrs'].get('messenger.job.outcome'), s['status'])
|
||||
for s in spans if s['name'] == 'attachment.process process']
|
||||
publishes = sum(1 for s in spans if s['name'] == 'attachment.process publish')
|
||||
check(any(a[1] == 'retry' for a in attempts), 'no retry attempt in trace: %s' % attempts)
|
||||
ev = psql("SELECT string_agg(event, ',' ORDER BY id) FROM job_events WHERE job_id = "
|
||||
"(SELECT job_id FROM jobs WHERE attachment_id = '%s')" % att['id'])
|
||||
return {'request_id': rid, 'trace_id': tid, 'attempts_in_trace': attempts, 'publish_spans': publishes,
|
||||
'job_events': ev, 'final_status': meta['status'],
|
||||
'tree': [x for x in tree(spans) if x['name'].startswith('attachment.') or x['name'].startswith('POST')]}
|
||||
|
||||
|
||||
# ---------------- инцидент 1: worker ----------------
|
||||
|
||||
def scenario_incident_worker(c):
|
||||
o.wait_grafana()
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
t_stop = time.time()
|
||||
compose('stop', 'worker')
|
||||
ids = [upload(c, alice, chat, 'obs-inc1-%d-%s' % (i, uuid.uuid4().hex[:8]))['id'] for i in range(3)]
|
||||
t_firing = wait_alert('MessengerQueueLagGrowing', 'firing', 240)
|
||||
check(t_firing, 'MessengerQueueLagGrowing did not fire')
|
||||
detect = round(time.time() - t_stop, 1)
|
||||
al = o.alerts()
|
||||
# Диагностика «как оператор»: только по сохранённым наблюдениям
|
||||
diag = {
|
||||
'alerts_firing': sorted(k for k, v in al.items() if v == 'firing'),
|
||||
'backlog_queued': o.prom_value('sum(messenger_jobs_backlog{state="queued"})'),
|
||||
'oldest_age_s': o.prom_value('max(messenger_jobs_oldest_age_seconds)'),
|
||||
'jobs_processed_rate_1m': o.prom_value('sum(rate(messenger_jobs_processed_total[1m]))', default=0.0),
|
||||
'worker_capacity_series': len(o.prom('messenger_worker_capacity')),
|
||||
'rabbitmq_ready': o.prom_value('sum(rabbitmq_detailed_queue_messages_ready{queue="attachment.process"})'),
|
||||
'api_5xx_ratio': o.prom_value('messenger:http_error_ratio:rate1m', default=0.0),
|
||||
'producer_spans_since_stop': len(o.tempo_search('{name="attachment.process publish"}', t_stop)),
|
||||
'consumer_spans_since_stop': len(o.tempo_search('{name="attachment.process process"}', t_stop + 2)),
|
||||
'last_worker_log_events': sorted({l[2].get('event', '') for l in
|
||||
o.loki('{service_name="messenger-worker"}', t_stop - 30, limit=50)}),
|
||||
}
|
||||
t_start = time.time()
|
||||
compose('start', 'worker')
|
||||
for i in ids:
|
||||
wait_status(c, bob, i, ('ready',), timeout=120)
|
||||
t_ready = round(time.time() - t_start, 1)
|
||||
t_resolved = wait_alert('MessengerQueueLagGrowing', None, 180)
|
||||
check(t_resolved is not None, 'alert did not resolve')
|
||||
series = o.prom_range('max(messenger_jobs_oldest_age_seconds)', t_stop - 30, time.time(), 10)
|
||||
return {'detection_seconds_from_worker_stop': detect, 'diagnosis': diag,
|
||||
'backlog_ready_seconds_after_start': t_ready,
|
||||
'resolved_seconds_after_worker_start': round(t_ready + t_resolved, 1),
|
||||
'oldest_age_series': [[round(float(t) - t_stop), round(float(v), 1)] for t, v in (series[0]['values'] if series else [])]}
|
||||
|
||||
|
||||
# ---------------- инцидент 2: БД ----------------
|
||||
|
||||
def is_db(s):
|
||||
return (s['attrs'].get('db.system') == 'postgresql' or s['attrs'].get('db.system.name') == 'postgresql'
|
||||
or s['name'].split(' ')[0] in ('query', 'acquire', 'batch', 'prepare', 'connect', 'copy_from'))
|
||||
|
||||
|
||||
def breakdown(spans):
|
||||
"""Доля времени server span, проведённая в дочерних spans БД (pgx) и S3."""
|
||||
by_parent = {}
|
||||
for s in spans:
|
||||
by_parent.setdefault(s['parent'], []).append(s)
|
||||
srv = next((s for s in spans if s['parent'] == '' or s['name'].startswith(('POST /api', 'GET /api'))), None)
|
||||
if not srv:
|
||||
return None
|
||||
db = sum(s['ms'] for s in spans if s['service'] == srv['service'] and is_db(s))
|
||||
s3 = sum(s['ms'] for s in spans if s['name'].startswith('S3'))
|
||||
return {'server_span': srv['name'], 'server_ms': srv['ms'], 'status': srv['attrs'].get('http.response.status_code'),
|
||||
'db_ms': round(db, 1), 's3_ms': round(s3, 1), 'db_share': round(db / srv['ms'], 3) if srv['ms'] else None,
|
||||
'db_spans': [(s['name'], s['ms']) for s in spans if is_db(s)][:6]}
|
||||
|
||||
|
||||
def scenario_incident_db(c):
|
||||
o.wait_grafana()
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
load = Load(c.base, None, alice, chat, concurrency=4, timeout=10, prefix='obs-inc2').start()
|
||||
time.sleep(20)
|
||||
t_lock = time.time()
|
||||
lock = subprocess.Popen(['docker', 'compose', 'exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger',
|
||||
'-c', 'BEGIN; LOCK TABLE messages IN ACCESS EXCLUSIVE MODE; SELECT pg_sleep(110); COMMIT;'],
|
||||
cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
t_firing = wait_alert('MessengerHighErrorRate', 'firing', 150)
|
||||
detect = round(time.time() - t_lock, 1) if t_firing else None
|
||||
snap = {
|
||||
'error_ratio_1m': o.prom_value('messenger:http_error_ratio:rate1m'),
|
||||
'p99_s': o.prom_value('histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket{job="messenger-api", http_route!~"/health/.*"}[1m])))'),
|
||||
'p99_by_route': {r['metric'].get('http_route'): round(float(r['value'][1]), 3) for r in o.prom(
|
||||
'histogram_quantile(0.99, sum by (le, http_route) (rate(http_server_request_duration_seconds_bucket{job="messenger-api", http_route!~"/health/.*"}[1m])))')},
|
||||
'db_pool_acquired': o.prom_value('sum({__name__=~"pgxpool_acquired_connections.*", job="messenger-api"})'),
|
||||
'health_ready_5xx_rate': o.prom_value('sum(rate(http_server_request_duration_seconds_count{http_route="/health/ready", http_response_status_class="5xx"}[1m]))', default=0.0),
|
||||
}
|
||||
lock.wait(timeout=200)
|
||||
t_unlock = time.time()
|
||||
t_resolved = wait_alert('MessengerHighErrorRate', None, 180)
|
||||
load.stop()
|
||||
# Трассы ошибок: где время? (по сохранённым трассам Tempo)
|
||||
err_traces = o.tempo_search('{resource.service.name="messenger-api" && span.http.response.status_code >= 500}', t_lock - 1, limit=5)
|
||||
analysis = []
|
||||
for t in err_traces[:3]:
|
||||
sp, _ = o.tempo_trace(t['traceID'])
|
||||
analysis.append(breakdown(sp))
|
||||
# Сравнение: медленный upload большого файла — время не в БД
|
||||
rid = 'obs-slowhandler-' + uuid.uuid4().hex[:8]
|
||||
from labutil import noise_png
|
||||
t_up = time.time() - 2
|
||||
upload(c, alice, chat, rid, data=noise_png(4 * 1024 * 1024), name='big.png')
|
||||
tid = o.find_trace('{span.request_id="%s"}' % rid, t_up)
|
||||
slow_handler = breakdown(o.tempo_trace(tid)[0]) if tid else None
|
||||
err_logs = o.loki('{service_name="messenger-api"} | detected_level=~"error|ERROR"', t_lock, t_unlock + 5, limit=200)
|
||||
check(detect is not None, 'MessengerHighErrorRate did not fire')
|
||||
check(t_resolved is not None, 'MessengerHighErrorRate did not resolve')
|
||||
check(analysis and all(a and a['db_share'] and a['db_share'] > 0.8 for a in analysis),
|
||||
'error traces do not point to DB: %s' % analysis)
|
||||
return {'fault': 'LOCK TABLE messages IN ACCESS EXCLUSIVE MODE for 110 s under load (4 clients)',
|
||||
'detection_seconds': detect, 'resolved_seconds_after_unlock': t_resolved,
|
||||
'metrics_at_firing': snap, 'error_trace_breakdown': analysis,
|
||||
'slow_handler_comparison': slow_handler,
|
||||
'error_logs': {'count': len(err_logs),
|
||||
'events': sorted({l[2].get('event', '') for l in err_logs}),
|
||||
'routes': sorted({l[2].get('route', '') for l in err_logs})},
|
||||
'load': load.summary(exclude=[(t_lock, t_unlock)])}
|
||||
|
||||
|
||||
# ---------------- отказ backend телеметрии ----------------
|
||||
|
||||
def mem_of(service):
|
||||
cid = compose('ps', '-q', service).stdout.split()
|
||||
return round(o.mem_bytes(cid[0]) / 2**20, 1) if cid and o.mem_bytes(cid[0]) else None
|
||||
|
||||
|
||||
def scenario_backend_down(c):
|
||||
o.wait_grafana()
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
load = Load(c.base, None, alice, chat, concurrency=4, timeout=10, prefix='obs-bd').start()
|
||||
samples = []
|
||||
stop = threading.Event()
|
||||
col = compose('ps', '-q', 'otel-collector').stdout.split()[0]
|
||||
|
||||
def sampler():
|
||||
while not stop.is_set():
|
||||
samples.append({'t': round(time.time() - t0, 1), 'collector_mib': round((o.mem_bytes(col) or 0) / 2**20, 1),
|
||||
'api_mib': [round((o.mem_bytes(x) or 0) / 2**20, 1) for x in compose('ps', '-q', 'api').stdout.split()]})
|
||||
time.sleep(5)
|
||||
t0 = time.time()
|
||||
threading.Thread(target=sampler, daemon=True).start()
|
||||
time.sleep(15)
|
||||
compose('stop', 'tempo', 'loki')
|
||||
t_down = time.time()
|
||||
phase = {}
|
||||
fired = wait_alert('MessengerTelemetryExportFailing', 'firing', 150)
|
||||
phase['export_failing_alert_seconds'] = round(time.time() - t_down, 1) if fired else None
|
||||
time.sleep(max(0, 130 - (time.time() - t_down)))
|
||||
q = lambda e: o.prom_value(e, default=0.0)
|
||||
phase['during'] = {
|
||||
'exporter_queue_size_max': q('max_over_time(sum(otelcol_exporter_queue_size)[2m:5s])'),
|
||||
'exporter_queue_capacity': q('sum(otelcol_exporter_queue_capacity)'),
|
||||
'send_failed_spans': q('sum(increase(otelcol_exporter_send_failed_spans_total[3m]))'),
|
||||
'send_failed_log_records': q('sum(increase(otelcol_exporter_send_failed_log_records_total[3m]))'),
|
||||
'enqueue_failed_spans': q('sum(increase(otelcol_exporter_enqueue_failed_spans_total[3m]))'),
|
||||
'refused_spans_memory_limiter': q('sum(increase(otelcol_receiver_refused_spans_total[3m]))'),
|
||||
'metrics_still_scraped': q('sum(rate(http_server_request_duration_seconds_count{job="messenger-api"}[1m]))'),
|
||||
}
|
||||
compose('start', 'tempo', 'loki')
|
||||
compose('up', '-d', '--wait', '--no-deps', 'tempo', 'loki', timeout=180)
|
||||
t_up = time.time()
|
||||
rid = 'obs-after-' + uuid.uuid4().hex[:8]
|
||||
c.call('POST', '/api/v1/chats/%s/messages' % chat['id'], 201, actor=alice, body={'text': 'after'},
|
||||
headers={'Idempotency-Key': uuid.uuid4().hex, 'X-Request-Id': rid})
|
||||
phase['new_trace_after_recovery'] = bool(o.find_trace('{span.request_id="%s"}' % rid, t_up - 2, timeout=90))
|
||||
# Фаза 2: остановлен сам Collector — SDK отбрасывает по ограниченной очереди
|
||||
compose('stop', 'otel-collector')
|
||||
t_cd = time.time()
|
||||
time.sleep(40)
|
||||
compose('start', 'otel-collector')
|
||||
time.sleep(10)
|
||||
load.stop()
|
||||
stop.set()
|
||||
summary = load.summary()
|
||||
col_max = max(s['collector_mib'] for s in samples)
|
||||
api_max = max(max(s['api_mib'] or [0]) for s in samples)
|
||||
check(summary['errors'] == 0, 'API errors while telemetry backend was down: %s' % summary)
|
||||
check(col_max < 256, 'collector memory not bounded')
|
||||
check(phase['new_trace_after_recovery'], 'no traces after backend recovery')
|
||||
return {'load': summary, 'collector_limit_mib': 256, 'collector_max_mib': col_max,
|
||||
'api_max_mib': api_max, 'api_limit_mib': 256, 'phases': phase,
|
||||
'timeline': {'tempo_loki_down_s': round(t_down - t0), 'tempo_loki_up_s': round(t_up - t0),
|
||||
'collector_down_s': round(t_cd - t0), 'collector_down_for_s': 40},
|
||||
'memory_samples': samples}
|
||||
|
||||
|
||||
SCENARIOS = {'signals': scenario_signals, 'retry-trace': scenario_retry_trace,
|
||||
'incident-worker': scenario_incident_worker, 'incident-db': scenario_incident_db,
|
||||
'backend-down': scenario_backend_down}
|
||||
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument('scenario', choices=sorted(SCENARIOS))
|
||||
p.add_argument('--output', default=None)
|
||||
args = arguments('Lab6 observability scenarios on the Docker stand', configure)
|
||||
c = Client(args.base_url, args.ca_file, timeout=30)
|
||||
try:
|
||||
result = SCENARIOS[args.scenario](c)
|
||||
finally:
|
||||
compose('up', '-d', '--no-deps', '--wait', 'worker', 'relay', 's3', 'api', 'otel-collector', 'tempo', 'loki',
|
||||
timeout=300, check=False)
|
||||
text = json.dumps({'scenario': args.scenario, 'result': result}, ensure_ascii=False, indent=2)
|
||||
if args.output:
|
||||
Path(args.output).write_text(text + '\n', encoding='utf-8')
|
||||
print(text)
|
||||
print('PASS: ' + args.scenario)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,202 @@
|
||||
"""Доступ к сохранённым наблюдениям через Grafana (единственный интерфейс к хранилищам).
|
||||
|
||||
Prometheus, Loki и Tempo не публикуют порты: запросы идут через datasource proxy
|
||||
Grafana (http://127.0.0.1:3000/api/datasources/proxy/uid/<uid>/...) с учётной записью
|
||||
admin из secrets/grafana_admin_password. Пароль не печатается.
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
GRAFANA = os.environ.get('GRAFANA_URL', 'http://127.0.0.1:3000')
|
||||
|
||||
|
||||
def _auth():
|
||||
pw = (ROOT / 'secrets' / 'grafana_admin_password').read_text().strip()
|
||||
return 'Basic ' + base64.b64encode(('admin:' + pw).encode()).decode()
|
||||
|
||||
|
||||
def grafana(path, params=None, method='GET', body=None, timeout=30):
|
||||
url = GRAFANA + path
|
||||
if params:
|
||||
url += ('&' if '?' in url else '?') + urllib.parse.urlencode(params)
|
||||
data = json.dumps(body).encode() if body is not None else None
|
||||
req = urllib.request.Request(url, data=data, method=method,
|
||||
headers={'Authorization': _auth(), 'Content-Type': 'application/json'})
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
raw = r.read()
|
||||
return json.loads(raw) if raw else None
|
||||
|
||||
|
||||
def wait_grafana(timeout=120):
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
try:
|
||||
if grafana('/api/health')['database'] == 'ok':
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(2)
|
||||
raise RuntimeError('grafana not ready')
|
||||
|
||||
|
||||
# ---------------- Prometheus ----------------
|
||||
|
||||
def prom(query, at=None):
|
||||
p = {'query': query}
|
||||
if at:
|
||||
p['time'] = at
|
||||
r = grafana('/api/datasources/proxy/uid/prometheus/api/v1/query', p)
|
||||
return r['data']['result']
|
||||
|
||||
|
||||
def prom_value(query, at=None, default=None):
|
||||
res = prom(query, at)
|
||||
if not res:
|
||||
return default
|
||||
return float(res[0]['value'][1])
|
||||
|
||||
|
||||
def prom_range(query, start, end, step=5):
|
||||
r = grafana('/api/datasources/proxy/uid/prometheus/api/v1/query_range',
|
||||
{'query': query, 'start': start, 'end': end, 'step': step})
|
||||
return r['data']['result']
|
||||
|
||||
|
||||
def prom_labels():
|
||||
return grafana('/api/datasources/proxy/uid/prometheus/api/v1/labels')['data']
|
||||
|
||||
|
||||
def prom_label_values(name):
|
||||
return grafana('/api/datasources/proxy/uid/prometheus/api/v1/label/%s/values' % name)['data']
|
||||
|
||||
|
||||
def alerts():
|
||||
"""Активные alerts Prometheus: {alertname: state} (pending/firing)."""
|
||||
r = grafana('/api/datasources/proxy/uid/prometheus/api/v1/alerts')
|
||||
return {a['labels']['alertname']: a['state'] for a in r['data']['alerts']}
|
||||
|
||||
|
||||
# ---------------- Loki ----------------
|
||||
|
||||
def loki(query, start, end=None, limit=200):
|
||||
"""Записи логов: [(ts_ns, line, labels)] (labels включают structured metadata)."""
|
||||
end = end or time.time() + 1
|
||||
r = grafana('/api/datasources/proxy/uid/loki/loki/api/v1/query_range',
|
||||
{'query': query, 'start': int(start * 1e9), 'end': int(end * 1e9), 'limit': limit,
|
||||
'direction': 'forward'})
|
||||
out = []
|
||||
for stream in r['data']['result']:
|
||||
for ts, line, *rest in stream['values']:
|
||||
labels = dict(stream['stream'])
|
||||
if rest and isinstance(rest[0], dict):
|
||||
for v in rest[0].values():
|
||||
if isinstance(v, dict):
|
||||
labels.update(v)
|
||||
out.append((int(ts), line, labels))
|
||||
out.sort(key=lambda x: x[0])
|
||||
return out
|
||||
|
||||
|
||||
# ---------------- Tempo ----------------
|
||||
|
||||
def tempo_search(traceql, start, end=None, limit=20):
|
||||
end = end or time.time() + 1
|
||||
r = grafana('/api/datasources/proxy/uid/tempo/api/search',
|
||||
{'q': traceql, 'start': int(start), 'end': int(end) + 1, 'limit': limit})
|
||||
return r.get('traces') or []
|
||||
|
||||
|
||||
def _b64hex(v):
|
||||
if not v:
|
||||
return ''
|
||||
if all(c in '0123456789abcdef' for c in v.lower()) and len(v) in (16, 32):
|
||||
return v.lower()
|
||||
return base64.b64decode(v).hex()
|
||||
|
||||
|
||||
def tempo_trace(trace_id):
|
||||
"""Spans трассы: [{service, name, kind, span_id, parent, start, end, ms, attrs, status}]."""
|
||||
r = grafana('/api/datasources/proxy/uid/tempo/api/traces/' + trace_id)
|
||||
batches = r.get('batches') or r.get('resourceSpans') or (r.get('trace') or {}).get('resourceSpans') or []
|
||||
spans = []
|
||||
for b in batches:
|
||||
res = {a['key']: _val(a['value']) for a in b.get('resource', {}).get('attributes', [])}
|
||||
for ss in b.get('scopeSpans') or b.get('instrumentationLibrarySpans') or []:
|
||||
for s in ss.get('spans', []):
|
||||
st, en = int(s.get('startTimeUnixNano', 0)), int(s.get('endTimeUnixNano', 0))
|
||||
spans.append({
|
||||
'service': res.get('service.name'), 'instance': res.get('service.instance.id'),
|
||||
'name': s.get('name'), 'kind': s.get('kind', ''),
|
||||
'span_id': _b64hex(s.get('spanId')), 'parent': _b64hex(s.get('parentSpanId')),
|
||||
'start': st, 'end': en, 'ms': round((en - st) / 1e6, 2),
|
||||
'attrs': {a['key']: _val(a['value']) for a in s.get('attributes', [])},
|
||||
'status': (s.get('status') or {}).get('code', ''),
|
||||
})
|
||||
spans.sort(key=lambda s: s['start'])
|
||||
return spans, r
|
||||
|
||||
|
||||
def _val(v):
|
||||
for k in ('stringValue', 'intValue', 'boolValue', 'doubleValue'):
|
||||
if k in v:
|
||||
return v[k]
|
||||
return json.dumps(v)
|
||||
|
||||
|
||||
def find_trace(traceql, start, timeout=90):
|
||||
"""Ждёт появления трассы по TraceQL (ingest Collector → Tempo занимает секунды)."""
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
res = tempo_search(traceql, start)
|
||||
if res:
|
||||
return res[0]['traceID']
|
||||
time.sleep(2)
|
||||
return None
|
||||
|
||||
|
||||
def wait_until(fn, timeout, interval=2):
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
v = fn()
|
||||
if v:
|
||||
return v
|
||||
time.sleep(interval)
|
||||
return None
|
||||
|
||||
|
||||
# ---------------- cgroup ресурсов контейнера (с хоста) ----------------
|
||||
|
||||
def cgroup_dir(cid):
|
||||
for p in ('/sys/fs/cgroup/system.slice/docker-%s.scope' % cid, '/sys/fs/cgroup/docker/%s' % cid):
|
||||
if os.path.isdir(p):
|
||||
return p
|
||||
return None
|
||||
|
||||
|
||||
def cg_read(cid, name):
|
||||
d = cgroup_dir(cid)
|
||||
if not d:
|
||||
return None
|
||||
try:
|
||||
return Path(d, name).read_text()
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def cpu_usec(cid):
|
||||
t = cg_read(cid, 'cpu.stat') or ''
|
||||
for line in t.splitlines():
|
||||
if line.startswith('usage_usec '):
|
||||
return int(line.split()[1])
|
||||
return None
|
||||
|
||||
|
||||
def mem_bytes(cid, name='memory.current'):
|
||||
t = cg_read(cid, name)
|
||||
return int(t.strip()) if t and t.strip().isdigit() else None
|
||||
@@ -0,0 +1,486 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Сценарии асинхронной обработки lab5 на Docker-стенде.
|
||||
|
||||
demo уровень 3: worker остановлен → upload 202 → сообщение с вложением →
|
||||
content 409, чат работает → рестарт API и broker (volume) → worker → ready
|
||||
outbox-gap relay остановлен (разрыв COMMIT↔publish) → upload → relay → ready;
|
||||
relay падает после confirm до отметки outbox → повторная публикация → один результат
|
||||
crash-effect worker падает после записи объектов до COMMIT → lease истекает → повтор → тот же результат
|
||||
crash-commit worker падает после COMMIT до ack → повторная доставка → no-op
|
||||
broker-restart принятая задача в quorum-очереди переживает рестарт RabbitMQ с volume
|
||||
transient S3 недоступен во время обработки → retry с backoff и jitter → ready
|
||||
failed-replay постоянная ошибка → failed (error_code), реестр, явный replay, повтор успешной запрещён;
|
||||
невалидное сообщение → DLQ
|
||||
limits изображение 36 Мпикс и параллельная обработка: пик памяти worker, время
|
||||
versions трек 5: reprocess v2, устаревший дубль v1 и повтор v2 после публикации не меняют результат
|
||||
|
||||
Каждый сценарий печатает JSON-итог и PASS/FAIL; ID вложений и задания — без токенов.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import struct
|
||||
import time
|
||||
import zlib
|
||||
from labutil import (BUCKET, bucket_count, compose, fixture, mc, psql, sh, wait_status)
|
||||
from client import Client, Failure, arguments, check, run
|
||||
from image_probe import jpeg_size
|
||||
|
||||
SAMPLE = None
|
||||
|
||||
|
||||
def sample():
|
||||
global SAMPLE
|
||||
if SAMPLE is None:
|
||||
from pathlib import Path
|
||||
SAMPLE = (Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png').read_bytes()
|
||||
return SAMPLE
|
||||
|
||||
|
||||
def upload(c, actor, chat, data, name='p.png', ctype='image/png'):
|
||||
r = c.call('POST', '/api/v1/chats/%s/attachments?filename=%s' % (chat['id'], name), 202, actor=actor,
|
||||
raw=data, headers={'Content-Type': ctype}, schema='Attachment')
|
||||
check(r['json']['status'] == 'queued', 'upload snapshot must be queued')
|
||||
return r['json']
|
||||
|
||||
|
||||
def wait_ready_api(c, timeout=90):
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
try:
|
||||
c.call('GET', '/health/ready')
|
||||
return
|
||||
except Failure:
|
||||
time.sleep(1)
|
||||
raise Failure('API not ready')
|
||||
|
||||
|
||||
def job_of(att_id, version=1):
|
||||
row = psql("SELECT job_id || '|' || state || '|' || attempt FROM jobs WHERE attachment_id = '%s' AND pipeline_version = %d"
|
||||
% (att_id, version))
|
||||
jid, state, attempt = row.split('|')
|
||||
return jid, state, int(attempt)
|
||||
|
||||
|
||||
def events(job_id):
|
||||
return psql("SELECT string_agg(event, ',' ORDER BY id) FROM job_events WHERE job_id = '%s'" % job_id)
|
||||
|
||||
|
||||
def invariants(att_id, chat_id):
|
||||
"""I1 ≤1 варианта на (версия, имя); I2 ready ⇒ 3 варианта опубликованной версии с объектами;
|
||||
I3 объектов v/ ровно 3 на каждую версию с вариантами (повторы не размножают)."""
|
||||
dup = psql("SELECT count(*) FROM (SELECT 1 FROM attachment_variants WHERE attachment_id='%s' "
|
||||
"GROUP BY pipeline_version, name HAVING count(*) > 1) d" % att_id)
|
||||
check(dup == '0', 'I1 duplicated variants')
|
||||
st, ver = psql("SELECT status || '|' || pipeline_version FROM attachments WHERE id='%s'" % att_id).split('|')
|
||||
out = {'status': st, 'published_version': int(ver)}
|
||||
if st == 'ready':
|
||||
n = psql("SELECT count(*) FROM attachment_variants WHERE attachment_id='%s' AND pipeline_version=%s" % (att_id, ver))
|
||||
check(n == '3', 'I2 ready with %s variants' % n)
|
||||
versions = psql("SELECT string_agg(DISTINCT pipeline_version::text, ',') FROM attachment_variants WHERE attachment_id='%s'" % att_id)
|
||||
for v in versions.split(','):
|
||||
objs = bucket_count('v/%s/%s/p%s/' % (chat_id, att_id, v))
|
||||
check(objs == 3, 'I3 version %s has %d objects' % (v, objs))
|
||||
out['objects_per_version'] = {v: 3 for v in versions.split(',')}
|
||||
return out
|
||||
|
||||
|
||||
def check_variants(c, actor, meta, original):
|
||||
vs = {v['name']: v for v in meta['variants']}
|
||||
check(set(vs) == {'thumbnail', 'crop', 'optimized'}, 'variants: %s' % sorted(vs))
|
||||
th = c.call('GET', '/api/v1/attachments/%s/content?variant=thumbnail' % meta['id'], actor=actor)
|
||||
check(th['headers'].get_content_type() == 'image/jpeg', 'thumbnail type')
|
||||
check(hashlib.sha256(th['bytes']).hexdigest() == vs['thumbnail']['sha256'], 'thumbnail sha')
|
||||
tw, thh = jpeg_size(th['bytes'])
|
||||
cr = c.call('GET', '/api/v1/attachments/%s/content?variant=crop' % meta['id'], actor=actor)
|
||||
check(jpeg_size(cr['bytes']) == (128, 128), 'crop size')
|
||||
op = c.call('GET', '/api/v1/attachments/%s/content?variant=optimized' % meta['id'], actor=actor)
|
||||
check(op['bytes'][:4] == b'RIFF' and op['bytes'][8:12] == b'WEBP', 'optimized is not WebP')
|
||||
check(hashlib.sha256(op['bytes']).hexdigest() == vs['optimized']['sha256'], 'optimized sha')
|
||||
orig = c.call('GET', '/api/v1/attachments/%s/content' % meta['id'], actor=actor)
|
||||
check(orig['bytes'] == original, 'original changed')
|
||||
return {'thumbnail': [tw, thh], 'crop': [128, 128],
|
||||
'optimized': [vs['optimized']['width'], vs['optimized']['height']],
|
||||
'optimized_bytes': vs['optimized']['size_bytes'], 'original_bytes': len(original)}
|
||||
|
||||
|
||||
def rabbit_healthy(timeout=90):
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
st = sh('docker', 'inspect', '-f', '{{.State.Health.Status}}', compose('ps', '-q', 'rabbitmq').stdout.strip(),
|
||||
check=False).stdout.strip()
|
||||
if st == 'healthy':
|
||||
return
|
||||
time.sleep(1)
|
||||
raise Failure('rabbitmq not healthy')
|
||||
|
||||
|
||||
def queues():
|
||||
"""Сообщений в очередях RabbitMQ (без строки заголовка)."""
|
||||
rabbit_healthy()
|
||||
out = compose('exec', '-T', 'rabbitmq', 'rabbitmqctl', '-q', 'list_queues', '--no-table-headers',
|
||||
'name', 'messages').stdout
|
||||
res = {}
|
||||
for line in out.splitlines():
|
||||
parts = line.split()
|
||||
if len(parts) == 2 and parts[1].isdigit():
|
||||
res[parts[0]] = int(parts[1])
|
||||
return res
|
||||
|
||||
|
||||
def drain(timeout=180):
|
||||
"""Изоляция сценариев: все сервисы pipeline запущены, незавершённых заданий нет."""
|
||||
compose('up', '-d', '--no-deps', '--wait', 'worker', 'relay', 'rabbitmq', 's3', timeout=240)
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
busy = psql("SELECT count(*) FROM jobs WHERE state IN ('queued', 'processing')")
|
||||
if busy == '0':
|
||||
return
|
||||
time.sleep(1)
|
||||
raise Failure('pipeline did not drain: %s jobs pending' % busy)
|
||||
|
||||
|
||||
def recreate(service, **env):
|
||||
"""Пересоздать сервис с переменными окружения (точки сбоя, таймауты)."""
|
||||
compose('up', '-d', '--no-deps', '--wait', service, env=env, timeout=180)
|
||||
|
||||
|
||||
# ---------------- уровень 3 ----------------
|
||||
|
||||
def scenario_demo(c):
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
timeline = []
|
||||
compose('stop', 'worker')
|
||||
timeline.append('worker stopped')
|
||||
att = upload(c, alice, chat, sample(), name='demo.png')
|
||||
timeline.append('upload 202 queued id=%s' % att['id'])
|
||||
msg = c.message(alice, chat, 'с вложением в очереди', attachments=[att['id']])['json']
|
||||
check(msg['attachment_ids'] == [att['id']], 'message attachment')
|
||||
timeline.append('message 201 with queued attachment')
|
||||
c.call('GET', '/api/v1/attachments/%s/content' % att['id'], 409, actor=bob)
|
||||
c.message(bob, chat, 'чат работает без worker')
|
||||
timeline.append('content 409, other messages OK')
|
||||
time.sleep(2)
|
||||
published = psql("SELECT count(*) FROM outbox o JOIN jobs j USING (job_id) WHERE j.attachment_id='%s' AND o.published_at IS NOT NULL" % att['id'])
|
||||
compose('restart', 'api')
|
||||
compose('restart', 'rabbitmq')
|
||||
sh('sh', 'scripts/restore.sh')
|
||||
wait_ready_api(c)
|
||||
timeline.append('api and rabbitmq restarted (volumes kept), outbox published=%s' % published)
|
||||
q = {}
|
||||
for _ in range(30):
|
||||
q = queues()
|
||||
if q.get('attachment.process', 0) >= 1:
|
||||
break
|
||||
time.sleep(1)
|
||||
timeline.append('rabbitmq queues after restart: %s' % q)
|
||||
check(q.get('attachment.process', 0) >= 1, 'accepted job not in broker after restart: %s' % q)
|
||||
t0 = time.time()
|
||||
compose('start', 'worker')
|
||||
meta = wait_status(c, bob, att['id'], ('ready',), timeout=90)
|
||||
timeline.append('worker started → ready in %.1f s' % (time.time() - t0))
|
||||
res = check_variants(c, bob, meta, sample())
|
||||
check(res['thumbnail'] == [256, 160], 'fixture thumbnail must be 256x160')
|
||||
jid, state, attempt = job_of(att['id'])
|
||||
return {'attachment_id': att['id'], 'job_id': jid, 'job_state': state, 'attempt': attempt,
|
||||
'timeline': timeline, 'variants': res, 'invariants': invariants(att['id'], chat['id']),
|
||||
'events': events(jid)}
|
||||
|
||||
|
||||
# ---------------- уровень 4 ----------------
|
||||
|
||||
def scenario_outbox_gap(c):
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
compose('stop', 'relay')
|
||||
att = upload(c, alice, chat, sample(), name='gap.png')
|
||||
time.sleep(3)
|
||||
jid, state, _ = job_of(att['id'])
|
||||
unpublished = psql("SELECT count(*) FROM outbox WHERE job_id='%s' AND published_at IS NULL" % jid)
|
||||
check(state == 'queued' and unpublished == '1', 'job must wait in outbox: %s %s' % (state, unpublished))
|
||||
compose('restart', 'api') # «падение» после COMMIT, publish ещё не было
|
||||
wait_ready_api(c)
|
||||
compose('start', 'relay')
|
||||
meta = wait_status(c, bob, att['id'], ('ready',))
|
||||
part1 = {'attachment_id': att['id'], 'unpublished_while_relay_down': 1, 'then': meta['status']}
|
||||
|
||||
# Relay падает ПОСЛЕ publisher confirm, ДО отметки published_at → повторная публикация.
|
||||
recreate('relay', RELAY_FAULT_POINTS='relay.after_publish')
|
||||
att2 = upload(c, alice, chat, sample(), name='dup.png')
|
||||
meta2 = wait_status(c, bob, att2['id'], ('ready',), timeout=120)
|
||||
jid2, _, attempt2 = job_of(att2['id'])
|
||||
for _ in range(60):
|
||||
if psql("SELECT count(*) FROM outbox WHERE job_id='%s' AND published_at IS NOT NULL" % jid2) == '1':
|
||||
break
|
||||
time.sleep(0.5)
|
||||
attempts = psql("SELECT publish_attempts FROM outbox WHERE job_id='%s'" % jid2)
|
||||
restarts = sh('docker', 'inspect', '-f', '{{.RestartCount}}', compose('ps', '-q', 'relay').stdout.strip()).stdout.strip()
|
||||
recreate('relay')
|
||||
worker_log = compose('logs', '--no-color', 'worker').stdout
|
||||
dup_seen = worker_log.count(jid2) >= 2
|
||||
check(int(restarts) >= 1, 'fault relay.after_publish did not crash the relay')
|
||||
check(attempt2 == 1, 'duplicate publish must not create a second attempt')
|
||||
part2 = {'attachment_id': att2['id'], 'relay_restarts': int(restarts), 'outbox_publish_attempts': int(attempts or 0),
|
||||
'worker_saw_message_twice': dup_seen, 'job_attempt': attempt2, 'invariants': invariants(att2['id'], chat['id'])}
|
||||
return {'relay_down_then_up': part1, 'relay_crash_after_confirm': part2, 'events': events(jid2)}
|
||||
|
||||
|
||||
def scenario_crash_effect(c):
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
recreate('worker', WORKER_FAULT_POINTS='worker.after_side_effect', JOB_TIMEOUT_SECONDS='15')
|
||||
t0 = time.time()
|
||||
att = upload(c, alice, chat, sample(), name='crash.png')
|
||||
meta = wait_status(c, bob, att['id'], ('ready',), timeout=120)
|
||||
took = time.time() - t0
|
||||
jid, state, attempt = job_of(att['id'])
|
||||
cid = compose('ps', '-q', 'worker').stdout.split()[0]
|
||||
restarts = sh('docker', 'inspect', '-f', '{{.RestartCount}}', cid).stdout.strip()
|
||||
recreate('worker')
|
||||
check(attempt == 2, 'expected recovery on attempt 2, got %d; events=%s' % (attempt, events(jid)))
|
||||
ev = events(jid)
|
||||
check('lease_expired_requeued' in ev, 'lease expiry recovery missing: ' + ev)
|
||||
return {'attachment_id': att['id'], 'job_id': jid, 'worker_restarts': int(restarts), 'attempt': attempt,
|
||||
'seconds_to_ready': round(took, 1), 'events': ev, 'invariants': invariants(att['id'], chat['id']),
|
||||
'variants': check_variants(c, bob, meta, sample())}
|
||||
|
||||
|
||||
def scenario_crash_commit(c):
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
recreate('worker', WORKER_FAULT_POINTS='worker.after_commit')
|
||||
att = upload(c, alice, chat, sample(), name='commit.png')
|
||||
wait_status(c, bob, att['id'], ('ready',))
|
||||
time.sleep(8) # контейнер перезапускается, broker доставляет неподтверждённое сообщение повторно
|
||||
jid, state, attempt = job_of(att['id'])
|
||||
cid = compose('ps', '-q', 'worker').stdout.split()[0]
|
||||
restarts = sh('docker', 'inspect', '-f', '{{.RestartCount}}', cid).stdout.strip()
|
||||
log = compose('logs', '--no-color', 'worker').stdout
|
||||
noop = any(jid in l and 'duplicate delivery of finished job' in l for l in log.splitlines())
|
||||
recreate('worker')
|
||||
check(int(restarts) >= 1, 'fault worker.after_commit did not crash the worker')
|
||||
check(attempt == 1 and state == 'done', 'redelivery after commit must be a no-op: %s %d' % (state, attempt))
|
||||
return {'attachment_id': att['id'], 'job_id': jid, 'worker_restarts': int(restarts), 'attempt': attempt,
|
||||
'redelivery_acked_as_noop': noop, 'invariants': invariants(att['id'], chat['id'])}
|
||||
|
||||
|
||||
def scenario_broker_restart(c):
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
compose('stop', 'worker')
|
||||
att = upload(c, alice, chat, sample(), name='broker.png')
|
||||
jid, _, _ = job_of(att['id'])
|
||||
for _ in range(30):
|
||||
if psql("SELECT count(*) FROM outbox WHERE job_id='%s' AND published_at IS NOT NULL" % jid) == '1':
|
||||
break
|
||||
time.sleep(0.5)
|
||||
before = queues()
|
||||
compose('restart', 'rabbitmq')
|
||||
# Quorum-очередь после рестарта выбирает лидера и восстанавливает журнал: ждём.
|
||||
after = {}
|
||||
for _ in range(30):
|
||||
after = queues()
|
||||
if after.get('attachment.process', 0) >= 1:
|
||||
break
|
||||
time.sleep(1)
|
||||
sh('docker', 'start', compose('ps', '-aq', 'worker').stdout.split()[0]) # без запуска зависимостей
|
||||
wait_status(c, bob, att['id'], ('ready',))
|
||||
published = psql("SELECT publish_attempts FROM outbox WHERE job_id='%s'" % jid)
|
||||
check(after.get('attachment.process', 0) >= 1, 'message lost on broker restart: %s' % after)
|
||||
check(published == '1', 'message was republished from outbox (%s): not a broker durability proof' % published)
|
||||
return {'attachment_id': att['id'], 'queue_before_restart': before, 'queue_after_restart': after,
|
||||
'outbox_publish_attempts': int(published),
|
||||
'invariants': invariants(att['id'], chat['id'])}
|
||||
|
||||
|
||||
def scenario_transient(c):
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
worker_cid = compose('ps', '-q', 'worker').stdout.split()[0]
|
||||
s3_cid = compose('ps', '-q', 's3').stdout.split()[0]
|
||||
compose('stop', 'worker')
|
||||
att = upload(c, alice, chat, sample(), name='retry.png')
|
||||
jid, _, _ = job_of(att['id'])
|
||||
for _ in range(30):
|
||||
if psql("SELECT count(*) FROM outbox WHERE job_id='%s' AND published_at IS NOT NULL" % jid) == '1':
|
||||
break
|
||||
time.sleep(0.5)
|
||||
# Прямые docker stop/start: `docker compose start worker` поднял бы и S3
|
||||
# (worker → s3-init → s3), и временного отказа бы не было.
|
||||
sh('docker', 'stop', s3_cid)
|
||||
sh('docker', 'start', worker_cid)
|
||||
seen = []
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < 25:
|
||||
ev = events(jid) or ''
|
||||
seen = ev.split(',')
|
||||
if seen.count('retry_scheduled') >= 2:
|
||||
break
|
||||
time.sleep(1)
|
||||
sh('docker', 'start', s3_cid)
|
||||
meta = wait_status(c, bob, att['id'], ('ready',), timeout=150)
|
||||
_, state, attempt = job_of(att['id'])
|
||||
details = psql("SELECT string_agg(detail, ' | ' ORDER BY id) FROM job_events WHERE job_id='%s' AND event='retry_scheduled'" % jid)
|
||||
check(attempt >= 2 and state == 'done', 'expected retries then success: %s/%d events=%s' % (state, attempt, events(jid)))
|
||||
return {'attachment_id': att['id'], 'attempts': attempt, 'final_status': meta['status'],
|
||||
'retry_details': details, 'events': events(jid), 'invariants': invariants(att['id'], chat['id'])}
|
||||
|
||||
|
||||
def scenario_failed_replay(c):
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
compose('stop', 'worker')
|
||||
att = upload(c, alice, chat, sample(), name='bad.png')
|
||||
key = psql("SELECT staging_key FROM attachments WHERE id='%s'" % att['id'])
|
||||
mc('printf garbage > /tmp/g && mc cp -q /tmp/g s3/%s/%s >/dev/null' % (BUCKET, key)) # порча staging
|
||||
compose('start', 'worker')
|
||||
meta = wait_status(c, bob, att['id'], ('failed',))
|
||||
check(meta['error_code'] == 'checksum_mismatch', 'error_code %s' % meta['error_code'])
|
||||
c.call('GET', '/api/v1/attachments/%s/content' % att['id'], 409, actor=bob)
|
||||
c.call('POST', '/api/v1/chats/%s/messages' % chat['id'], 409, actor=alice,
|
||||
body={'text': '', 'attachment_ids': [att['id']]}, headers={'Idempotency-Key': 'f-' + att['id']})
|
||||
registry = compose('run', '--rm', '--no-deps', '-T', '--entrypoint', '/app/pipeline', 'relay', 'failed').stdout
|
||||
check(att['id'] in registry, 'failed registry must list the job')
|
||||
# Восстанавливаем исходник и делаем явный replay.
|
||||
import subprocess
|
||||
p = subprocess.run(['docker', 'compose', 'run', '--rm', '--no-deps', '-T', '--entrypoint', 'sh', 's3-init', '-c',
|
||||
'mc alias set s3 http://s3:9000 "$(cat /run/secrets/s3_root_user)" "$(cat /run/secrets/s3_root_password)" >/dev/null; '
|
||||
'cat > /tmp/o && mc cp -q /tmp/o s3/%s/%s >/dev/null' % (BUCKET, key)], input=sample(), capture_output=True)
|
||||
check(p.returncode == 0, 'restore staging failed')
|
||||
rp = compose('run', '--rm', '--no-deps', '-T', '--entrypoint', '/app/pipeline', 'relay', 'replay', att['id'],
|
||||
'--actor', 'lab5-test', check=False)
|
||||
check(rp.returncode == 0, 'replay failed: ' + rp.stdout + rp.stderr[-200:])
|
||||
ready = wait_status(c, bob, att['id'], ('ready',))
|
||||
again = compose('run', '--rm', '--no-deps', '-T', '--entrypoint', '/app/pipeline', 'relay', 'replay', att['id'],
|
||||
'--actor', 'lab5-test', check=False)
|
||||
check(again.returncode != 0, 'replay of a finished job must be refused')
|
||||
jid, _, attempt = job_of(att['id'])
|
||||
# Невалидное сообщение → DLQ (не крутится вечно, не теряется молча).
|
||||
psql("INSERT INTO outbox (job_id, payload) VALUES ('%s', '{\"schema_version\": 99}'::jsonb)" % jid)
|
||||
dead = 0
|
||||
for _ in range(30):
|
||||
dead = queues().get('attachment.dead', 0)
|
||||
if dead >= 1:
|
||||
break
|
||||
time.sleep(1)
|
||||
check(dead >= 1, 'invalid message did not reach DLQ')
|
||||
return {'attachment_id': att['id'], 'failed_error_code': meta['error_code'], 'content_while_failed': 409,
|
||||
'attach_failed_to_message': 409, 'registry_listed': True, 'replay': json.loads(rp.stdout.strip().splitlines()[-1]),
|
||||
'replay_after_success': json.loads(again.stdout.strip().splitlines()[-1]),
|
||||
'final_status': ready['status'], 'events': events(jid), 'dlq_messages': dead,
|
||||
'invariants': invariants(att['id'], chat['id'])}
|
||||
|
||||
|
||||
def solid_png(w, h, rgb=(40, 120, 200)):
|
||||
row = b'\x00' + bytes(rgb) * w
|
||||
raw = row * h
|
||||
ihdr = struct.pack('>IIBBBBB', w, h, 8, 2, 0, 0, 0)
|
||||
ch = lambda t, d: struct.pack('>I', len(d)) + t + d + struct.pack('>I', zlib.crc32(t + d) & 0xffffffff)
|
||||
return b'\x89PNG\r\n\x1a\n' + ch(b'IHDR', ihdr) + ch(b'IDAT', zlib.compress(raw, 9)) + ch(b'IEND', b'')
|
||||
|
||||
|
||||
def scenario_limits(c):
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
big = solid_png(6000, 6000) # 36 Мпикс, сжатый файл маленький
|
||||
check(len(big) < 10 * 1024 * 1024, 'test image too big')
|
||||
import threading
|
||||
compose('restart', 'worker') # новый cgroup → счётчики с нуля
|
||||
time.sleep(3)
|
||||
cid = compose('ps', '-q', 'worker').stdout.split()[0]
|
||||
|
||||
def cg(name):
|
||||
return sh('docker', 'exec', cid, 'cat', '/sys/fs/cgroup/' + name, check=False).stdout
|
||||
|
||||
anon_max = [0]
|
||||
stop = threading.Event()
|
||||
|
||||
def sampler():
|
||||
# memory.peak включает page cache (временные файлы cwebp и т. п.), поэтому
|
||||
# отдельно снимаем анонимную память процесса — её и ограничивает пиксельный бюджет.
|
||||
while not stop.is_set():
|
||||
for line in cg('memory.stat').splitlines():
|
||||
if line.startswith('anon '):
|
||||
anon_max[0] = max(anon_max[0], int(line.split()[1]))
|
||||
time.sleep(0.3)
|
||||
th = threading.Thread(target=sampler, daemon=True)
|
||||
th.start()
|
||||
t0 = time.time()
|
||||
ids = [upload(c, alice, chat, big, name='big%d.png' % i)['id'] for i in range(3)]
|
||||
done = [wait_status(c, bob, i, ('ready', 'failed'), timeout=240) for i in ids]
|
||||
took = time.time() - t0
|
||||
stop.set()
|
||||
th.join()
|
||||
peak = cg('memory.peak').strip()
|
||||
limit = cg('memory.max').strip()
|
||||
oom = {l.split()[0]: int(l.split()[1]) for l in cg('memory.events').splitlines() if len(l.split()) == 2}
|
||||
check(all(d['status'] == 'ready' for d in done), 'big images failed: %s' % [d['error_code'] for d in done])
|
||||
check(oom.get('oom_kill', 0) == 0, 'worker was OOM-killed')
|
||||
th = {v['name']: (v['width'], v['height']) for v in done[0]['variants']}
|
||||
check(th['thumbnail'] == (256, 256) and th['optimized'] == (1280, 1280), 'variant sizes %s' % th)
|
||||
return {'image': '6000x6000 PNG (%d bytes)' % len(big), 'parallel_uploads': 3, 'seconds_all_ready': round(took, 1),
|
||||
'worker_anon_memory_max_mib': round(anon_max[0] / 1048576, 1),
|
||||
'worker_memory_peak_incl_page_cache_mib': round(int(peak) / 1048576, 1) if peak.isdigit() else peak,
|
||||
'oom_kill_events': oom.get('oom_kill', 0),
|
||||
'go_memlimit': sh('docker', 'exec', cid, 'printenv', 'GOMEMLIMIT', check=False).stdout.strip(),
|
||||
'oom_events': oom.get('oom', 0),
|
||||
'worker_memory_limit_mib': round(int(limit) / 1048576, 1) if limit.isdigit() else limit,
|
||||
'pixel_budget': 60_000_000, 'decoded_rgba_per_image_mib': round(6000 * 6000 * 4 / 1048576, 1),
|
||||
'variant_sizes': th}
|
||||
|
||||
|
||||
# ---------------- трек 5: версии и устаревшие задания ----------------
|
||||
|
||||
def scenario_versions(c):
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
att = upload(c, alice, chat, sample(), name='ver.png')
|
||||
v1 = wait_status(c, bob, att['id'], ('ready',))
|
||||
th1 = {v['name']: v['sha256'] for v in v1['variants']}['thumbnail']
|
||||
jid1, _, _ = job_of(att['id'], 1)
|
||||
rp = compose('run', '--rm', '--no-deps', '-T', '--entrypoint', '/app/pipeline', 'relay', 'reprocess', att['id'], '--version', '2')
|
||||
jid2 = json.loads(rp.stdout.strip().splitlines()[-1])['job_id']
|
||||
for _ in range(120):
|
||||
if psql("SELECT pipeline_version FROM attachments WHERE id='%s'" % att['id']) == '2':
|
||||
break
|
||||
time.sleep(0.5)
|
||||
v2 = c.call('GET', '/api/v1/attachments/' + att['id'], actor=bob, schema='Attachment')['json']
|
||||
th2 = {v['name']: v['sha256'] for v in v2['variants']}['thumbnail']
|
||||
check(v2['status'] == 'ready' and th2 != th1, 'v2 must be published with a different thumbnail')
|
||||
# Устаревший дубль v1 и повтор v2 после публикации v2.
|
||||
psql("INSERT INTO outbox (job_id, payload) SELECT job_id, payload FROM outbox WHERE job_id='%s' ORDER BY id LIMIT 1" % jid1)
|
||||
psql("INSERT INTO outbox (job_id, payload) SELECT job_id, payload FROM outbox WHERE job_id='%s' ORDER BY id LIMIT 1" % jid2)
|
||||
time.sleep(6)
|
||||
after = c.call('GET', '/api/v1/attachments/' + att['id'], actor=bob, schema='Attachment')['json']
|
||||
th_after = {v['name']: v['sha256'] for v in after['variants']}['thumbnail']
|
||||
got = c.call('GET', '/api/v1/attachments/%s/content?variant=thumbnail' % att['id'], actor=bob)['bytes']
|
||||
check(th_after == th2 and hashlib.sha256(got).hexdigest() == th2, 'stale v1 overwrote v2')
|
||||
check(psql("SELECT pipeline_version FROM attachments WHERE id='%s'" % att['id']) == '2', 'version went back')
|
||||
_, s1, a1 = job_of(att['id'], 1)
|
||||
_, s2, a2 = job_of(att['id'], 2)
|
||||
check(a1 == 1 and a2 == 1, 'duplicates must not start new attempts')
|
||||
return {'attachment_id': att['id'], 'v1_thumbnail_sha': th1, 'v2_thumbnail_sha': th2,
|
||||
'after_stale_v1_and_dup_v2': th_after, 'published_version': 2,
|
||||
'jobs': {'v1': {'state': s1, 'attempt': a1, 'events': events(jid1)},
|
||||
'v2': {'state': s2, 'attempt': a2, 'events': events(jid2)}},
|
||||
'invariants': invariants(att['id'], chat['id'])}
|
||||
|
||||
|
||||
SCENARIOS = {'demo': scenario_demo, 'outbox-gap': scenario_outbox_gap, 'crash-effect': scenario_crash_effect,
|
||||
'crash-commit': scenario_crash_commit, 'broker-restart': scenario_broker_restart,
|
||||
'transient': scenario_transient, 'failed-replay': scenario_failed_replay,
|
||||
'limits': scenario_limits, 'versions': scenario_versions}
|
||||
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument('scenario', choices=sorted(SCENARIOS))
|
||||
p.add_argument('--output', default=None)
|
||||
args = arguments('Lab5 pipeline scenarios on the Docker stand', configure)
|
||||
c = Client(args.base_url, args.ca_file, timeout=60)
|
||||
drain()
|
||||
try:
|
||||
result = SCENARIOS[args.scenario](c)
|
||||
finally:
|
||||
# Сценарий мог остановить сервисы или включить точки сбоя: возвращаем штатную конфигурацию.
|
||||
compose('up', '-d', '--no-deps', '--wait', 'worker', 'relay', 'rabbitmq', 's3', 'api', timeout=300, check=False)
|
||||
text = json.dumps({'scenario': args.scenario, 'result': result}, ensure_ascii=False, indent=2)
|
||||
if args.output:
|
||||
open(args.output, 'w', encoding='utf-8').write(text + '\n')
|
||||
print(text)
|
||||
print('PASS: ' + args.scenario)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,89 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Трек 2: стоимость обхода reconciler в зависимости от числа вложений.
|
||||
|
||||
Для каждого N: досеиваем согласованные пары (строка в PostgreSQL + объект в S3)
|
||||
под отдельным префиксом чата-стенда, затем 3 раза запускаем dry-run и берём
|
||||
медиану duration_ms. Фиксируем число строк/объектов, LIST-страниц, Stat-вызовов
|
||||
и heap процесса reconciler. Дополнительно — прогон с 1% внедрённых расхождений.
|
||||
|
||||
Объекты — 1 KiB случайных байт (размер не влияет на обход: LIST возвращает
|
||||
метаданные, тела объектов не читаются).
|
||||
"""
|
||||
import json
|
||||
import statistics
|
||||
import time
|
||||
import uuid
|
||||
from labutil import BUCKET, compose, mc, psql
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def reconcile_dry():
|
||||
for _ in range(10):
|
||||
r = compose('run', '--rm', '--no-deps', '-T', '--entrypoint', '/app/reconcile', 'reconciler',
|
||||
'--grace', '1h', check=False, timeout=900)
|
||||
if r.returncode == 3:
|
||||
time.sleep(2)
|
||||
continue
|
||||
check(r.returncode in (0, 4), 'reconcile failed: ' + r.stderr[-300:])
|
||||
return json.loads(r.stdout.strip().splitlines()[-1])
|
||||
raise RuntimeError('lock busy')
|
||||
|
||||
|
||||
def seed(chat_id, owner_id, start, count):
|
||||
"""count согласованных пар с ключами a/<chat>/bench-<номер>."""
|
||||
# Объекты: генерируем count файлов в контейнере mc и заливаем одним mirror.
|
||||
mc('mkdir -p /tmp/b && head -c 1024 /dev/urandom > /tmp/one && i=%d; while [ $i -lt %d ]; do '
|
||||
'cp /tmp/one /tmp/b/bench-$(printf %%07d $i); i=$((i+1)); done && '
|
||||
'mc mirror -q --overwrite /tmp/b s3/%s/a/%s/ >/dev/null' % (start, start + count, BUCKET, chat_id))
|
||||
psql("INSERT INTO attachments (id, chat_id, owner_id, filename, object_key, status, content_type, size_bytes, sha256) "
|
||||
"SELECT gen_random_uuid(), '%s', '%s', 'b.png', 'a/%s/bench-' || lpad(g::text, 7, '0'), 'ready', "
|
||||
"'image/png', 1024, repeat('a', 64) FROM generate_series(%d, %d) g"
|
||||
% (chat_id, owner_id, chat_id, start, start + count - 1))
|
||||
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument('--sizes', default='1000,10000,30000')
|
||||
p.add_argument('--output', default=None)
|
||||
args = arguments('Reconciler traversal cost (lab4 track 2)', configure)
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, _, _, chat = c.bootstrap()
|
||||
total_existing = int(psql('SELECT count(*) FROM attachments'))
|
||||
sizes = [int(x) for x in args.sizes.split(',')]
|
||||
seeded, runs = 0, []
|
||||
for n in sizes:
|
||||
t0 = time.time()
|
||||
seed(chat['id'], alice['id'], seeded, n - seeded)
|
||||
seed_s = time.time() - t0
|
||||
seeded = n
|
||||
reps = [reconcile_dry() for _ in range(3)]
|
||||
ms = [r['duration_ms'] for r in reps]
|
||||
r = reps[-1]
|
||||
runs.append({'bench_pairs': n, 'rows_scanned': r['rows_scanned'], 'objects_scanned': r['objects_scanned'],
|
||||
'duration_ms_runs': ms, 'duration_ms_median': statistics.median(ms),
|
||||
'us_per_pair': round(1000 * statistics.median(ms) / max(1, r['rows_scanned']), 1),
|
||||
'calls': r['calls'], 'heap_alloc_mb': r['heap_alloc_mb'], 'found': r['found'],
|
||||
'wait_ms_runs': [x.get('wait_ms') for x in reps],
|
||||
'seed_seconds': round(seed_s, 1)})
|
||||
print(json.dumps(runs[-1], ensure_ascii=False))
|
||||
# 1% расхождений на самом большом наборе: удалённые объекты и сироты.
|
||||
k = max(1, sizes[-1] // 100)
|
||||
mc('i=0; while [ $i -lt %d ]; do mc rm -q s3/%s/a/%s/bench-$(printf %%07d $((i*97 %% %d))) >/dev/null 2>&1; i=$((i+1)); done'
|
||||
% (k // 2, BUCKET, chat['id'], sizes[-1]))
|
||||
mc('head -c 512 /dev/urandom > /tmp/o && i=0; while [ $i -lt %d ]; do mc cp -q /tmp/o s3/%s/a/%s/zz-orphan-$i >/dev/null; i=$((i+1)); done'
|
||||
% (k - k // 2, BUCKET, chat['id']))
|
||||
faulty = reconcile_dry()
|
||||
out = {'preexisting_rows': total_existing, 'object_size_bytes': 1024, 'runs': runs,
|
||||
'with_1pct_faults': {'injected_missing': k // 2, 'injected_orphans': k - k // 2,
|
||||
'duration_ms': faulty['duration_ms'], 'found': faulty['found'],
|
||||
'skipped': faulty['skipped'], 'calls': faulty['calls']},
|
||||
'note': 'dry-run, grace 1h: свежие сироты учитываются как skipped.fresh_object, а не удаляются'}
|
||||
text = json.dumps(out, ensure_ascii=False, indent=2)
|
||||
if args.output:
|
||||
open(args.output, 'w', encoding='utf-8').write(text + '\n')
|
||||
print(text)
|
||||
print('PASS: reconciler cost measured for %s pairs' % sizes)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,175 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Трек 2: внедрение расхождений PostgreSQL↔S3 и проверка reconciler.
|
||||
|
||||
Сценарий (Docker-стенд, reconciler запускается одноразово через docker compose run):
|
||||
1. Через API: чат, 6 вложений, два из них прикреплены к сообщениям.
|
||||
2. Внедряем ошибки с обеих сторон:
|
||||
S3: сирота (объект без строки, старый), сирота свежая (моложе grace),
|
||||
удалённый объект используемого и неиспользуемого вложения,
|
||||
объект с подменённым размером;
|
||||
БД: брошенное намерение с объектом и без, свежее намерение (загрузка «идёт»).
|
||||
3. dry-run: всё найдено, ничего не изменено (снимки БД и S3 совпадают).
|
||||
4. apply: исправлено; свежие и используемые не тронуты; API: здоровые вложения
|
||||
скачиваются байт-в-байт, потерянные отвечают 503, сообщение сохраняет attachment_ids.
|
||||
5. Повторный apply — ничего не исправляет (идемпотентность).
|
||||
6. Объект «восстановлен из бэкапа» → apply снимает карантин, скачивание снова работает.
|
||||
7. После grace: неиспользуемая запись карантина удаляется, используемая остаётся;
|
||||
свежая сирота, ставшая старой, удаляется.
|
||||
|
||||
Grace в тесте — 8 s (--unsafe-short-grace); «старые» строки сдвинуты на 30 минут
|
||||
назад, поэтому фоновый reconciler стенда (grace 1h) их не трогает.
|
||||
"""
|
||||
import json
|
||||
import time
|
||||
import uuid
|
||||
from labutil import BUCKET, compose, fixture, mc, noise_png, object_key, psql, wait_status
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
GRACE = '8s'
|
||||
|
||||
|
||||
def reconcile(*flags):
|
||||
for _ in range(10):
|
||||
r = compose('run', '--rm', '--no-deps', '-T', '--entrypoint', '/app/reconcile', 'reconciler',
|
||||
'--grace', GRACE, '--unsafe-short-grace', *flags, check=False)
|
||||
if r.returncode == 3: # фоновый reconciler держит advisory lock
|
||||
time.sleep(2)
|
||||
continue
|
||||
check(r.returncode in (0, 4), 'reconcile failed: ' + r.stderr[-400:])
|
||||
return json.loads(r.stdout.strip().splitlines()[-1])
|
||||
raise RuntimeError('reconciler lock busy')
|
||||
|
||||
|
||||
def snapshot(chat_id):
|
||||
rows = psql("SELECT id || ':' || status || ':' || COALESCE(size_bytes, 0) FROM attachments "
|
||||
"WHERE chat_id = '%s' ORDER BY id" % chat_id)
|
||||
objs = mc('mc ls --recursive --json s3/%s/a/%s/' % (BUCKET, chat_id)).stdout
|
||||
# mc ls --json отдаёт key относительно листинга — дополняем до полного ключа.
|
||||
keys = sorted(('a/%s/%s' % (chat_id, json.loads(l)['key']), json.loads(l)['size'])
|
||||
for l in objs.splitlines() if l.strip() and 'key' in json.loads(l))
|
||||
return rows, keys
|
||||
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument('--output', default=None)
|
||||
args = arguments('Reconciler fault injection (lab4 track 2)', configure)
|
||||
c = Client(args.base_url, args.ca_file, timeout=30)
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
cid = chat['id']
|
||||
def up(data):
|
||||
a = c.call('POST', '/api/v1/chats/%s/attachments?filename=r.png' % cid, 202, actor=alice,
|
||||
raw=data, headers={'Content-Type': 'image/png'}, schema='Attachment')['json']
|
||||
return wait_status(c, alice, a['id'], ('ready',))
|
||||
datas = [noise_png(20_000 + i * 1000) for i in range(6)]
|
||||
ok, lost_used, lost_free, resized, keep_used, restore_me = [up(d) for d in datas]
|
||||
for att in (lost_used, keep_used, restore_me):
|
||||
c.message(alice, chat, 'с вложением', attachments=[att['id']])
|
||||
|
||||
# --- внедрение ошибок ---
|
||||
tmp = '/tmp/f.bin'
|
||||
put = 'head -c %d /dev/urandom > ' + tmp + ' && mc cp -q ' + tmp + ' s3/' + BUCKET + '/%s >/dev/null'
|
||||
orphan_old = 'a/%s/%s' % (cid, uuid.uuid4())
|
||||
orphan_fresh = 'a/%s/%s' % (cid, uuid.uuid4())
|
||||
stale_with = str(uuid.uuid4())
|
||||
stale_without = str(uuid.uuid4())
|
||||
inflight = str(uuid.uuid4())
|
||||
mc(' && '.join([
|
||||
put % (5000, orphan_old),
|
||||
'mc rm -q s3/%s/%s' % (BUCKET, object_key(lost_used['id'])),
|
||||
'mc rm -q s3/%s/%s' % (BUCKET, object_key(lost_free['id'])),
|
||||
'mc rm -q s3/%s/%s' % (BUCKET, object_key(restore_me['id'])),
|
||||
put % (777, object_key(resized['id'])),
|
||||
put % (4000, 'a/%s/%s' % (cid, stale_with)),
|
||||
put % (4000, 'a/%s/%s' % (cid, inflight)),
|
||||
]))
|
||||
for aid, age in ((stale_with, "now() - interval '30 minutes'"), (stale_without, "now() - interval '30 minutes'"),
|
||||
(inflight, 'now()')):
|
||||
psql("INSERT INTO attachments (id, chat_id, owner_id, filename, object_key, status, created_at, updated_at) "
|
||||
"VALUES ('%s', '%s', '%s', 'x.png', 'a/%s/%s', 'uploading', %s, %s)" % (aid, cid, alice['id'], cid, aid, age, age))
|
||||
time.sleep(9) # «старые» объекты стали старше grace
|
||||
mc(put % (3000, orphan_fresh)) # а эта сирота — свежая
|
||||
psql("UPDATE attachments SET updated_at = now() WHERE id = '%s'" % inflight) # загрузка «продолжается»
|
||||
|
||||
# --- dry-run ---
|
||||
before = snapshot(cid)
|
||||
dry = reconcile()
|
||||
check(snapshot(cid) == before, 'dry-run changed state')
|
||||
mine = lambda rep, kind: [i for i in rep['items'] if i['kind'] == kind and cid in i['key']]
|
||||
expect = {'orphan_object': 1, 'stale_intent': 2, 'missing_object': 3, 'size_mismatch': 1}
|
||||
for kind, n in expect.items():
|
||||
check(len(mine(dry, kind)) == n, 'dry-run %s: %d, want %d' % (kind, len(mine(dry, kind)), n))
|
||||
check(all(i['action'].startswith('would_') for i in dry['items'] if cid in i['key']), 'dry-run planned real actions')
|
||||
|
||||
# --- apply ---
|
||||
applied = reconcile('--apply')
|
||||
rows, keys = snapshot(cid)
|
||||
status = {r.split(':')[0]: r.split(':')[1] for r in rows.splitlines()}
|
||||
key_set = {k for k, _ in keys}
|
||||
check(stale_with not in status and stale_without not in status, 'stale intents not removed')
|
||||
check('a/%s/%s' % (cid, stale_with) not in key_set, 'stale intent object not removed')
|
||||
check(orphan_old not in key_set, 'old orphan not removed')
|
||||
check(orphan_fresh in key_set, 'FRESH orphan was deleted')
|
||||
check(status.get(inflight) == 'uploading' and 'a/%s/%s' % (cid, inflight) in key_set, 'IN-FLIGHT upload touched')
|
||||
for att in (lost_used, lost_free, restore_me, resized):
|
||||
check(status.get(att['id']) == 'missing', '%s not quarantined' % att['id'])
|
||||
check(status.get(ok['id']) == 'ready' and status.get(keep_used['id']) == 'ready', 'healthy rows touched')
|
||||
# API после исправления
|
||||
for att, data in ((ok, datas[0]), (keep_used, datas[4])):
|
||||
d = c.call('GET', '/api/v1/attachments/%s/content' % att['id'], actor=bob)
|
||||
check(d['bytes'] == data, 'healthy attachment changed')
|
||||
c.call('GET', '/api/v1/attachments/%s' % lost_used['id'], 503, actor=bob)
|
||||
c.call('GET', '/api/v1/attachments/%s/content' % lost_used['id'], 503, actor=bob)
|
||||
hist = c.call('GET', '/api/v1/chats/%s/messages?limit=100' % cid, actor=bob, schema='MessagePage')['json']['items']
|
||||
check(any(lost_used['id'] in m['attachment_ids'] for m in hist), 'message lost its attachment reference')
|
||||
c.call('POST', '/api/v1/chats/%s/messages' % cid, 409, actor=alice, body={'text': '', 'attachment_ids': [lost_free['id']]},
|
||||
headers={'Idempotency-Key': uuid.uuid4().hex})
|
||||
|
||||
# --- идемпотентность ---
|
||||
again = reconcile('--apply')
|
||||
check(not [i for i in again['items'] if cid in i['key']], 'second apply changed something: %s' % [i for i in again['items'] if cid in i['key']])
|
||||
|
||||
# --- восстановление объекта ---
|
||||
with_data = datas[5]
|
||||
open_key = object_key(restore_me['id'])
|
||||
# Восстанавливаем исходные байты («из бэкапа») через stdin контейнера mc.
|
||||
import subprocess
|
||||
p = subprocess.run(['docker', 'compose', 'run', '--rm', '--no-deps', '-T', '--entrypoint', 'sh', 's3-init', '-c',
|
||||
'mc alias set s3 http://s3:9000 "$(cat /run/secrets/s3_root_user)" "$(cat /run/secrets/s3_root_password)" >/dev/null; '
|
||||
'cat > /tmp/r.png && mc cp -q /tmp/r.png s3/%s/%s >/dev/null' % (BUCKET, open_key)],
|
||||
input=with_data, capture_output=True)
|
||||
check(p.returncode == 0, 'restore put failed')
|
||||
restored = reconcile('--apply')
|
||||
check(len(mine(restored, 'restored')) == 1, 'restore not detected')
|
||||
d = c.call('GET', '/api/v1/attachments/%s/content' % restore_me['id'], actor=bob)
|
||||
check(d['bytes'] == with_data, 'restored attachment bytes differ')
|
||||
|
||||
# --- после grace ---
|
||||
time.sleep(9)
|
||||
late = reconcile('--apply')
|
||||
rows, keys = snapshot(cid)
|
||||
status = {r.split(':')[0]: r.split(':')[1] for r in rows.splitlines()}
|
||||
check(lost_free['id'] not in status, 'unreferenced quarantined row not purged after grace')
|
||||
check(resized['id'] not in status or status[resized['id']] == 'missing', 'resized row state')
|
||||
check(status.get(lost_used['id']) == 'missing', 'REFERENCED quarantined row deleted')
|
||||
check(orphan_fresh not in {k for k, _ in keys}, 'orphan not removed after grace')
|
||||
|
||||
summary = {
|
||||
'injected': {'orphan_old': 1, 'orphan_fresh': 1, 'deleted_objects': 3, 'resized_object': 1,
|
||||
'stale_intents': 2, 'inflight_intent': 1},
|
||||
'dry_run_found': {k: len(mine(dry, k)) for k in expect}, 'dry_run_state_changed': False,
|
||||
'apply_found': {k: len(mine(applied, k)) for k in expect},
|
||||
'second_apply_actions': 0, 'restored': 1,
|
||||
'after_grace': {k: len(mine(late, k)) for k in ('purge_missing', 'orphan_object')},
|
||||
'never_deleted': ['fresh orphan (until grace)', 'in-flight intent', 'referenced quarantined row', 'healthy rows'],
|
||||
'reports': {'dry_run': dry, 'apply': applied, 'second_apply': again, 'restore': restored, 'after_grace': late},
|
||||
}
|
||||
text = json.dumps(summary, ensure_ascii=False, indent=2)
|
||||
if args.output:
|
||||
open(args.output, 'w', encoding='utf-8').write(text + '\n')
|
||||
print(json.dumps({k: v for k, v in summary.items() if k != 'reports'}, ensure_ascii=False, indent=2))
|
||||
print('PASS: reconciler detected and safely fixed faults on both sides; dry-run and repeat are safe')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,81 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Регрессии по замечаниям проверки lab3.
|
||||
|
||||
1. Видимость подтверждённой записи при отказе Redis в командах инвалидации:
|
||||
чат с двумя сообщениями → закэшировать историю → в Redis запретить команды
|
||||
через ACL (сначала только INCR, затем INCR+DEL+UNLINK+SCAN) → отправить
|
||||
третье сообщение → каждое следующее чтение через LB обязано вернуть его.
|
||||
2. Пароль из одних пробельных символов при регистрации → 400.
|
||||
|
||||
Нужен запущенный Docker-стенд (redis-cli вызывается через docker compose exec).
|
||||
ACL всегда восстанавливается в finally. --only cache|password запускает одну часть.
|
||||
"""
|
||||
import subprocess
|
||||
import sys
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests')) # публичный client.py
|
||||
from client import Client, arguments, check, run
|
||||
from resilience import history
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
WHITESPACE_PASSWORDS = (' ' * 12, '\t' * 12, ' ' * 8)
|
||||
|
||||
|
||||
def redis_cli(*args):
|
||||
r = subprocess.run(['docker', 'compose', 'exec', '-T', 'redis', 'redis-cli', *args],
|
||||
cwd=ROOT, capture_output=True, text=True, timeout=30)
|
||||
check(r.returncode == 0, 'redis-cli failed: ' + r.stderr.strip())
|
||||
return r.stdout.strip()
|
||||
|
||||
|
||||
def visibility_case(c, alice, bob, chat, denied):
|
||||
path = '/api/v1/chats/' + chat['id'] + '/messages?limit=50'
|
||||
before = [m['id'] for m in history(c, bob, chat)]
|
||||
# Прогреваем кэш на обеих репликах.
|
||||
for _ in range(4):
|
||||
c.call('GET', path, actor=bob, schema='MessagePage')
|
||||
redis_cli('ACL', 'SETUSER', 'default', *('-' + cmd for cmd in denied))
|
||||
try:
|
||||
sent = c.message(alice, chat, 'после запрета ' + '+'.join(denied))['json']
|
||||
# Каждое следующее чтение (через любую реплику) видит подтверждённую запись.
|
||||
for i in range(6):
|
||||
page = c.call('GET', path, actor=bob, schema='MessagePage')
|
||||
ids = [m['id'] for m in page['json']['items']]
|
||||
check(sent['id'] in ids, 'read %d after 201 misses confirmed message (denied: %s)' % (i, denied))
|
||||
# Порядок (created_at до секунды, id): новое сообщение той же секунды может
|
||||
# встать раньше старых, поэтому проверяем наличие, а не префикс.
|
||||
check(set(before) <= set(ids), 'previously confirmed messages missing')
|
||||
finally:
|
||||
# reset — чтобы снять и точечные запреты, независимо от порядка правил.
|
||||
redis_cli('ACL', 'SETUSER', 'default', 'reset', 'on', 'nopass', '~*', '&*', '+@all')
|
||||
return len(before) + 1
|
||||
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument('--only', choices=['password', 'cache'], default=None)
|
||||
args = arguments('Regression checks for lab3 review findings', configure)
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
|
||||
# 2. Пароль из пробельных символов (пробелы, табуляции, неразрывные пробелы).
|
||||
if args.only in (None, 'password'):
|
||||
for pw in WHITESPACE_PASSWORDS:
|
||||
c.call('POST', '/api/v1/users', 400,
|
||||
body={'username': 'ws_' + uuid.uuid4().hex[:10], 'display_name': 'WS', 'password': pw})
|
||||
print('PASS: whitespace-only password rejected with 400 (3 variants)')
|
||||
if args.only == 'password':
|
||||
return
|
||||
|
||||
# 1. Видимость записи при отказе Redis.
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
c.message(alice, chat, 'первое')
|
||||
c.message(bob, chat, 'второе')
|
||||
n = visibility_case(c, alice, bob, chat, ['incr'])
|
||||
print('PASS: Redis ACL -incr: message visible on every next read (%d in history)' % n)
|
||||
n = visibility_case(c, alice, bob, chat, ['incr', 'del', 'unlink', 'scan'])
|
||||
print('PASS: Redis ACL -incr -del -unlink -scan: message visible on every next read (%d in history)' % n)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,221 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Трек 1 lab6: цена наблюдаемости.
|
||||
|
||||
Конфигурации (одинаковая нагрузка, одинаковые лимиты контейнеров):
|
||||
off OTEL_SDK_DISABLED=true — SDK не экспортирует ничего (stdout-логи остаются)
|
||||
full трассы 100% (parentbased_always_on), Collector пропускает всё
|
||||
head10 head sampling в SDK: parentbased_traceidratio 0.1
|
||||
tail SDK 100% → Collector tail_sampling: ошибки + медленные (≥250 ms) + 10% остальных
|
||||
(infra/otel/collector-tail.yaml) — предлагаемая сбалансированная конфигурация
|
||||
|
||||
Прогон: пересоздание api/relay/worker/collector с конфигурацией → прогрев 10 s →
|
||||
45 s closed-loop POST сообщений (4 клиента) с двумя внедрёнными инцидентами
|
||||
(LOCK TABLE messages на 6.5 s: часть запросов падает по таймауту 5 s = ошибки,
|
||||
часть ждёт = редкие медленные). Каждый запрос несёт X-Request-Id; после прогона по
|
||||
Tempo проверяется, сохранилась ли трасса каждой ошибки, каждого медленного и
|
||||
выборки обычных запросов. Ресурсы — cgroup контейнеров (cpu.stat, memory.peak),
|
||||
объём ingest — счётчики Collector/Tempo/Loki/Prometheus. 3 повтора, порядок
|
||||
конфигураций чередуется.
|
||||
"""
|
||||
import json
|
||||
import random
|
||||
import statistics
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
from client import Client, arguments, check, run
|
||||
from labutil import ROOT, compose
|
||||
from loadgen import Load
|
||||
import obsutil as o
|
||||
|
||||
CONFIGS = {
|
||||
'off': {'OTEL_SDK_DISABLED': 'true', 'OTEL_TRACES_SAMPLER': 'parentbased_always_on', 'OTEL_TRACES_SAMPLER_ARG': '1.0',
|
||||
'COLLECTOR_CONFIG': 'collector.yaml'},
|
||||
'full': {'OTEL_SDK_DISABLED': 'false', 'OTEL_TRACES_SAMPLER': 'parentbased_always_on', 'OTEL_TRACES_SAMPLER_ARG': '1.0',
|
||||
'COLLECTOR_CONFIG': 'collector.yaml'},
|
||||
'head10': {'OTEL_SDK_DISABLED': 'false', 'OTEL_TRACES_SAMPLER': 'parentbased_traceidratio', 'OTEL_TRACES_SAMPLER_ARG': '0.1',
|
||||
'COLLECTOR_CONFIG': 'collector.yaml'},
|
||||
'tail': {'OTEL_SDK_DISABLED': 'false', 'OTEL_TRACES_SAMPLER': 'parentbased_always_on', 'OTEL_TRACES_SAMPLER_ARG': '1.0',
|
||||
'COLLECTOR_CONFIG': 'collector-tail.yaml'},
|
||||
}
|
||||
COUNTERS = {
|
||||
'spans_received': 'sum(otelcol_receiver_accepted_spans_total)',
|
||||
'spans_exported': 'sum(otelcol_exporter_sent_spans_total)',
|
||||
'log_records_received': 'sum(otelcol_receiver_accepted_log_records_total)',
|
||||
'metric_points_received': 'sum(otelcol_receiver_accepted_metric_points_total)',
|
||||
'tempo_bytes': 'sum(tempo_distributor_bytes_received_total)',
|
||||
'loki_bytes': 'sum(loki_distributor_bytes_received_total)',
|
||||
'prometheus_samples': 'sum(prometheus_tsdb_head_samples_appended_total)',
|
||||
}
|
||||
DURATION, WARMUP, CONC = 45, 10, 4
|
||||
LOCKS = (12, 28) # секунда прогона, когда начинается блокировка
|
||||
LOCK_SECONDS = 6.5
|
||||
SLOW = 0.25
|
||||
|
||||
|
||||
def apply(name):
|
||||
env = dict(CONFIGS[name])
|
||||
compose('up', '-d', '--no-deps', '--wait', 'otel-collector', 'api', 'relay', 'worker', env=env, timeout=300)
|
||||
|
||||
|
||||
def wait_api(c, timeout=120):
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
try:
|
||||
c.call('GET', '/health/ready')
|
||||
return
|
||||
except Exception:
|
||||
time.sleep(1)
|
||||
raise RuntimeError('api not ready')
|
||||
|
||||
|
||||
def counters():
|
||||
return {k: o.prom_value(q, default=0.0) for k, q in COUNTERS.items()}
|
||||
|
||||
|
||||
def containers(service):
|
||||
return compose('ps', '-q', service).stdout.split()
|
||||
|
||||
|
||||
def lock(seconds):
|
||||
return subprocess.Popen(['docker', 'compose', 'exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-c',
|
||||
'BEGIN; LOCK TABLE messages IN ACCESS EXCLUSIVE MODE; SELECT pg_sleep(%s); COMMIT;' % seconds],
|
||||
cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def traced(rid, since):
|
||||
return bool(o.tempo_search('{span.request_id="%s"}' % rid, since, limit=1))
|
||||
|
||||
|
||||
def one_run(c, name, actor, chat, rnd):
|
||||
apply(name)
|
||||
wait_api(c)
|
||||
warm =Load(c.base, None, actor, chat, concurrency=CONC, timeout=10, prefix='warm-%s' % name).start()
|
||||
time.sleep(WARMUP)
|
||||
warm.stop()
|
||||
time.sleep(6)
|
||||
api = containers('api')
|
||||
col = containers('otel-collector')
|
||||
cpu0 = {cid: o.cpu_usec(cid) for cid in api + col}
|
||||
c0 = counters()
|
||||
t_start = time.time()
|
||||
load = Load(c.base, None, actor, chat, concurrency=CONC, timeout=10, prefix='tc-%s-%d' % (name, rnd)).start()
|
||||
windows, procs = [], []
|
||||
for at in LOCKS:
|
||||
time.sleep(max(0, t_start + at - time.time()))
|
||||
procs.append(lock(LOCK_SECONDS))
|
||||
windows.append((time.time(), time.time() + LOCK_SECONDS + 5.5))
|
||||
time.sleep(max(0, t_start + DURATION - time.time()))
|
||||
load.stop()
|
||||
for p in procs:
|
||||
p.wait(timeout=60)
|
||||
elapsed = time.time() - t_start
|
||||
cpu1 = {cid: o.cpu_usec(cid) for cid in api + col}
|
||||
time.sleep(15) # tail decision_wait 5 s + batch + экспорт метрик + scrape
|
||||
c1 = counters()
|
||||
s = load.summary(exclude=windows)
|
||||
recs = load.records
|
||||
errors = [r for r in recs if r[3] != 201]
|
||||
slow = [r for r in recs if r[3] == 201 and r[2] >= SLOW]
|
||||
normal = [r for r in recs if r[3] == 201 and r[2] < SLOW]
|
||||
random.seed(rnd * 7 + len(name))
|
||||
sample = random.sample(normal, min(40, len(normal)))
|
||||
kept = {}
|
||||
if name != 'off':
|
||||
for label, group in (('errors', errors[:40]), ('slow', slow[:40]), ('normal_sample', sample)):
|
||||
kept[label] = [sum(traced(r[0], t_start - 5) for r in group), len(group)]
|
||||
else:
|
||||
kept = {'errors': [0, len(errors)], 'slow': [0, len(slow)], 'normal_sample': [0, len(sample)]}
|
||||
|
||||
def cores(ids):
|
||||
tot = sum((cpu1[i] - cpu0[i]) for i in ids if cpu0.get(i) is not None and cpu1.get(i) is not None)
|
||||
return round(tot / 1e6 / elapsed, 3)
|
||||
ok = s['ok'] or 1
|
||||
delta = {k: round(c1[k] - c0[k]) for k in COUNTERS}
|
||||
return {
|
||||
'config': name, 'round': rnd, 'load': s, 'slow_requests': len(slow), 'error_requests': len(errors),
|
||||
'traces_kept': kept,
|
||||
'api_cpu_cores': cores(api), 'api_cpu_ms_per_request': round(sum(
|
||||
(cpu1[i] - cpu0[i]) for i in api if cpu0.get(i) is not None) / 1e3 / ok, 3),
|
||||
'api_mem_peak_mib': [round((o.mem_bytes(i, 'memory.peak') or 0) / 2**20, 1) for i in api],
|
||||
'api_mem_now_mib': [round((o.mem_bytes(i) or 0) / 2**20, 1) for i in api],
|
||||
'collector_cpu_cores': cores(col),
|
||||
'collector_mem_peak_mib': [round((o.mem_bytes(i, 'memory.peak') or 0) / 2**20, 1) for i in col],
|
||||
'ingest_delta': delta,
|
||||
'ingest_per_1000_requests': {k: round(v * 1000 / ok, 1) for k, v in delta.items()},
|
||||
}
|
||||
|
||||
|
||||
def aggregate(runs):
|
||||
out = {}
|
||||
for name in CONFIGS:
|
||||
rs = [r for r in runs if r['config'] == name]
|
||||
if not rs:
|
||||
continue
|
||||
med = lambda f: round(statistics.median(f(r) for r in rs), 3)
|
||||
|
||||
def kept(label):
|
||||
k = sum(r['traces_kept'][label][0] for r in rs)
|
||||
n = sum(r['traces_kept'][label][1] for r in rs)
|
||||
return {'kept': k, 'total': n, 'ratio': round(k / n, 3) if n else None}
|
||||
out[name] = {
|
||||
'runs': len(rs),
|
||||
'ok_rps_median': med(lambda r: r['load']['ok_rps']),
|
||||
'p50_ms_median': med(lambda r: r['load']['latency_ms_outside_faults']['p50']),
|
||||
'p95_ms_median': med(lambda r: r['load']['latency_ms_outside_faults']['p95']),
|
||||
'p99_ms_median': med(lambda r: r['load']['latency_ms_outside_faults']['p99']),
|
||||
'errors_total': sum(r['error_requests'] for r in rs),
|
||||
'slow_total': sum(r['slow_requests'] for r in rs),
|
||||
'api_cpu_cores_median': med(lambda r: r['api_cpu_cores']),
|
||||
'api_cpu_ms_per_request_median': med(lambda r: r['api_cpu_ms_per_request']),
|
||||
'api_mem_peak_mib_median': med(lambda r: max(r['api_mem_peak_mib'] or [0])),
|
||||
'collector_cpu_cores_median': med(lambda r: r['collector_cpu_cores']),
|
||||
'collector_mem_peak_mib_median': med(lambda r: max(r['collector_mem_peak_mib'] or [0])),
|
||||
'spans_received_per_1000_req': med(lambda r: r['ingest_per_1000_requests']['spans_received']),
|
||||
'spans_exported_per_1000_req': med(lambda r: r['ingest_per_1000_requests']['spans_exported']),
|
||||
'tempo_kib_per_1000_req': med(lambda r: r['ingest_per_1000_requests']['tempo_bytes'] / 1024),
|
||||
'loki_kib_per_1000_req': med(lambda r: r['ingest_per_1000_requests']['loki_bytes'] / 1024),
|
||||
'log_records_per_1000_req': med(lambda r: r['ingest_per_1000_requests']['log_records_received']),
|
||||
'metric_points_per_1000_req': med(lambda r: r['ingest_per_1000_requests']['metric_points_received']),
|
||||
'traces_kept_errors': kept('errors'), 'traces_kept_slow': kept('slow'),
|
||||
'traces_kept_normal_sample': kept('normal_sample'),
|
||||
}
|
||||
return out
|
||||
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument('--rounds', type=int, default=3)
|
||||
p.add_argument('--output', default=None)
|
||||
args = arguments('Lab6 track 1: cost of observability', configure)
|
||||
c = Client(args.base_url, args.ca_file, timeout=30)
|
||||
o.wait_grafana()
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
order = list(CONFIGS)
|
||||
runs = []
|
||||
try:
|
||||
for rnd in range(args.rounds):
|
||||
seq = order[rnd % len(order):] + order[:rnd % len(order)]
|
||||
for name in seq:
|
||||
r = one_run(c, name, alice, chat, rnd)
|
||||
runs.append(r)
|
||||
print(json.dumps({k: r[k] for k in ('config', 'round', 'traces_kept', 'api_cpu_cores')}, ensure_ascii=False),
|
||||
json.dumps(r['load']['latency_ms_outside_faults']), flush=True)
|
||||
finally:
|
||||
apply('full')
|
||||
result = {'method': {'duration_s': DURATION, 'warmup_s': WARMUP, 'concurrency': CONC, 'locks_at_s': LOCKS,
|
||||
'lock_seconds': LOCK_SECONDS, 'slow_threshold_s': SLOW, 'rounds': args.rounds,
|
||||
'handler_timeout_s': 5},
|
||||
'summary': aggregate(runs), 'runs': runs}
|
||||
text = json.dumps(result, ensure_ascii=False, indent=2)
|
||||
if args.output:
|
||||
Path(args.output).write_text(text + '\n', encoding='utf-8')
|
||||
print(json.dumps(result['summary'], ensure_ascii=False, indent=2))
|
||||
check(len(runs) == args.rounds * len(CONFIGS), 'not all runs completed')
|
||||
print('PASS: telemetry cost experiment')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Reference in New Issue
Block a user