Done Track 4
This commit is contained in:
@@ -0,0 +1,327 @@
|
||||
"""Негативные и граничные сценарии вложений lab4 (только stdlib).
|
||||
|
||||
Проверяет, что пользовательская ошибка никогда не становится 500:
|
||||
- размер: ровно 10 MiB -> 201; 10 MiB + 1 по Content-Length и chunked -> 413;
|
||||
- пиксели: ровно 40 млн -> 201; 50 млн (маленький файл, «бомба») -> 413;
|
||||
- повреждённые PNG/JPEG (обрезка, CRC, мусор в IDAT), чужие форматы -> 415;
|
||||
- подмена MIME: PNG как image/jpeg, JPEG как image/png, text/plain, multipart -> 415;
|
||||
- опасные filename (/, \\, NUL, управляющие, bidi, пустой, 256 символов) -> 400;
|
||||
- чужой пользователь: upload в чужой чат, metadata, content -> 404;
|
||||
- message: вложение другого чата / неизвестное -> 404, дубли / 11 ID -> 400,
|
||||
text="" с вложением -> 201, повтор Idempotency-Key -> то же сообщение;
|
||||
- оборванная загрузка не ломает реплику; variant без варианта -> 404.
|
||||
|
||||
Запуск: docker compose --profile tools run --rm tester python3 student-tests/attachment_edge_cases.py
|
||||
или с хоста: python student-tests/attachment_edge_cases.py --base-url http://localhost:8080
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import http.client
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import struct
|
||||
import sys
|
||||
import urllib.parse
|
||||
import uuid
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
SAMPLE_PNG = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
SAMPLE_JPG = (ROOT / 'student-tests/fixtures/sample.jpg').read_bytes()
|
||||
MIB10 = 10 * 1024 * 1024
|
||||
|
||||
|
||||
# --- синтетические изображения ---------------------------------------------
|
||||
|
||||
def png_chunk(kind: bytes, data: bytes) -> bytes:
|
||||
return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data))
|
||||
|
||||
|
||||
def png(width: int, height: int, bit_depth: int = 8, color_type: int = 0, idat: bytes | None = None,
|
||||
extra: bytes = b'') -> bytes:
|
||||
if idat is None:
|
||||
row_bytes = (width * bit_depth * {0: 1, 2: 3}[color_type] + 7) // 8
|
||||
raw = (b'\x00' + b'\x00' * row_bytes) * height
|
||||
idat = zlib.compress(raw, 9)
|
||||
ihdr = struct.pack('>IIBBBBB', width, height, bit_depth, color_type, 0, 0, 0)
|
||||
return (b'\x89PNG\r\n\x1a\n' + png_chunk(b'IHDR', ihdr) + extra
|
||||
+ png_chunk(b'IDAT', idat) + png_chunk(b'IEND', b''))
|
||||
|
||||
|
||||
def png_exactly(size: int) -> bytes:
|
||||
"""Валидный PNG ровно size байт: добивается приватным ancillary-чанком."""
|
||||
base = png(8, 8)
|
||||
pad = size - len(base) - 12
|
||||
return png(8, 8, extra=png_chunk(b'zpAD', b'\x00' * pad))
|
||||
|
||||
|
||||
def pixels_png(width: int, height: int) -> bytes:
|
||||
"""1-битный grayscale: 40 млн пикселей занимают ~5 MB raw, ~10 KB zlib."""
|
||||
row = b'\x00' + b'\x00' * ((width + 7) // 8)
|
||||
compressor = zlib.compressobj(9)
|
||||
idat = b''.join(compressor.compress(row) for _ in range(height)) + compressor.flush()
|
||||
return png(width, height, bit_depth=1, idat=idat)
|
||||
|
||||
|
||||
def corrupt_crc(data: bytes) -> bytes:
|
||||
i = data.index(b'IDAT') + 6
|
||||
return data[:i] + bytes([data[i] ^ 0xFF]) + data[i + 1:]
|
||||
|
||||
|
||||
def corrupt_idat(data: bytes) -> bytes:
|
||||
"""Мусор в zlib-потоке с ПРАВИЛЬНЫМ CRC: ловится только распаковкой."""
|
||||
return png(320, 200, color_type=2, idat=b'\x78\x9c' + os.urandom(2000))
|
||||
|
||||
|
||||
# --- HTTP ------------------------------------------------------------------
|
||||
|
||||
class Api:
|
||||
def __init__(self, base_url: str):
|
||||
parts = urllib.parse.urlsplit(base_url)
|
||||
self.host = parts.hostname
|
||||
self.port = parts.port or 80
|
||||
|
||||
def conn(self) -> http.client.HTTPConnection:
|
||||
return http.client.HTTPConnection(self.host, self.port, timeout=60)
|
||||
|
||||
def call(self, method, path, body=None, headers=None, raw=None, chunks=None):
|
||||
h = dict(headers or {})
|
||||
if body is not None:
|
||||
raw = json.dumps(body).encode()
|
||||
h['Content-Type'] = 'application/json'
|
||||
c = self.conn()
|
||||
try:
|
||||
if chunks is not None:
|
||||
c.request(method, '/api/v1' + path, body=chunks, headers=h, encode_chunked=True)
|
||||
else:
|
||||
c.request(method, '/api/v1' + path, body=raw, headers=h)
|
||||
r = c.getresponse()
|
||||
data = r.read()
|
||||
except (BrokenPipeError, ConnectionResetError):
|
||||
# Сервер ответил 413 и закрыл соединение, не дочитав тело.
|
||||
r = c.getresponse()
|
||||
data = r.read()
|
||||
finally:
|
||||
c.close()
|
||||
ctype = r.getheader('Content-Type', '')
|
||||
parsed = json.loads(data) if data and ctype.startswith('application/json') else None
|
||||
return r.status, parsed, data, r
|
||||
|
||||
|
||||
def main() -> int:
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument('--base-url', default=os.environ.get('BASE_URL', 'http://localhost:8080'))
|
||||
args = p.parse_args()
|
||||
api = Api(args.base_url)
|
||||
failed = 0
|
||||
|
||||
def code(resp):
|
||||
return resp.get('error', {}).get('code') if isinstance(resp, dict) else None
|
||||
|
||||
def check(label, status, resp, want_status, want_code=None, extra_ok=True):
|
||||
nonlocal failed
|
||||
ok = status == want_status and (want_code is None or code(resp) == want_code) and extra_ok
|
||||
failed += not ok
|
||||
print(f"{'OK ' if ok else 'FAIL'} {label}: {status} {code(resp) or ''} "
|
||||
f"(ожидается {want_status} {want_code or ''})", flush=True)
|
||||
|
||||
def new_user():
|
||||
name = 'att' + uuid.uuid4().hex[:12]
|
||||
password = 'attachment-edge-password'
|
||||
s, user, _, _ = api.call('POST', '/users', {'username': name, 'display_name': 'Вложения', 'password': password})
|
||||
assert s == 201, f'register: {s}'
|
||||
basic = 'Basic ' + base64.b64encode(f'{name}:{password}'.encode()).decode()
|
||||
s, session, _, _ = api.call('POST', '/auth/sessions', headers={'Authorization': basic})
|
||||
assert s == 201, f'login: {s}'
|
||||
return user, {'Authorization': 'Bearer ' + session['token']}
|
||||
|
||||
def new_chat(auth, members, title='attachments'):
|
||||
s, chat, _, _ = api.call('POST', '/chats', {'title': title, 'member_ids': members}, headers=auth)
|
||||
assert s == 201, f'chat: {s}'
|
||||
return chat
|
||||
|
||||
def upload(auth, chat_id, data, content_type='image/png', filename='photo.png', **kw):
|
||||
query = '' if filename is None else '?filename=' + urllib.parse.quote(filename, safe='')
|
||||
h = dict(auth)
|
||||
if content_type is not None:
|
||||
h['Content-Type'] = content_type
|
||||
return api.call('POST', f'/chats/{chat_id}/attachments{query}', headers=h, raw=data, **kw)
|
||||
|
||||
def message(auth, chat_id, text, ids=None, key=None):
|
||||
body = {'text': text}
|
||||
if ids is not None:
|
||||
body['attachment_ids'] = ids
|
||||
h = dict(auth, **{'Idempotency-Key': key or uuid.uuid4().hex})
|
||||
return api.call('POST', f'/chats/{chat_id}/messages', body, headers=h)
|
||||
|
||||
alice, a_auth = new_user()
|
||||
bob, b_auth = new_user()
|
||||
eve, e_auth = new_user()
|
||||
chat = new_chat(a_auth, [alice['id'], bob['id']])
|
||||
other_chat = new_chat(a_auth, [alice['id']], 'other')
|
||||
eve_chat = new_chat(e_auth, [eve['id']], 'eve')
|
||||
|
||||
# --- успешные границы ---------------------------------------------------
|
||||
s, att, _, r = upload(a_auth, chat['id'], SAMPLE_JPG, 'image/jpeg', 'фото 😀 v1.0.jpg')
|
||||
check('JPEG fixture -> 201 ready', s, att, 201, extra_ok=s == 201 and att['status'] == 'ready'
|
||||
and att['sha256'] == hashlib.sha256(SAMPLE_JPG).hexdigest() and att['size_bytes'] == len(SAMPLE_JPG)
|
||||
and att['filename'] == 'фото 😀 v1.0.jpg' and att['variants'] == [] and att['error_code'] is None
|
||||
and 'object_key' not in att)
|
||||
jpg_id = att['id']
|
||||
s, _, data, r = api.call('GET', f'/attachments/{jpg_id}/content', headers=b_auth)
|
||||
check('участник скачивает JPEG побайтно, без redirect', s, None, 200,
|
||||
extra_ok=data == SAMPLE_JPG and r.getheader('Content-Type') == 'image/jpeg')
|
||||
|
||||
exact = png_exactly(MIB10)
|
||||
s, att, _, _ = upload(a_auth, chat['id'], exact)
|
||||
check('PNG ровно 10 MiB -> 201', s, att, 201, extra_ok=s == 201 and att['size_bytes'] == MIB10)
|
||||
if s == 201:
|
||||
s, _, data, _ = api.call('GET', f"/attachments/{att['id']}/content", headers=a_auth)
|
||||
check('10 MiB скачан побайтно', s, None, 200, extra_ok=hashlib.sha256(data).digest() == hashlib.sha256(exact).digest())
|
||||
|
||||
s, att, _, _ = upload(a_auth, chat['id'], pixels_png(8000, 5000))
|
||||
check('PNG ровно 40 млн пикселей -> 201', s, att, 201)
|
||||
|
||||
# --- размер -------------------------------------------------------------
|
||||
s, r, _, _ = upload(a_auth, chat['id'], png_exactly(MIB10 + 1))
|
||||
check('10 MiB + 1 байт (Content-Length) -> 413', s, r, 413, 'payload_too_large')
|
||||
|
||||
def big_chunks():
|
||||
block = png_exactly(MIB10)[:1024 * 1024]
|
||||
for _ in range(11):
|
||||
yield block
|
||||
|
||||
s, r, _, _ = upload(a_auth, chat['id'], None, chunks=big_chunks())
|
||||
check('11 MiB chunked без Content-Length -> 413', s, r, 413, 'payload_too_large')
|
||||
|
||||
s, r, _, _ = upload(a_auth, chat['id'], pixels_png(10000, 5000))
|
||||
check('PNG-«бомба» 50 млн пикселей (~10 KB файл) -> 413', s, r, 413, 'payload_too_large')
|
||||
s, r, _, _ = upload(a_auth, chat['id'], png(0x7FFFFFFF, 0x7FFFFFFF, idat=b'x'))
|
||||
check('PNG 2^31-1 x 2^31-1 в IHDR -> 413', s, r, 413, 'payload_too_large')
|
||||
|
||||
s, r, _, _ = upload(a_auth, chat['id'], b'')
|
||||
check('пустое тело -> 400', s, r, 400, 'invalid_request')
|
||||
|
||||
# --- повреждённые и чужие форматы --------------------------------------
|
||||
for label, data, ctype in [
|
||||
('PNG обрезан пополам', SAMPLE_PNG[:len(SAMPLE_PNG) // 2], 'image/png'),
|
||||
('PNG с неверным CRC', corrupt_crc(SAMPLE_PNG), 'image/png'),
|
||||
('PNG с мусором в zlib при верном CRC', corrupt_idat(SAMPLE_PNG), 'image/png'),
|
||||
('PNG без IEND', SAMPLE_PNG[:-12], 'image/png'),
|
||||
('JPEG обрезан', SAMPLE_JPG[:len(SAMPLE_JPG) // 2], 'image/jpeg'),
|
||||
('JPEG только сигнатура', b'\xff\xd8\xff\xe0' + b'\x00' * 100, 'image/jpeg'),
|
||||
('GIF как image/png', b'GIF89a' + b'\x00' * 100, 'image/png'),
|
||||
('случайные байты как image/png', os.urandom(4096), 'image/png'),
|
||||
('HTML как image/jpeg', b'<html><script>alert(1)</script></html>', 'image/jpeg'),
|
||||
]:
|
||||
s, r, _, _ = upload(a_auth, chat['id'], data, ctype)
|
||||
check(label + ' -> 415', s, r, 415, 'unsupported_media_type')
|
||||
|
||||
# --- подмена MIME -------------------------------------------------------
|
||||
for label, data, ctype in [
|
||||
('PNG под Content-Type image/jpeg', SAMPLE_PNG, 'image/jpeg'),
|
||||
('JPEG под Content-Type image/png', SAMPLE_JPG, 'image/png'),
|
||||
('PNG под text/plain', SAMPLE_PNG, 'text/plain'),
|
||||
('PNG под image/gif', SAMPLE_PNG, 'image/gif'),
|
||||
('multipart/form-data', b'--x\r\n\r\n' + SAMPLE_PNG + b'\r\n--x--', 'multipart/form-data; boundary=x'),
|
||||
('без Content-Type', SAMPLE_PNG, None),
|
||||
]:
|
||||
s, r, _, _ = upload(a_auth, chat['id'], data, ctype)
|
||||
check(label + ' -> 415', s, r, 415, 'unsupported_media_type')
|
||||
|
||||
# --- filename -----------------------------------------------------------
|
||||
for label, name in [
|
||||
('../../etc/passwd', '../../etc/passwd'),
|
||||
('C:\\boot.png', 'C:\\boot.png'),
|
||||
('NUL в имени', 'a\x00.png'),
|
||||
('перевод строки', 'a\nb.png'),
|
||||
('ESC-последовательность', '\x1b[31mred.png'),
|
||||
('bidi override (gnp.exe)', 'photo\u202egnp.exe'),
|
||||
('только пробелы', ' '),
|
||||
('..', '..'),
|
||||
('256 символов', 'a' * 252 + '.png'),
|
||||
('пустой filename', ''),
|
||||
('нет filename', None),
|
||||
]:
|
||||
s, r, _, _ = upload(a_auth, chat['id'], SAMPLE_PNG, filename=name)
|
||||
check(f'filename {label} -> 400', s, r, 400, 'invalid_request')
|
||||
s, r, _, _ = upload(a_auth, chat['id'], SAMPLE_PNG, filename='a' * 251 + '.png')
|
||||
check('filename ровно 255 символов -> 201', s, r, 201)
|
||||
|
||||
# --- доступ -------------------------------------------------------------
|
||||
s, r, _, _ = upload({}, chat['id'], SAMPLE_PNG)
|
||||
check('upload без токена -> 401', s, r, 401, 'unauthorized')
|
||||
s, r, _, _ = upload(e_auth, chat['id'], SAMPLE_PNG)
|
||||
check('посторонний upload в чужой чат -> 404', s, r, 404, 'not_found')
|
||||
s, r, _, _ = upload(a_auth, str(uuid.uuid4()), SAMPLE_PNG)
|
||||
check('upload в несуществующий чат -> 404', s, r, 404, 'not_found')
|
||||
for suffix in ('', '/content'):
|
||||
s, r, _, _ = api.call('GET', f'/attachments/{jpg_id}{suffix}', headers=e_auth)
|
||||
check(f'посторонний GET /attachments/id{suffix} -> 404', s, r, 404, 'not_found')
|
||||
s, r, _, _ = api.call('GET', f'/attachments/{uuid.uuid4()}{suffix}', headers=a_auth)
|
||||
check(f'неизвестный attachment{suffix} -> 404', s, r, 404, 'not_found')
|
||||
s, r, _, _ = api.call('GET', '/attachments/not-a-uuid', headers=a_auth)
|
||||
check('attachment_id не UUID -> 400', s, r, 400, 'invalid_request')
|
||||
s, r, _, _ = api.call('GET', f'/attachments/{jpg_id}/content?variant=thumbnail', headers=a_auth)
|
||||
check('ready без варианта thumbnail -> 404', s, r, 404, 'not_found')
|
||||
s, r, _, _ = api.call('GET', f'/attachments/{jpg_id}/content?variant=../../x', headers=a_auth)
|
||||
check('variant неизвестного имени -> 400', s, r, 400, 'invalid_request')
|
||||
|
||||
# --- привязка к сообщению -----------------------------------------------
|
||||
s, other_att, _, _ = upload(a_auth, other_chat['id'], SAMPLE_PNG)
|
||||
s, eve_att, _, _ = upload(e_auth, eve_chat['id'], SAMPLE_PNG)
|
||||
s, r, _, _ = message(a_auth, chat['id'], 'x', [other_att['id']])
|
||||
check('вложение другого чата (своего) -> 404', s, r, 404, 'not_found')
|
||||
s, r, _, _ = message(a_auth, chat['id'], 'x', [eve_att['id']])
|
||||
check('вложение чужого чата -> 404', s, r, 404, 'not_found')
|
||||
s, r, _, _ = message(a_auth, chat['id'], 'x', [jpg_id, str(uuid.uuid4())])
|
||||
check('одно из ID неизвестно -> 404, ничего не создано', s, r, 404, 'not_found')
|
||||
s, r, _, _ = message(a_auth, chat['id'], 'x', [jpg_id, jpg_id])
|
||||
check('дубли attachment_ids -> 400', s, r, 400, 'invalid_request')
|
||||
s, r, _, _ = message(a_auth, chat['id'], 'x', [str(uuid.uuid4()) for _ in range(11)])
|
||||
check('11 attachment_ids -> 400', s, r, 400, 'invalid_request')
|
||||
s, r, _, _ = message(a_auth, chat['id'], 'x', ['not-a-uuid'])
|
||||
check('attachment_id не UUID -> 400', s, r, 400, 'invalid_request')
|
||||
s, r, _, _ = message(a_auth, chat['id'], ' ', [])
|
||||
check('пробельный text без вложений -> 400', s, r, 400, 'invalid_request')
|
||||
|
||||
key = uuid.uuid4().hex
|
||||
s, m1, _, _ = message(b_auth, chat['id'], '', [jpg_id], key)
|
||||
check('Bob: text="" + вложение Alice из общего чата -> 201', s, m1, 201,
|
||||
extra_ok=s == 201 and m1['attachment_ids'] == [jpg_id] and m1['text'] == '')
|
||||
s, m2, _, _ = message(b_auth, chat['id'], '', [jpg_id], key)
|
||||
check('повтор Idempotency-Key -> то же сообщение', s, m2, 201, extra_ok=s == 201 and m2['id'] == m1['id'])
|
||||
s, r, _, _ = message(b_auth, chat['id'], 'другой текст', [], key)
|
||||
check('тот же ключ, другое тело -> 409', s, r, 409, 'conflict')
|
||||
s, page, _, _ = api.call('GET', f"/chats/{chat['id']}/messages?limit=100", headers=a_auth)
|
||||
linked = [m for m in page['items'] if m['attachment_ids']]
|
||||
check('история: ровно одно сообщение с вложением', s, page, 200,
|
||||
extra_ok=len(linked) == 1 and linked[0]['attachment_ids'] == [jpg_id])
|
||||
|
||||
# --- оборванная загрузка ------------------------------------------------
|
||||
sock = socket.create_connection((api.host, api.port), timeout=10)
|
||||
head = (f"POST /api/v1/chats/{chat['id']}/attachments?filename=cut.png HTTP/1.1\r\n"
|
||||
f"Host: {api.host}\r\nAuthorization: {a_auth['Authorization']}\r\n"
|
||||
f"Content-Type: image/png\r\nContent-Length: {len(SAMPLE_PNG)}\r\n\r\n")
|
||||
sock.sendall(head.encode() + SAMPLE_PNG[:len(SAMPLE_PNG) // 3])
|
||||
sock.close()
|
||||
s, r, _, _ = upload(a_auth, chat['id'], SAMPLE_PNG)
|
||||
check('после оборванной загрузки API работает', s, r, 201)
|
||||
|
||||
# --- формат ошибок ------------------------------------------------------
|
||||
s, r, _, resp = upload(a_auth, chat['id'], b'not an image')
|
||||
check('ошибка в общем формате с request_id', s, r, 415, extra_ok=bool(r)
|
||||
and r['error']['request_id'] == resp.getheader('X-Request-Id') and bool(resp.getheader('X-Instance-Id')))
|
||||
|
||||
print('PASS: граничные случаи вложений соответствуют контракту' if not failed
|
||||
else f'FAIL: {failed} проверок не прошло')
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 4.1 KiB |
@@ -0,0 +1,185 @@
|
||||
"""Приватность bucket вне API и недоступность S3 (stdlib + docker CLI).
|
||||
|
||||
1. Bucket приватен вне API: реальный object_key берётся из PostgreSQL
|
||||
(docker exec db psql), затем анонимные GET/HEAD/LIST/PUT напрямую в S3
|
||||
из сети backend -> 403; S3-порт не опубликован на хосте; LB не
|
||||
проксирует пути S3.
|
||||
2. Отказ S3 (docker stop s3): /health/ready 200, сообщения 201, metadata 200,
|
||||
upload/download -> быстрый 503 в общем формате (не 500, не зависание).
|
||||
После docker start s3: upload 201, старый файл скачивается побайтно.
|
||||
|
||||
Нужен docker.sock: запускайте только в tester на учебном стенде:
|
||||
docker compose --profile tools run --rm tester python3 student-tests/s3_failures.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
BASE = os.environ.get('BASE_URL', 'http://lb:8080').rstrip('/')
|
||||
S3 = os.environ.get('S3_ENDPOINT', 'http://s3:9000').rstrip('/')
|
||||
PROJECT = os.environ.get('COMPOSE_PROJECT', 'messenger-lab4')
|
||||
BUCKET = 'messenger-attachments'
|
||||
SAMPLE = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
|
||||
failed = 0
|
||||
|
||||
|
||||
def check(label, ok, detail=''):
|
||||
global failed
|
||||
failed += not ok
|
||||
print(f"{'OK ' if ok else 'FAIL'} {label} {detail}".rstrip(), flush=True)
|
||||
|
||||
|
||||
def docker(*args, check_rc=True) -> str:
|
||||
return subprocess.run(['docker', *args], check=check_rc, capture_output=True, text=True).stdout.strip()
|
||||
|
||||
|
||||
def container(service: str) -> str:
|
||||
ids = docker('ps', '-aq', '--filter', f'label=com.docker.compose.project={PROJECT}',
|
||||
'--filter', f'label=com.docker.compose.service={service}').split()
|
||||
assert ids, f'no container for {service}'
|
||||
return ids[0]
|
||||
|
||||
|
||||
def http(method, url, data=None, headers=None, timeout=30):
|
||||
req = urllib.request.Request(url, data=data, headers=headers or {}, method=method)
|
||||
started = time.monotonic()
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return r.status, r.read(), time.monotonic() - started
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, e.read(), time.monotonic() - started
|
||||
|
||||
|
||||
def api(method, path, body=None, auth=None, raw=None, ctype=None, extra=None):
|
||||
h = dict(extra or {})
|
||||
if auth:
|
||||
h['Authorization'] = auth
|
||||
if body is not None:
|
||||
raw = json.dumps(body).encode()
|
||||
ctype = 'application/json'
|
||||
if ctype:
|
||||
h['Content-Type'] = ctype
|
||||
status, data, elapsed = http(method, BASE + '/api/v1' + path, raw, h)
|
||||
try:
|
||||
parsed = json.loads(data) if data else None
|
||||
except ValueError:
|
||||
parsed = None
|
||||
return status, parsed, data, elapsed
|
||||
|
||||
|
||||
def err(parsed):
|
||||
return parsed.get('error', {}).get('code') if isinstance(parsed, dict) else None
|
||||
|
||||
|
||||
def wait_healthy(cid, seconds=90):
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
if docker('inspect', '-f', '{{.State.Health.Status}}', cid) == 'healthy':
|
||||
return True
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
|
||||
def main() -> int:
|
||||
name = 's3f' + uuid.uuid4().hex[:12]
|
||||
password = 's3-failure-password'
|
||||
s, user, _, _ = api('POST', '/users', {'username': name, 'display_name': 'S3', 'password': password})
|
||||
basic = 'Basic ' + base64.b64encode(f'{name}:{password}'.encode()).decode()
|
||||
s, session, _, _ = api('POST', '/auth/sessions', auth=basic)
|
||||
auth = 'Bearer ' + session['token']
|
||||
s, chat, _, _ = api('POST', '/chats', {'title': 's3', 'member_ids': [user['id']]}, auth=auth)
|
||||
s, att, _, _ = api('POST', f"/chats/{chat['id']}/attachments?filename=a.png", auth=auth, raw=SAMPLE, ctype='image/png')
|
||||
assert s == 201, s
|
||||
|
||||
# --- 1. приватный bucket вне API ---------------------------------------
|
||||
db = container('db')
|
||||
key = docker('exec', db, 'psql', '-U', 'messenger', '-d', 'messenger', '-tAc',
|
||||
f"SELECT object_key FROM attachments WHERE id = '{att['id']}'")
|
||||
check('object_key есть в PostgreSQL и не совпадает с filename/ID',
|
||||
bool(key) and 'a.png' not in key and att['id'] not in key)
|
||||
check('API не раскрывает object_key', key not in json.dumps(att))
|
||||
for method, path, data in [
|
||||
('GET', f'/{BUCKET}/{key}', None),
|
||||
('HEAD', f'/{BUCKET}/{key}', None),
|
||||
('GET', f'/{BUCKET}?list-type=2', None),
|
||||
('GET', f'/{BUCKET}/', None),
|
||||
('PUT', f'/{BUCKET}/{key}', b'overwrite'),
|
||||
('DELETE', f'/{BUCKET}/{key}', None),
|
||||
]:
|
||||
s, _, _ = http(method, S3 + path, data)
|
||||
check(f'анонимный {method} {path.replace(key, "<key>")} напрямую в S3 -> 403', s == 403, f'({s})')
|
||||
s, _, data, _ = api('GET', f"/attachments/{att['id']}/content", auth=auth)
|
||||
check('объект не изменён анонимными PUT/DELETE', hashlib.sha256(data).digest() == hashlib.sha256(SAMPLE).digest())
|
||||
s3 = container('s3')
|
||||
ports = docker('port', s3, check_rc=False)
|
||||
check('S3 не опубликован на хосте (docker port пуст)', ports == '', repr(ports))
|
||||
s, _, _ = http('GET', BASE + f'/{BUCKET}/{key}')
|
||||
check('LB не проксирует путь S3', s == 404, f'({s})')
|
||||
host = urllib.parse.urlsplit(S3).hostname
|
||||
for port, role in [(9333, 'master UI/API'), (8888, 'filer UI/API'), (8080, 'volume'),
|
||||
(19333, 'master gRPC'), (18888, 'filer gRPC'), (23646, 'admin')]:
|
||||
try:
|
||||
socket.create_connection((host, port), timeout=2).close()
|
||||
reachable = True
|
||||
except OSError:
|
||||
reachable = False
|
||||
check(f'SeaweedFS {role} :{port} недоступен из сети стенда', not reachable)
|
||||
|
||||
# --- 2. отказ S3 -------------------------------------------------------
|
||||
docker('stop', '--time', '10', s3)
|
||||
print('-- s3 остановлен', flush=True)
|
||||
try:
|
||||
s, _, _ = http('GET', BASE + '/health/ready')
|
||||
check('/health/ready при отказе S3 -> 200 (S3 не критичен для чата)', s == 200, f'({s})')
|
||||
s, m, _, _ = api('POST', f"/chats/{chat['id']}/messages", {'text': 'без S3', 'attachment_ids': [att['id']]},
|
||||
auth=auth, extra={'Idempotency-Key': uuid.uuid4().hex})
|
||||
check('сообщение со ссылкой на готовое вложение -> 201', s == 201, f'({s})')
|
||||
s, _, _, _ = api('GET', f"/attachments/{att['id']}", auth=auth)
|
||||
check('metadata из PostgreSQL -> 200', s == 200, f'({s})')
|
||||
s, p, _, t = api('POST', f"/chats/{chat['id']}/attachments?filename=b.png", auth=auth, raw=SAMPLE, ctype='image/png')
|
||||
check('upload -> 503 unavailable', s == 503 and err(p) == 'unavailable', f'({s} {err(p)}, {t:.2f} s)')
|
||||
check('upload отказал быстрее timeout LB (< 8 s)', t < 8, f'({t:.2f} s)')
|
||||
s, p, _, t = api('GET', f"/attachments/{att['id']}/content", auth=auth)
|
||||
check('download -> 503 unavailable', s == 503 and err(p) == 'unavailable', f'({s} {err(p)}, {t:.2f} s)')
|
||||
check('download отказал быстрее timeout LB (< 8 s)', t < 8, f'({t:.2f} s)')
|
||||
s, p, _, _ = api('POST', f"/chats/{chat['id']}/attachments?filename=c.png", auth=auth, raw=b'junk', ctype='image/png')
|
||||
check('пользовательская ошибка при отказе S3 остаётся 415', s == 415, f'({s})')
|
||||
intents = docker('exec', db, 'psql', '-U', 'messenger', '-d', 'messenger', '-tAc',
|
||||
'SELECT count(*) FROM upload_intents')
|
||||
print(f' upload_intents после неудачных upload: {intents}', flush=True)
|
||||
finally:
|
||||
docker('start', s3)
|
||||
print('-- s3 запущен', flush=True)
|
||||
|
||||
check('s3 снова healthy', wait_healthy(s3))
|
||||
deadline = time.monotonic() + 30
|
||||
while True:
|
||||
s, new, _, _ = api('POST', f"/chats/{chat['id']}/attachments?filename=d.png", auth=auth, raw=SAMPLE, ctype='image/png')
|
||||
if s == 201 or time.monotonic() > deadline:
|
||||
break
|
||||
time.sleep(1)
|
||||
check('после восстановления S3 upload -> 201', s == 201, f'({s})')
|
||||
s, _, data, _ = api('GET', f"/attachments/{att['id']}/content", auth=auth)
|
||||
check('старый файл скачивается побайтно', s == 200 and data == SAMPLE, f'({s})')
|
||||
|
||||
print('PASS: bucket приватен вне API, отказ S3 даёт 503 только для вложений' if not failed
|
||||
else f'FAIL: {failed} проверок не прошло')
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,221 @@
|
||||
"""Уровень 4: отказ между S3 PUT и COMMIT не оставляет вечных объектов.
|
||||
|
||||
1. db_error_after_s3_put — процесс API (FAULT_INJECTION, порт 8091 внутри
|
||||
контейнера реплики) теряет БД после PUT -> 503, фоновая компенсация
|
||||
сама удаляет объект и intent;
|
||||
2. crash_after_s3_put — процесс (порт 8090) умирает после PUT до COMMIT ->
|
||||
остаются intent и объект; janitor после grace удаляет оба;
|
||||
3. свежий intent (моложе grace, «загрузка в процессе») janitor не трогает;
|
||||
готовое вложение после janitor скачивается побайтно.
|
||||
|
||||
docker compose --profile tools run --rm tester python3 student-tests/upload_compensation.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
BASE = os.environ.get('BASE_URL', 'http://lb:8080').rstrip('/')
|
||||
PROJECT = os.environ.get('COMPOSE_PROJECT', 'messenger-lab4')
|
||||
SAMPLE = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
GRACE = 20
|
||||
|
||||
failed = 0
|
||||
|
||||
|
||||
def check(label, ok, detail=''):
|
||||
global failed
|
||||
failed += not ok
|
||||
print(f"{'OK ' if ok else 'FAIL'} {label} {detail}".rstrip(), flush=True)
|
||||
|
||||
|
||||
def docker(*args, stdin=None) -> str:
|
||||
r = subprocess.run(['docker', *args], capture_output=True, text=True, input=stdin)
|
||||
if r.returncode:
|
||||
raise RuntimeError(f'docker {args[0]} failed: {r.stderr.strip()[-300:]}')
|
||||
return r.stdout.strip()
|
||||
|
||||
|
||||
def container(service: str) -> str:
|
||||
return docker('ps', '-q', '--filter', f'label=com.docker.compose.project={PROJECT}',
|
||||
'--filter', f'label=com.docker.compose.service={service}').split()[0]
|
||||
|
||||
|
||||
API = DB = ''
|
||||
|
||||
|
||||
def psql(sql: str) -> str:
|
||||
return docker('exec', DB, 'psql', '-U', 'messenger', '-d', 'messenger', '-tAc', sql)
|
||||
|
||||
|
||||
def intents() -> set[str]:
|
||||
return set(filter(None, psql('SELECT object_key FROM upload_intents').splitlines()))
|
||||
|
||||
|
||||
def s3_exists(*keys: str) -> list:
|
||||
code = """
|
||||
import asyncio, json, sys
|
||||
from app.storage import storage
|
||||
async def main():
|
||||
await storage.start()
|
||||
out = [await storage.exists(k) for k in json.load(sys.stdin)]
|
||||
await storage.close()
|
||||
print(json.dumps(out))
|
||||
asyncio.run(main())
|
||||
"""
|
||||
return json.loads(docker('exec', '-i', API, 'python', '-c', code, stdin=json.dumps(list(keys))))
|
||||
|
||||
|
||||
def run_janitor(grace: int) -> int:
|
||||
code = f"""
|
||||
import asyncio
|
||||
from app.attachments import cleanup_stale_uploads
|
||||
from app.storage import storage
|
||||
async def main():
|
||||
await storage.start()
|
||||
print(await cleanup_stale_uploads({grace}))
|
||||
await storage.close()
|
||||
asyncio.run(main())
|
||||
"""
|
||||
return int(docker('exec', API, 'python', '-c', code).splitlines()[-1])
|
||||
|
||||
|
||||
def http(method, url, data=None, headers=None, timeout=30):
|
||||
req = urllib.request.Request(url, data=data, headers=headers or {}, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return r.status, r.read()
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, e.read()
|
||||
|
||||
|
||||
class Client:
|
||||
def __init__(self, base):
|
||||
self.base = base
|
||||
|
||||
def call(self, method, path, body=None, auth=None, raw=None, ctype=None):
|
||||
h = {}
|
||||
if auth:
|
||||
h['Authorization'] = auth
|
||||
if body is not None:
|
||||
raw, ctype = json.dumps(body).encode(), 'application/json'
|
||||
if ctype:
|
||||
h['Content-Type'] = ctype
|
||||
s, data = http(method, self.base + '/api/v1' + path, raw, h)
|
||||
try:
|
||||
return s, json.loads(data)
|
||||
except ValueError:
|
||||
return s, data
|
||||
|
||||
def upload(self, auth, chat_id):
|
||||
return self.call('POST', f'/chats/{chat_id}/attachments?filename=c.png',
|
||||
auth=auth, raw=SAMPLE, ctype='image/png')
|
||||
|
||||
|
||||
def start_faulty(mode: str, port: int) -> Client:
|
||||
docker('exec', '-d', '-e', f'FAULT_INJECTION={mode}', '-e', f'APP_PORT={port}',
|
||||
'-e', 'JANITOR_INTERVAL_SECONDS=3600', API, 'python', '-m', 'app.server')
|
||||
name = docker('inspect', '-f', '{{.Name}}', API).lstrip('/')
|
||||
base = f'http://{name}:{port}'
|
||||
for _ in range(60):
|
||||
try:
|
||||
if http('GET', base + '/health/ready', timeout=2)[0] == 200:
|
||||
return Client(base)
|
||||
except OSError:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
raise RuntimeError(f'faulty process {mode} did not start')
|
||||
|
||||
|
||||
def stop_faulty() -> None:
|
||||
"""Kill the extra app.server processes (not PID 1, the real replica)."""
|
||||
code = """
|
||||
import os, signal
|
||||
for p in filter(str.isdigit, os.listdir('/proc')):
|
||||
if int(p) in (1, os.getpid()):
|
||||
continue
|
||||
try:
|
||||
cmd = open(f'/proc/{p}/cmdline', 'rb').read()
|
||||
except OSError:
|
||||
continue
|
||||
if b'app.server' in cmd:
|
||||
os.kill(int(p), signal.SIGKILL)
|
||||
"""
|
||||
docker('exec', API, 'python', '-c', code)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
global API, DB
|
||||
API, DB = container('api'), container('db')
|
||||
lb = Client(BASE)
|
||||
|
||||
name = 'comp' + uuid.uuid4().hex[:12]
|
||||
password = 'compensation-password-1'
|
||||
lb.call('POST', '/users', {'username': name, 'display_name': 'Comp', 'password': password})
|
||||
basic = 'Basic ' + base64.b64encode(f'{name}:{password}'.encode()).decode()
|
||||
auth = 'Bearer ' + lb.call('POST', '/auth/sessions', auth=basic)[1]['token']
|
||||
me = lb.call('GET', '/users/me', auth=auth)[1]
|
||||
chat = lb.call('POST', '/chats', {'title': 'compensation', 'member_ids': [me['id']]}, auth=auth)[1]
|
||||
ready = lb.upload(auth, chat['id'])[1]
|
||||
|
||||
try:
|
||||
# 1. DB lost after PUT -> 503 + background compensation
|
||||
before = intents()
|
||||
s, _ = start_faulty('db_error_after_s3_put', 8091).upload(auth, chat['id'])
|
||||
time.sleep(2)
|
||||
check('db_error_after_s3_put: 503', s == 503, f'({s})')
|
||||
check('db_error_after_s3_put: компенсация убрала intent', intents() - before == set())
|
||||
|
||||
# 2. crash after PUT -> intent + object stay
|
||||
before = intents()
|
||||
try:
|
||||
s, _ = start_faulty('crash_after_s3_put', 8090).upload(auth, chat['id'])
|
||||
result = f'HTTP {s}'
|
||||
except OSError as exc:
|
||||
result = type(exc).__name__
|
||||
crash_keys = sorted(intents() - before)
|
||||
check('crash_after_s3_put: клиент не получил 201', '201' not in result, f'({result})')
|
||||
check('crash_after_s3_put: остались intent и объект',
|
||||
len(crash_keys) == 1 and s3_exists(*crash_keys) == [True])
|
||||
finally:
|
||||
stop_faulty()
|
||||
|
||||
check('janitor до grace ничего не удаляет',
|
||||
run_janitor(GRACE) == 0 and set(crash_keys) <= intents())
|
||||
|
||||
print(f'-- ждём grace {GRACE + 1} s', flush=True)
|
||||
time.sleep(GRACE + 1)
|
||||
|
||||
# 3. fresh in-flight upload (younger than grace) must survive
|
||||
inflight = f'originals/{uuid.uuid4().hex}'
|
||||
psql(f"INSERT INTO upload_intents (object_key, attachment_id, chat_id) "
|
||||
f"VALUES ('{inflight}', '{uuid.uuid4()}', '{chat['id']}')")
|
||||
|
||||
cleaned = run_janitor(GRACE)
|
||||
left = intents()
|
||||
check('janitor после grace удалил intent от crash', cleaned >= 1 and not set(crash_keys) & left,
|
||||
f'(cleaned={cleaned})')
|
||||
check('janitor удалил объект от crash', s3_exists(*crash_keys) == [False])
|
||||
check('свежий intent не тронут', inflight in left)
|
||||
psql(f"DELETE FROM upload_intents WHERE object_key = '{inflight}'")
|
||||
|
||||
s, body = lb.call('GET', f"/attachments/{ready['id']}/content", auth=auth)
|
||||
check('готовое вложение цело', s == 200 and hashlib.sha256(body).hexdigest() == ready['sha256'])
|
||||
|
||||
print('PASS: компенсация и janitor не оставляют вечных объектов' if not failed
|
||||
else f'FAIL: {failed} проверок не прошли')
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,105 @@
|
||||
"""Upload -> остановка обслужившей реплики -> download через другую, для КАЖДОЙ реплики.
|
||||
|
||||
Публичный failover-тест останавливает ту реплику, что ему ответила (при
|
||||
round-robin — обычно одну и ту же). Здесь цель выбирается явно: файл
|
||||
загружается, пока X-Instance-Id не совпадёт с целевой репликой, затем она
|
||||
останавливается (docker stop, остаётся остановленной на время проверки),
|
||||
файл скачивается через LB и сравнивается по SHA-256; реплика запускается снова.
|
||||
|
||||
docker compose --profile tools run --rm tester python3 student-tests/upload_failover.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
BASE = os.environ.get('BASE_URL', 'http://lb:8080').rstrip('/')
|
||||
PROJECT = os.environ.get('COMPOSE_PROJECT', 'messenger-lab4')
|
||||
SAMPLE = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
|
||||
|
||||
def docker(*args) -> str:
|
||||
return subprocess.run(['docker', *args], check=True, capture_output=True, text=True).stdout.strip()
|
||||
|
||||
|
||||
def call(method, path, body=None, auth=None, raw=None, ctype=None):
|
||||
h = {}
|
||||
if auth:
|
||||
h['Authorization'] = auth
|
||||
if body is not None:
|
||||
raw, ctype = json.dumps(body).encode(), 'application/json'
|
||||
if ctype:
|
||||
h['Content-Type'] = ctype
|
||||
req = urllib.request.Request(BASE + '/api/v1' + path, data=raw, headers=h, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=30) as r:
|
||||
return r.status, r.read(), r.headers.get('X-Instance-Id')
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, e.read(), e.headers.get('X-Instance-Id')
|
||||
|
||||
|
||||
def main() -> int:
|
||||
failed = 0
|
||||
replicas = docker('ps', '-q', '--no-trunc', '--filter', f'label=com.docker.compose.project={PROJECT}',
|
||||
'--filter', 'label=com.docker.compose.service=api').split()
|
||||
assert len(replicas) >= 2, 'need >= 2 running api replicas'
|
||||
|
||||
name = 'ufo' + uuid.uuid4().hex[:12]
|
||||
password = 'upload-failover-password'
|
||||
call('POST', '/users', {'username': name, 'display_name': 'UFO', 'password': password})
|
||||
basic = 'Basic ' + base64.b64encode(f'{name}:{password}'.encode()).decode()
|
||||
auth = 'Bearer ' + json.loads(call('POST', '/auth/sessions', auth=basic)[1])['token']
|
||||
me = json.loads(call('GET', '/users/me', auth=auth)[1])
|
||||
chat = json.loads(call('POST', '/chats', {'title': 'ufo', 'member_ids': [me['id']]}, auth=auth)[1])
|
||||
digest = hashlib.sha256(SAMPLE).hexdigest()
|
||||
|
||||
for target in replicas:
|
||||
alias = target[:12]
|
||||
for _ in range(20):
|
||||
s, body, instance = call('POST', f"/chats/{chat['id']}/attachments?filename=ufo.png",
|
||||
auth=auth, raw=SAMPLE, ctype='image/png')
|
||||
if s == 201 and target.startswith(instance):
|
||||
break
|
||||
else:
|
||||
print(f'FAIL could not hit replica {alias}')
|
||||
failed += 1
|
||||
continue
|
||||
att = json.loads(body)
|
||||
docker('stop', '--time', '15', target)
|
||||
time.sleep(1)
|
||||
try:
|
||||
served = set()
|
||||
ok = True
|
||||
for _ in range(4):
|
||||
s, data, instance = call('GET', f"/attachments/{att['id']}/content", auth=auth)
|
||||
served.add(instance)
|
||||
ok &= s == 200 and hashlib.sha256(data).hexdigest() == digest
|
||||
ok &= alias not in served
|
||||
failed += not ok
|
||||
print(f"{'OK ' if ok else 'FAIL'} upload через {alias} -> {alias} остановлена -> "
|
||||
f"download через {sorted(served)}: SHA-256 {'совпал' if ok else 'НЕ совпал'}", flush=True)
|
||||
finally:
|
||||
docker('start', target)
|
||||
for _ in range(60):
|
||||
if docker('inspect', '-f', '{{.State.Health.Status}}', target) == 'healthy':
|
||||
break
|
||||
time.sleep(1)
|
||||
time.sleep(3)
|
||||
|
||||
print('PASS: файл доступен после остановки любой обслужившей реплики' if not failed
|
||||
else f'FAIL: {failed}')
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,230 @@
|
||||
"""Эксперимент: пик памяти API при N одновременных загрузках (stdlib + docker CLI).
|
||||
|
||||
Гипотеза: память реплики ограничена конструкцией, а не числом/размером
|
||||
загрузок: тело пишется в SpooledTemporaryFile (в RAM <= UPLOAD_SPOOL_MEMORY_BYTES
|
||||
на загрузку), PNG проверяется потоково, одновременно <= MAX_CONCURRENT_UPLOADS
|
||||
на реплику. Ожидаем прирост пика RSS << N x размер файла.
|
||||
|
||||
Методика: перезапуск API-реплик (сброс high-water mark) -> базовые VmRSS/VmHWM ->
|
||||
N потоков одновременно (Barrier) загружают валидный PNG из шума ~9.5 MiB ->
|
||||
во время загрузок внутри каждой реплики каждые 100 мс читается VmRSS процесса
|
||||
API (/proc/1/status) и anon cgroup (без page cache временных файлов) -> пик
|
||||
минус базовое значение -> проверка SHA-256. VmHWM не годится: стартовый пик
|
||||
импорта библиотек (~170 MiB) выше пика загрузок.
|
||||
|
||||
docker compose --profile tools run --rm tester python3 student-tests/upload_memory.py --concurrency 12
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import collections
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import struct
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
import zlib
|
||||
|
||||
PROJECT = os.environ.get('COMPOSE_PROJECT', 'messenger-lab4')
|
||||
|
||||
|
||||
def docker(*args) -> str:
|
||||
return subprocess.run(['docker', *args], check=True, capture_output=True, text=True).stdout.strip()
|
||||
|
||||
|
||||
def service_containers(service: str) -> list[str]:
|
||||
return docker('ps', '-q', '--filter', f'label=com.docker.compose.project={PROJECT}',
|
||||
'--filter', f'label=com.docker.compose.service={service}').split()
|
||||
|
||||
|
||||
def api_containers() -> list[str]:
|
||||
return service_containers('api')
|
||||
|
||||
|
||||
def memory(cid: str) -> dict:
|
||||
out = docker('exec', cid, 'sh', '-c',
|
||||
'grep -E "^Vm(RSS|HWM)" /proc/1/status; '
|
||||
'echo "peak $(cat /sys/fs/cgroup/memory.peak 2>/dev/null || echo 0)"; '
|
||||
'echo "current $(cat /sys/fs/cgroup/memory.current)"; '
|
||||
'grep -E "^anon " /sys/fs/cgroup/memory.stat')
|
||||
values = {}
|
||||
for line in out.splitlines():
|
||||
name, value = line.replace(':', '').split()[:2]
|
||||
values[name] = int(value) * (1024 if name.startswith('Vm') else 1)
|
||||
return {k: round(v / 2 ** 20, 1) for k, v in values.items()}
|
||||
|
||||
|
||||
SAMPLER = ('while :; do r=$(grep VmRSS /proc/1/status | tr -s " " | cut -d" " -f2); '
|
||||
'a=$(grep "^anon " /sys/fs/cgroup/memory.stat | cut -d" " -f2); '
|
||||
'echo "$r $a"; sleep 0.1; done')
|
||||
|
||||
|
||||
class Sampler:
|
||||
def __init__(self, cid: str):
|
||||
self.proc = subprocess.Popen(['docker', 'exec', cid, 'sh', '-c', SAMPLER],
|
||||
stdout=subprocess.PIPE, text=True)
|
||||
self.rss = self.anon = 0
|
||||
self.samples = 0
|
||||
self.thread = threading.Thread(target=self._read, daemon=True)
|
||||
self.thread.start()
|
||||
|
||||
def _read(self):
|
||||
for line in self.proc.stdout:
|
||||
try:
|
||||
rss_kib, anon = map(int, line.split())
|
||||
except ValueError:
|
||||
continue
|
||||
self.rss = max(self.rss, rss_kib * 1024)
|
||||
self.anon = max(self.anon, anon)
|
||||
self.samples += 1
|
||||
|
||||
def stop(self) -> dict:
|
||||
self.proc.terminate()
|
||||
self.proc.wait()
|
||||
return {'VmRSS_peak': round(self.rss / 2 ** 20, 1), 'anon_peak': round(self.anon / 2 ** 20, 1),
|
||||
'samples': self.samples}
|
||||
|
||||
|
||||
def noise_png(target_bytes: int) -> bytes:
|
||||
width = 1800
|
||||
height = target_bytes // (width * 3 + 1)
|
||||
raw = b''.join(b'\x00' + os.urandom(width * 3) for _ in range(height))
|
||||
def chunk(kind, data):
|
||||
return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data))
|
||||
ihdr = struct.pack('>IIBBBBB', width, height, 8, 2, 0, 0, 0)
|
||||
return b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', ihdr) + chunk(b'IDAT', zlib.compress(raw, 1)) + chunk(b'IEND', b'')
|
||||
|
||||
|
||||
def call(base, method, path, body=None, auth=None, raw=None, ctype=None, timeout=120):
|
||||
h = {}
|
||||
if auth:
|
||||
h['Authorization'] = auth
|
||||
if body is not None:
|
||||
raw, ctype = json.dumps(body).encode(), 'application/json'
|
||||
if ctype:
|
||||
h['Content-Type'] = ctype
|
||||
req = urllib.request.Request(base + '/api/v1' + path, data=raw, headers=h, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return r.status, r.read(), r.headers.get('X-Instance-Id')
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, e.read(), e.headers.get('X-Instance-Id')
|
||||
|
||||
|
||||
def wait_ready(base, seconds=90):
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
with urllib.request.urlopen(base + '/health/ready', timeout=2) as r:
|
||||
if r.status == 200:
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
raise SystemExit('API is not ready')
|
||||
|
||||
|
||||
def main() -> int:
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument('--base-url', default=os.environ.get('BASE_URL', 'http://lb:8080'))
|
||||
p.add_argument('--concurrency', type=int, default=12)
|
||||
p.add_argument('--size-mib', type=float, default=9.5)
|
||||
p.add_argument('--no-restart', action='store_true')
|
||||
p.add_argument('--output')
|
||||
args = p.parse_args()
|
||||
base = args.base_url.rstrip('/')
|
||||
|
||||
data = noise_png(int(args.size_mib * 2 ** 20))
|
||||
digest = hashlib.sha256(data).hexdigest()
|
||||
print(f'file: {len(data)} bytes ({len(data) / 2 ** 20:.2f} MiB), concurrency {args.concurrency}', flush=True)
|
||||
|
||||
containers = api_containers()
|
||||
if not args.no_restart:
|
||||
docker('restart', '--time', '15', *containers)
|
||||
time.sleep(3)
|
||||
wait_ready(base)
|
||||
time.sleep(3)
|
||||
|
||||
name = 'mem' + uuid.uuid4().hex[:12]
|
||||
password = 'upload-memory-password'
|
||||
call(base, 'POST', '/users', {'username': name, 'display_name': 'Mem', 'password': password})
|
||||
basic = 'Basic ' + base64.b64encode(f'{name}:{password}'.encode()).decode()
|
||||
s, session, _ = call(base, 'POST', '/auth/sessions', auth=basic)
|
||||
auth = 'Bearer ' + json.loads(session)['token']
|
||||
user = json.loads(call(base, 'GET', '/users/me', auth=auth)[1])
|
||||
chat = json.loads(call(base, 'POST', '/chats', {'title': 'mem', 'member_ids': [user['id']]}, auth=auth)[1])
|
||||
|
||||
before = {c[:12]: memory(c) for c in containers}
|
||||
samplers = {c[:12]: Sampler(c) for c in containers}
|
||||
s3 = service_containers('s3')[0]
|
||||
s3_before = memory(s3)
|
||||
s3_sampler = Sampler(s3)
|
||||
time.sleep(1)
|
||||
barrier = threading.Barrier(args.concurrency)
|
||||
results = []
|
||||
lock = threading.Lock()
|
||||
|
||||
def worker():
|
||||
barrier.wait()
|
||||
t = time.monotonic()
|
||||
s, body, instance = call(base, 'POST', f"/chats/{chat['id']}/attachments?filename=noise.png",
|
||||
auth=auth, raw=data, ctype='image/png')
|
||||
with lock:
|
||||
results.append((s, time.monotonic() - t, instance, body))
|
||||
|
||||
started = time.monotonic()
|
||||
threads = [threading.Thread(target=worker) for _ in range(args.concurrency)]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
wall = time.monotonic() - started
|
||||
time.sleep(0.5)
|
||||
peaks = {c: sm.stop() for c, sm in samplers.items()}
|
||||
s3_peak = s3_sampler.stop()
|
||||
after = {c[:12]: memory(c) for c in containers}
|
||||
|
||||
ok = [r for r in results if r[0] == 201]
|
||||
sha_ok = all(json.loads(r[3])['sha256'] == digest for r in ok)
|
||||
if ok:
|
||||
att = json.loads(ok[0][3])
|
||||
s, content, _ = call(base, 'GET', f"/attachments/{att['id']}/content", auth=auth)
|
||||
sha_ok = sha_ok and hashlib.sha256(content).hexdigest() == digest
|
||||
latencies = sorted(r[1] for r in ok)
|
||||
summary = {
|
||||
'concurrency': args.concurrency,
|
||||
'file_bytes': len(data),
|
||||
'statuses': dict(collections.Counter(r[0] for r in results)),
|
||||
'per_instance': dict(collections.Counter(r[2] for r in results)),
|
||||
'wall_seconds': round(wall, 2),
|
||||
'latency_p50_s': round(latencies[len(latencies) // 2], 2) if latencies else None,
|
||||
'latency_max_s': round(latencies[-1], 2) if latencies else None,
|
||||
'sha256_ok': sha_ok,
|
||||
'memory_mib_before': before,
|
||||
'memory_mib_peak_during': peaks,
|
||||
'memory_mib_after': after,
|
||||
'rss_peak_increase_mib': {
|
||||
c: round(peaks[c]['VmRSS_peak'] - before[c]['VmRSS'], 1) for c in peaks
|
||||
},
|
||||
'anon_peak_increase_mib': {
|
||||
c: round(peaks[c]['anon_peak'] - before[c]['anon'], 1) for c in peaks
|
||||
},
|
||||
's3_server_mib': {'VmRSS_before': s3_before['VmRSS'], **s3_peak},
|
||||
'naive_in_memory_estimate_mib': round(args.concurrency * len(data) / 2 ** 20, 1),
|
||||
}
|
||||
text = json.dumps(summary, ensure_ascii=False, indent=2)
|
||||
print(text)
|
||||
if args.output:
|
||||
with open(args.output, 'w', encoding='utf-8') as f:
|
||||
f.write(text + '\n')
|
||||
return 0 if ok and sha_ok and all(r[0] in (201, 429) for r in results) else 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user