This commit is contained in:
Nurlygayanova Ekaterina
2026-11-05 19:36:11 +03:00
parent ec540a1a72
commit 354385e5f7
142 changed files with 13470 additions and 17 deletions
+97
View File
@@ -0,0 +1,97 @@
#!/usr/bin/env python3
"""Негативные и граничные сценарии вложений через работающий стенд. Создаёт синтетические данные."""
import hashlib
import uuid
from urllib.parse import quote
from common import Client, MAX_BYTES, MAX_PIXELS, SAMPLE_JPEG, SAMPLE_PNG, arguments, check, png_with_size, run
def main():
args = arguments('Attachment negative and boundary scenarios')
c = Client(args.base_url, args.ca_file, timeout=60)
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']
def upload(data, content_type='image/png', filename='a.png', actor=alice, target=chat, expected=201):
path = '/api/v1/chats/' + target['id'] + '/attachments?filename=' + quote(filename, safe='')
return c.call('POST', path, expected, actor=actor, raw=data, headers={'Content-Type': content_type},
schema='Attachment' if expected == 201 else None)
def rejected(name, expected, data, **kwargs):
response = upload(data, expected=expected, **kwargs)
print('ok %-44s -> %d %s' % (name, expected, response['json']['error']['code']))
half = SAMPLE_PNG[:len(SAMPLE_PNG) // 2]
flipped = bytearray(SAMPLE_PNG)
flipped[len(flipped) // 2] ^= 0xff
rejected('файл на байт больше лимита', 413, SAMPLE_PNG + b'\0' * (MAX_BYTES - len(SAMPLE_PNG) + 1))
rejected('размеры на пиксель больше лимита', 413, png_with_size(MAX_PIXELS + 1, 1))
rejected('«бомба» 100000x100000', 413, png_with_size(100000, 100000))
# Без Content-Length размер неизвестен заранее: лимит должен сработать при чтении.
rejected('chunked: файл на байт больше лимита', 413, iter([SAMPLE_PNG, b'\0' * (MAX_BYTES - len(SAMPLE_PNG) + 1)]))
rejected('заголовок PNG без пикселей', 415, png_with_size(16, 16))
rejected('обрезанный PNG', 415, half)
rejected('изменённый байт PNG', 415, bytes(flipped))
rejected('обрезанный JPEG', 415, SAMPLE_JPEG[:len(SAMPLE_JPEG) // 2], content_type='image/jpeg')
rejected('JPEG: только сигнатура', 415, b'\xff\xd8\xff', content_type='image/jpeg')
rejected('текст вместо картинки', 415, b'<script>alert(1)</script>')
rejected('пустое тело', 415, b'')
rejected('подмена: объявлен JPEG, внутри PNG', 415, SAMPLE_PNG, content_type='image/jpeg')
rejected('подмена: объявлен PNG, внутри JPEG', 415, SAMPLE_JPEG, content_type='image/png')
rejected('неподдерживаемый Content-Type', 415, SAMPLE_PNG, content_type='image/gif')
for name in ('../etc/passwd', 'a\\b.png', 'a\x00.png', 'a\nb.png', '..', ' ', 'x' * 256):
rejected('опасное имя %r' % name[:16], 400, SAMPLE_PNG, filename=name)
rejected('посторонний загружает в чужой чат', 404, SAMPLE_PNG, actor=eve)
rejected('посторонний: размер не важнее доступа', 404, b'\0' * (MAX_BYTES + 1), actor=eve)
exact = SAMPLE_PNG + b'\0' * (MAX_BYTES - len(SAMPLE_PNG))
att = upload(exact)['json']
check(att['size_bytes'] == MAX_BYTES, 'size mismatch at limit')
got = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob)
check(got['bytes'] == exact, 'byte-exact download failed at limit')
print('ok файл ровно 10 MiB принят и скачан побайтно')
jpeg = upload(SAMPLE_JPEG, content_type='image/jpeg', filename='фото.jpg')['json']
got = c.call('GET', '/api/v1/attachments/' + jpeg['id'] + '/content', actor=bob)
check(got['headers'].get_content_type() == 'image/jpeg', 'wrong JPEG content type')
check(hashlib.sha256(got['bytes']).hexdigest() == jpeg['sha256'], 'JPEG checksum mismatch')
print('ok JPEG с именем не ASCII принят и скачан, SHA-256 совпал')
for suffix in ('', '/content'):
c.call('GET', '/api/v1/attachments/' + jpeg['id'] + suffix, 404, actor=eve)
c.call('GET', '/api/v1/attachments/' + jpeg['id'] + suffix, 401)
c.call('GET', '/api/v1/attachments/not-a-uuid', 400, actor=alice)
c.call('GET', '/api/v1/attachments/' + str(uuid.uuid4()), 404, actor=alice)
print('ok посторонний 404, без сессии 401, неверный UUID 400, несуществующий 404')
foreign = upload(SAMPLE_PNG, target=other)['json']
messages = '/api/v1/chats/' + chat['id'] + '/messages'
key = {'Idempotency-Key': uuid.uuid4().hex}
c.call('POST', messages, 404, actor=alice, headers=key, body={'text': 'x', 'attachment_ids': [foreign['id']]})
c.call('POST', messages, 404, actor=alice, headers=key, body={'text': 'x', 'attachment_ids': [str(uuid.uuid4())]})
c.call('POST', messages, 400, actor=alice, headers=key, body={'text': '', 'attachment_ids': []})
c.call('POST', messages, 400, actor=alice, headers=key, body={'text': 'x', 'attachment_ids': [jpeg['id'], jpeg['id']]})
# Чужой файл: Eve загрузила его в свой чат, а Alice ссылается на него в своём и пытается прочитать.
eve_chat = c.call('POST', '/api/v1/chats', 201, actor=eve, body={'title': 'Чат Eve', 'member_ids': [eve['id']]}, schema='Chat')['json']
eve_file = upload(SAMPLE_PNG, actor=eve, target=eve_chat)['json']
c.call('POST', messages, 404, actor=alice, headers=key, body={'text': 'x', 'attachment_ids': [eve_file['id']]})
for suffix in ('', '/content'):
c.call('GET', '/api/v1/attachments/' + eve_file['id'] + suffix, 404, actor=alice)
# Смешанный список: одно своё вложение не даёт привязать чужое, сообщение не создаётся.
before = c.call('GET', messages + '?limit=100', actor=alice, schema='MessagePage')['json']['items']
c.call('POST', messages, 404, actor=alice, headers={'Idempotency-Key': uuid.uuid4().hex}, body={'text': 'x', 'attachment_ids': [jpeg['id'], foreign['id']]})
after = c.call('GET', messages + '?limit=100', actor=alice, schema='MessagePage')['json']['items']
check(len(after) == len(before), 'message was created with a foreign attachment')
print('ok вложение чужого чата 404, чужой пользователь 404, неизвестное 404, пустое сообщение 400, дубли 400, смешанный список без записи')
sent = c.message(alice, chat, 'с файлами', attachments=[att['id'], jpeg['id']])['json']
page = c.call('GET', messages + '?limit=100', actor=bob, schema='MessagePage')['json']
found = [m for m in page['items'] if m['id'] == sent['id']]
check(len(found) == 1 and found[0]['attachment_ids'] == [att['id'], jpeg['id']], 'attachment order lost in history')
print('ok второй участник читает сообщение, порядок вложений сохранён')
print('PASS: attachment negative and boundary scenarios')
if __name__ == '__main__':
run(main)
+25
View File
@@ -0,0 +1,25 @@
"""Общая часть собственных проверок: клиент из публичных тестов и построение тестовых файлов."""
import pathlib
import struct
import sys
import zlib
ROOT = pathlib.Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, Failure, arguments, check, run # noqa: E402,F401
SAMPLE_PNG = (ROOT / 'tests/fixtures/sample.png').read_bytes()
SAMPLE_JPEG = (ROOT / 'student-tests/fixtures/sample.jpg').read_bytes()
MAX_BYTES = 10 * 1024 * 1024
MAX_PIXELS = 40_000_000
def png_chunk(kind, data):
return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data))
def png_with_size(width, height):
"""Корректный заголовок с заданными размерами и почти без данных: так выглядит «бомба»."""
ihdr = struct.pack('>IIBBBBB', width, height, 8, 2, 0, 0, 0)
return b'\x89PNG\r\n\x1a\n' + png_chunk(b'IHDR', ihdr) + png_chunk(b'IDAT', zlib.compress(b'\0' * 16)) + png_chunk(b'IEND', b'')
+132
View File
@@ -0,0 +1,132 @@
#!/usr/bin/env python3
"""Track 1: negative scenarios, expiry, and API traffic/RAM at 1 and 8 MiB."""
import hashlib
import json
import subprocess
import time
import urllib.error
import urllib.request
from urllib.parse import urlsplit, urlunsplit
from common import Client, SAMPLE_PNG, arguments, check, run
from memory_concurrent import Sampler, anon_bytes, container_read, replicas
def put(upload, data, expected=200):
req = urllib.request.Request(upload['url'], data=data, headers=upload['headers'], method='PUT')
try:
response = urllib.request.urlopen(req, timeout=60)
except urllib.error.HTTPError as exc:
response = exc
with response:
response.read()
check(response.status == expected, 'S3 PUT: expected %d, got %d' % (expected, response.status))
def traffic(containers):
rx = tx = 0
for container in containers:
for line in container_read(container, '/proc/net/dev').splitlines():
if ':' in line and line.split(':')[0].strip() != 'lo':
values = line.split(':')[1].split()
rx += int(values[0])
tx += int(values[8])
return rx, tx
def main():
def configure(parser):
parser.add_argument('--skip-expiry', action='store_true', help='Skip real-clock expiry during a quick contract recheck')
args = arguments(__doc__, configure)
c = Client(args.base_url, args.ca_file, timeout=90)
alice, bob, eve, chat = c.bootstrap()
path = '/api/v1/chats/' + chat['id'] + '/attachments'
def init(data=SAMPLE_PNG, expected=201, actor=alice, **overrides):
body = dict(filename='direct.png', content_type='image/png', size_bytes=len(data), sha256=hashlib.sha256(data).hexdigest())
body.update(overrides)
out = c.call('POST', path+'/direct/init', expected, actor=actor, body=body)
return json.loads(out['bytes'])
def complete(u, expected=201, actor=alice, target=path):
return c.call('POST', target+'/direct/complete', expected, actor=actor, body={'token':u['token']}, schema='Attachment' if expected == 201 else None)
started = time.monotonic()
expired = init()
abandoned = init()
put(abandoned, SAMPLE_PNG)
init(expected=401, actor=None)
init(expected=404, actor=eve)
init(expected=413, size_bytes=10*1024*1024+1)
init(expected=400, sha256='bad')
init(expected=415, content_type='image/png; charset=utf-8')
init(expected=400, extra='unknown field')
init(expected=400, size_bytes=True)
c.call('POST', path+'/direct/complete', 400, actor=alice, body={'token':'x', 'extra':1})
c.call('POST', path+'/direct/complete', 400, actor=alice, raw=b'{"token":"x"} {}', headers={'Content-Type':'application/json'})
missing = init()
complete(missing, 409)
put(missing, SAMPLE_PNG)
complete(missing, 404, actor=bob) # Even another member cannot complete this ticket.
complete(missing, 404, actor=eve)
other = c.call('POST', '/api/v1/chats', 201, actor=alice, body={'title':'other', 'member_ids':[alice['id']]}, schema='Chat')['json']
complete(missing, 404, target='/api/v1/chats/'+other['id']+'/attachments')
complete(dict(missing, token='A'+missing['token'][1:]), 400)
altered = dict(missing)
parts = urlsplit(missing['url'])
altered['url'] = urlunsplit(parts._replace(path=parts.path+'x'))
put(altered, SAMPLE_PNG, 403)
wrong_sum = init(sha256='0'*64)
put(wrong_sum, SAMPLE_PNG)
complete(wrong_sum, 400)
wrong_size = init(size_bytes=len(SAMPLE_PNG)+1)
# Signed content length must be enforced by the actual S3 implementation.
put(wrong_size, SAMPLE_PNG, 403)
invalid = init(data=b'not an image')
put(invalid, b'not an image')
complete(invalid, 415)
good = complete(missing)['json']
check(complete(missing)['json']['id'] == good['id'], 'complete is not idempotent')
put(missing, b'x'*len(SAMPLE_PNG))
downloaded = c.call('GET', '/api/v1/attachments/'+good['id']+'/content', actor=alice)['bytes']
check(downloaded == SAMPLE_PNG, 'presigned replay modified a ready attachment')
print('PASS: auth, membership/owner/chat, limit, missing PUT, tampered token/key, checksum, size, invalid image, retry, overwrite protection', flush=True)
containers = replicas()
print('mode size_bytes api_rx_bytes api_tx_bytes anon_before_MiB anon_peak_MiB', flush=True)
for size in (1024*1024, 8*1024*1024):
# Same tiny image, different payload sizes: isolate buffering from decoder RAM.
data = SAMPLE_PNG + b'\0'*(size-len(SAMPLE_PNG))
for mode in ('proxy', 'direct'):
before_ram = max(anon_bytes(x) for x in containers)
sampler = Sampler(containers)
sampler.start()
before = traffic(containers)
try:
if mode == 'proxy':
c.call('POST', path+'?filename=proxy.png', 201, actor=alice, raw=data, headers={'Content-Type':'image/png'}, schema='Attachment')
else:
u = init(data)
put(u, data)
complete(u)
after = traffic(containers)
finally:
sampler.done.set()
sampler.join()
peak = max(before_ram, *sampler.peak.values())
print(mode, size, after[0]-before[0], after[1]-before[1], round(before_ram/2**20,2), round(peak/2**20,2), flush=True)
if args.skip_expiry:
print('SKIP: real-clock expiry; run without --skip-expiry for the full check', flush=True)
return
print('Waiting for real signature/ticket expiration...', flush=True)
time.sleep(max(0, 62-(time.monotonic()-started)))
put(expired, SAMPLE_PNG, 403)
time.sleep(max(0, 122-(time.monotonic()-started)))
complete(abandoned, 409)
print('PASS: expired PUT -> 403; abandoned upload complete after 120s -> 409; no ready metadata created', flush=True)
print('Abandoned staging key (janitor after grace):', urlsplit(abandoned['url']).path, flush=True)
if __name__ == '__main__':
run(main)
Binary file not shown.

After

Width:  |  Height:  |  Size: 896 B

+138
View File
@@ -0,0 +1,138 @@
#!/usr/bin/env python3
"""Память реплик при одновременных загрузках файлов на границе 10 МиБ. Только стандартная библиотека.
Файл: случайный несжатый PNG примерно на 3,5 Мп, размером почти ровно 10 МиБ. Его декодирование
дешёвое, поэтому результат показывает расход на приём тела, а не на декодирование 40 Мп (для этого
есть memory_peak.py).
Что измеряется для каждой реплики:
anon — анонимная память процесса (куча и стеки), опрос memory.stat каждые 0,2 с;
peak — memory.peak из cgroup, точный максимум, но он включает вытесняемый дисковый кэш.
Запускать на только что перезапущенных репликах, иначе peak включает более ранние нагрузки.
"""
from concurrent.futures import ThreadPoolExecutor
import hashlib
import os
import statistics
import subprocess
import threading
import time
import struct
import zlib
from common import Client, MAX_BYTES, ROOT, arguments, check, png_chunk, run
COMPOSE = ['docker', 'compose', '--env-file', '.env']
LIMIT = 1024 ** 3
MIB = 1024 ** 2
def noise_png(target):
"""Несжимаемый PNG truecolor размером не больше target байт."""
width = 2048
height = (target - 1024) // (width * 3 + 1)
raw = b''.join(b'\0' + os.urandom(width * 3) for _ in range(height))
ihdr = struct.pack('>IIBBBBB', width, height, 8, 2, 0, 0, 0)
data = b'\x89PNG\r\n\x1a\n' + png_chunk(b'IHDR', ihdr) + png_chunk(b'IDAT', zlib.compress(raw, 0)) + png_chunk(b'IEND', b'')
check(len(data) <= target, 'test file exceeds target size')
return data
def replicas():
return subprocess.run(COMPOSE + ['ps', '-q', 'api'], cwd=ROOT, check=True, capture_output=True, text=True).stdout.split()
def container_read(container, path):
return subprocess.run(['docker', 'exec', container, 'cat', path], check=True, capture_output=True, text=True).stdout
def anon_bytes(container):
for line in container_read(container, '/sys/fs/cgroup/memory.stat').splitlines():
name, value = line.split()
if name == 'anon':
return int(value)
raise RuntimeError('anon is missing from memory.stat')
def memory_event(container, name):
"""Счётчик из memory.events: max — упор в лимит (ядро вытесняет кэш), oom_kill — убитые процессы."""
for line in container_read(container, '/sys/fs/cgroup/memory.events').splitlines():
key, value = line.split()
if key == name:
return int(value)
raise RuntimeError(name + ' is missing from memory.events')
class Sampler(threading.Thread):
"""Опрашивает анонимную память реплик и помнит максимум."""
def __init__(self, containers):
super().__init__(daemon=True)
self.containers = containers
self.peak = {c: 0 for c in containers}
self.samples = 0
self.done = threading.Event()
def run(self):
while not self.done.is_set():
for container in self.containers:
try:
self.peak[container] = max(self.peak[container], anon_bytes(container))
except (subprocess.CalledProcessError, RuntimeError):
pass
self.samples += 1
self.done.wait(0.2)
def main():
parser_args = arguments('Replica memory under concurrent uploads', None)
concurrency = int(os.environ.get('UPLOADS', '20'))
rounds = int(os.environ.get('ROUNDS', '3'))
check(concurrency >= 10, 'the experiment needs at least 10 concurrent uploads')
c = Client(parser_args.base_url, parser_args.ca_file, timeout=120)
alice, _, _, chat = c.bootstrap()
path = '/api/v1/chats/' + chat['id'] + '/attachments?filename=load.png'
data = noise_png(MAX_BYTES)
digest = hashlib.sha256(data).hexdigest()
print('файл: %d байт, одновременно: %d, раундов: %d' % (len(data), concurrency, rounds))
containers = replicas()
before = {x: anon_bytes(x) for x in containers}
sampler = Sampler(containers)
sampler.start()
def upload(_):
client = Client(parser_args.base_url, parser_args.ca_file, timeout=120)
started = time.monotonic()
response = client.call('POST', path, [201, 429], actor=alice, raw=data, headers={'Content-Type': 'image/png'}, schema='Attachment')
if response['status'] == 201:
check(response['json']['sha256'] == digest, 'checksum differs after concurrent upload')
return response['status'], time.monotonic() - started
results = []
started = time.monotonic()
with ThreadPoolExecutor(max_workers=concurrency) as pool:
for _ in range(rounds):
results += list(pool.map(upload, range(concurrency)))
elapsed = time.monotonic() - started
sampler.done.set()
sampler.join()
ok = sorted(seconds for status, seconds in results if status == 201)
print('длительность %.1f с; 201=%d, 429=%d; опросов памяти: %d' % (elapsed, len(ok), len(results) - len(ok), sampler.samples))
if ok:
p95 = ok[min(len(ok) - 1, int(len(ok) * 0.95))]
print('время успешной загрузки: p50=%.2f с, p95=%.2f с, max=%.2f с' % (statistics.median(ok), p95, ok[-1]))
for x in containers:
peak = int(container_read(x, '/sys/fs/cgroup/memory.peak'))
state = subprocess.run(['docker', 'inspect', '--format', '{{.State.OOMKilled}} {{.RestartCount}}', x], check=True, capture_output=True, text=True).stdout.split()
kills = memory_event(x, 'oom_kill')
print('реплика %s: anon до %d МиБ, пик anon %d МиБ, memory.peak %d МиБ, упоров в лимит %d, oom_kill=%d, перезапусков=%s' % (
x[:12], before[x] // MIB, sampler.peak[x] // MIB, peak // MIB, memory_event(x, 'max'), kills, state[1]))
check(sampler.peak[x] < LIMIT and kills == 0 and state == ['false', '0'], 'replica ran out of memory or was restarted')
print('PASS: concurrent uploads caused no OOM or restart')
if __name__ == '__main__':
run(main)
+79
View File
@@ -0,0 +1,79 @@
#!/usr/bin/env python3
"""Пик памяти реплик на худших допустимых файлах. Нужен Pillow: .venv/bin/pip install pillow.
Запускать на только что запущенных репликах, иначе пик включает более ранние нагрузки.
Критерий: нет OOM и перезапусков, анонимная память ниже лимита контейнера. memory.peak только
выводится: он включает вытесняемый дисковый кэш временных файлов, поэтому может дойти до лимита без
всякой опасности (ядро просто освобождает кэш). Счётчик max показывает, сколько раз это случилось.
"""
from concurrent.futures import ThreadPoolExecutor
import io
import subprocess
from PIL import Image
from common import Client, MAX_BYTES, arguments, check, run
from memory_concurrent import LIMIT, MIB, Sampler, container_read, memory_event, replicas
Image.MAX_IMAGE_PIXELS = None
def report(label, sampler):
values = []
for container in sampler.containers:
values.append('%s: anon %d, memory.peak %d МиБ, упоров в лимит %d, oom_kill=%d' % (
container[:12], sampler.peak[container] // MIB, int(container_read(container, '/sys/fs/cgroup/memory.peak')) // MIB,
memory_event(container, 'max'), memory_event(container, 'oom_kill')))
print(label, *values, sep='\n ', flush=True)
for container in sampler.containers:
check(sampler.peak[container] < LIMIT and memory_event(container, 'oom_kill') == 0, 'replica ran out of memory')
def main():
args = arguments('Peak memory on worst allowed uploads', None)
c = Client(args.base_url, args.ca_file, timeout=120)
alice, _, _, chat = c.bootstrap()
path = '/api/v1/chats/' + chat['id'] + '/attachments?filename=x'
containers = replicas()
sampler = Sampler(containers)
sampler.start()
report('до загрузок', sampler)
def upload(data, content_type, client=c):
return client.call('POST', path, [201, 429], actor=alice, raw=data, headers={'Content-Type': content_type})
# Прогрессивный JPEG 4:4:4 — самый затратный вариант: декодер хранит коэффициенты всех компонентов.
picture = Image.effect_noise((400, 250), 60).convert('RGB').resize((8000, 5000))
buffer = io.BytesIO()
picture.save(buffer, 'JPEG', progressive=True, quality=40, subsampling=0)
check(len(buffer.getvalue()) <= MAX_BYTES, 'test file exceeds byte limit')
for _ in range(4):
response = upload(buffer.getvalue(), 'image/jpeg')
check(response['status'] == 201, 'worst-case JPEG rejected')
report('4 x JPEG 40 Мп, progressive 4:4:4', sampler)
# Худший случай целиком: тот же JPEG, дополненный до 10 МиБ нулями после конца изображения.
# Декодируется один файл за раз, остальные ждут своей очереди во временных файлах, а не в памяти.
big = buffer.getvalue() + b'\0' * (MAX_BYTES - len(buffer.getvalue()))
def parallel(_):
return upload(big, 'image/jpeg', Client(args.base_url, args.ca_file, timeout=120))['status']
with ThreadPoolExecutor(max_workers=24) as pool:
statuses = list(pool.map(parallel, range(24)))
print('24 одновременные загрузки JPEG 40 Мп по 10 МиБ: 201=%d, 429=%d (очередь на декодирование)' % (statuses.count(201), statuses.count(429)))
check(statuses.count(201) + statuses.count(429) == len(statuses), 'unexpected status')
report('после параллельных загрузок', sampler)
sampler.done.set()
sampler.join()
for container in containers:
state = subprocess.run(['docker', 'inspect', '--format', '{{.State.OOMKilled}} {{.RestartCount}}', container], check=True, capture_output=True, text=True).stdout.split()
check(state == ['false', '0'], 'replica was OOM-killed or restarted')
# Реплика после всего этого обслуживает запросы.
c.call('GET', '/health/ready', schema='Health')
print('OOMKilled=false, RestartCount=0 у всех реплик, readiness 200')
print('PASS: no OOM or restart, anonymous memory stays below the %d MiB container limit' % (LIMIT // MIB))
if __name__ == '__main__':
run(main)
+99
View File
@@ -0,0 +1,99 @@
#!/usr/bin/env python3
"""Validate real API exchanges against OpenAPI; public tests stay unchanged."""
import argparse
from collections import Counter
import json
import re
import sys
from urllib.parse import parse_qs, urlsplit
from jsonschema import Draft202012Validator, FormatChecker
from referencing import Registry, Resource
from common import Client, ROOT, check
SPEC = json.loads((ROOT/'contracts/openapi.json').read_text())
RESOURCE = dict(SPEC, **{'$schema':'https://json-schema.org/draft/2020-12/schema'})
REGISTRY = Registry().with_resource('urn:mtusi:openapi', Resource.from_contents(RESOURCE))
OBSERVED = Counter()
def validate(value, schema):
# Put the schema under the same base URI so local component references resolve.
wrapped = dict(RESOURCE)
wrapped['$id'] = 'urn:mtusi:openapi'
wrapped.update(schema)
Draft202012Validator(wrapped, registry=REGISTRY, format_checker=FormatChecker()).validate(value)
original_call = Client.call
def checked_call(self, method, path, *args, **kwargs):
split = urlsplit(path)
matches = [(template, operations) for template, operations in SPEC['paths'].items()
if re.fullmatch(re.sub(r'\{[^}]+\}', '[^/]+', template), split.path)]
check(len(matches) == 1, 'Undocumented/ambiguous API route: '+method+' '+path)
template, operations = matches[0]
check(method.lower() in operations, 'Undocumented method: '+method+' '+template)
operation = operations[method.lower()]
response = original_call(self, method, path, *args, **kwargs)
status = str(response['status'])
check(status in operation['responses'], 'Undocumented response: '+method+' '+template+' '+status)
declared = operation['responses'][status]
for name, header in declared.get('headers', {}).items():
value = response['headers'].get(name)
if value is not None:
schema = header['schema']
if schema.get('type') == 'integer':
value = int(value)
validate(value, schema)
if declared.get('content'):
media = response['headers'].get_content_type()
check(media in declared['content'], 'Undocumented response Content-Type: '+media)
schema = declared['content'][media]['schema']
if media == 'application/json':
validate(json.loads(response['bytes']), schema)
else:
check(not response['bytes'], 'Body returned for a response with no content')
if response['status'] < 400:
body = kwargs.get('body')
if body is not None:
validate(body, operation['requestBody']['content']['application/json']['schema'])
query = parse_qs(split.query)
path_values = dict(zip(re.findall(r'\{([^}]+)\}', template),
[v for t, v in zip(template.split('/'), split.path.split('/')) if t.startswith('{')]))
for parameter in operation.get('parameters', []):
values = {'path': path_values, 'query': query, 'header': kwargs.get('headers', {})}.get(parameter['in'], {})
name, schema = parameter['name'], parameter['schema']
check(not parameter.get('required') or name in values, 'Required parameter missing: '+name)
if name in values:
value = values[name]
if isinstance(value, list):
value = value[0]
if schema.get('type') == 'integer':
value = int(value)
validate(value, schema)
OBSERVED[(method, template, status)] += 1
return response
def main():
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('--scenario', choices=['smoke', 'attachments'], default='smoke')
args, remainder = parser.parse_known_args()
sys.argv = [sys.argv[0], *remainder]
Client.call = checked_call
if args.scenario == 'smoke':
import smoke as scenario
else:
import attachments as scenario
scenario.main()
for (method, path, status), count in sorted(OBSERVED.items()):
print('%s %s -> %s: %d checked' % (method, path, status, count))
routes = {(m, p) for m, p, _ in OBSERVED}
print('PASS: actual request/response schemas, formats, headers and statuses match OpenAPI; %d operations, %d exchanges' % (len(routes), sum(OBSERVED.values())))
if __name__ == '__main__':
main()
+192
View File
@@ -0,0 +1,192 @@
#!/usr/bin/env python3
"""Отказы между S3 и PostgreSQL на работающем стенде: компенсация, падение процесса, обрыв загрузки.
Отказ БД создаётся настоящей блокировкой: LOCK TABLE attachments IN SHARE MODE не мешает чтению, но
задерживает INSERT. Пока он ждёт, объект уже в S3, а строки ещё нет. Это и есть опасное окно.
Останавливает реплики API сигналом SIGKILL и возвращает их. Тома не трогает. Занимает около 6 минут.
"""
import hashlib
import json
import socket
import subprocess
import threading
import time
from urllib.parse import urlsplit
from common import Client, Failure, ROOT, SAMPLE_PNG, arguments, check, run
COMPOSE = ['docker', 'compose', '--env-file', '.env']
MIN_GRACE = 300
LOCK_SECONDS = 10
def compose(*command, **kwargs):
return subprocess.run(COMPOSE + list(command), cwd=ROOT, check=True, capture_output=True, text=True, **kwargs).stdout
def janitor(grace=3600, dry_run=False):
"""Один проход очистителя со своими настройками; работающий сервис остаётся с grace 1 час."""
flags = ['-once'] + (['-dry-run'] if dry_run else [])
out = compose('run', '--rm', '--no-deps', '-T', '-e', 'JANITOR_GRACE_SECONDS=%d' % grace, 'janitor', *flags)
for line in out.splitlines():
if line.startswith('{"janitor_report"'):
return json.loads(line)['janitor_report']
raise Failure('janitor printed no report')
def show(label, report):
print('%-52s просмотрено=%d свежих=%d со строкой=%d без строки=%d удалено=%d' % (
label, report['scanned'], report['fresh'], report['referenced'], report['orphans'], report['deleted']), flush=True)
def sql(query):
return int(compose('exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-Atc', query).strip())
def rows():
return sql('SELECT count(*) FROM attachments')
class TableLock:
"""Держит блокировку в отдельной транзакции, пока не истечёт время или не вызван release."""
def __enter__(self):
sql = 'BEGIN; LOCK TABLE attachments IN SHARE MODE; SELECT pg_sleep(%d); COMMIT;' % LOCK_SECONDS
self.process = subprocess.Popen(COMPOSE + ['exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-c', sql],
cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
time.sleep(1.5) # блокировка должна быть получена до загрузки
return self
def __exit__(self, *_):
self.process.wait(timeout=LOCK_SECONDS + 10)
def interrupted_upload(base_url, token, chat_id, sent, declared):
"""Отправляет часть объявленного тела и закрывает соединение."""
url = urlsplit(base_url)
with socket.create_connection((url.hostname, url.port or 80), timeout=10) as connection:
connection.sendall((
'POST /api/v1/chats/%s/attachments?filename=cut.png HTTP/1.1\r\nHost: %s\r\nAuthorization: Bearer %s\r\n'
'Content-Type: image/png\r\nContent-Length: %d\r\n\r\n' % (chat_id, url.hostname, token, declared)).encode())
connection.sendall(SAMPLE_PNG[:sent])
def main():
args = arguments('Failures between S3 and PostgreSQL')
c = Client(args.base_url, args.ca_file, timeout=30)
alice, bob, _, chat = c.bootstrap()
path = '/api/v1/chats/' + chat['id'] + '/attachments?filename=sample.png'
headers = {'Content-Type': 'image/png'}
def upload(client=c, expected=201, schema='Attachment'):
return client.call('POST', path, expected, actor=alice, raw=SAMPLE_PNG, headers=headers, schema=schema)
def verify_download(attachment):
got = c.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content', actor=bob)
check(hashlib.sha256(got['bytes']).hexdigest() == attachment['sha256'], 'attached file changed')
# Объекты, которые нельзя потерять: один привязан к сообщению, другой ещё ни к чему не привязан.
linked = upload()['json']
c.message(alice, chat, 'с вложением', attachments=[linked['id']])
unlinked = upload()['json']
print('== Очистка старых объектов от предыдущих прогонов')
show('старые неучтённые объекты', janitor(grace=MIN_GRACE))
print('== Исходное состояние')
show('очиститель, только отчёт', janitor(dry_run=True))
before = janitor(dry_run=True)['scanned']
rows_before = rows()
print('== 1. Отказ БД между PUT и INSERT: компенсация')
with TableLock():
started = time.monotonic()
failed = upload(expected=503, schema=None)
print('INSERT заблокирован: клиент получил %d за %.1f с' % (failed['status'], time.monotonic() - started))
report = janitor(dry_run=True)
show('после компенсации', report)
check(report['scanned'] == before and rows() == rows_before, 'compensation left an object or a row')
print('ok объект удалён сразу, строки нет, очиститель не понадобился')
print('== 2. Падение процесса между PUT и INSERT: kill -9')
outcome = {}
def doomed():
try:
outcome['status'] = upload(Client(args.base_url, args.ca_file, timeout=30), [201, 500, 502, 503, 504], schema=None)['status']
except Failure as failure:
outcome['error'] = type(failure).__name__
with TableLock():
thread = threading.Thread(target=doomed)
thread.start()
time.sleep(1.5) # PUT прошёл, INSERT ждёт блокировку
replicas = compose('ps', '-q', 'api').split()
subprocess.run(['docker', 'kill', '--signal', 'SIGKILL'] + replicas, check=True, capture_output=True)
thread.join()
# INSERT убитой реплики всё ещё ждёт блокировку внутри PostgreSQL и выполнился бы после её снятия:
# тогда и файл, и строка на месте, расхождения нет. Здесь нужен случай, когда запись не дошла до
# COMMIT, поэтому обслуживающий её процесс БД завершается. Итог тот же, что при падении до INSERT.
terminated = sql("SELECT count(pg_terminate_backend(pid)) FROM pg_stat_activity "
"WHERE wait_event_type = 'Lock' AND query LIKE '%INSERT INTO attachments%'")
check(terminated == 1, 'expected exactly one blocked INSERT, got %d' % terminated)
print('реплики убиты SIGKILL: клиент получил %s' % (outcome.get('status') or 'обрыв соединения'))
compose('up', '-d', '--wait')
time.sleep(3)
crashed_at = time.monotonic()
check(rows() == rows_before, 'row appeared for the crashed upload')
fresh = janitor(dry_run=True)
show('сразу после падения, grace 1 ч', fresh)
check(fresh['scanned'] == before + 1, 'orphan was not found in the bucket')
check(janitor(grace=MIN_GRACE)['deleted'] == 0, 'fresh object was deleted')
print('ok объект без строки есть в bucket, но он моложе grace period: не тронут')
time.sleep(max(0, MIN_GRACE + 2 - (time.monotonic() - crashed_at)))
# Свежая загрузка прямо перед очисткой: её объект должен пережить проход.
newest = upload()['json']
dry = janitor(grace=MIN_GRACE, dry_run=True)
show('через %d с, только отчёт' % MIN_GRACE, dry)
check(dry['deleted'] == 0, 'dry run deleted an object')
check(dry['orphans'] >= 1, 'orphan was not detected')
check(janitor(dry_run=True)['scanned'] == before + 2, 'dry run changed the bucket')
print('ok только отчёт: объект найден, ничего не удалено')
orphans = dry['orphans']
cleaned = janitor(grace=MIN_GRACE)
show('через %d с, очистка' % MIN_GRACE, cleaned)
check(cleaned['deleted'] == orphans, 'wrong number of objects deleted')
again = janitor(grace=MIN_GRACE)
show('повторный проход', again)
check(again['deleted'] == 0 and again['orphans'] == 0, 'second pass is not idempotent')
for attachment in (linked, unlinked, newest):
verify_download(attachment)
print('ok объект удалён, повтор ничего не меняет; файл сообщения, файл без сообщения и свежий файл скачиваются, SHA-256 совпал')
print('== 3. Обрыв загрузки клиентом')
state = janitor(dry_run=True)['scanned']
rows_state = rows()
# Попыток больше, чем слотов на реплику: утечка слота дала бы 429 на следующей загрузке.
for _ in range(40):
interrupted_upload(c.base, alice['token'], chat['id'], len(SAMPLE_PNG) // 2, len(SAMPLE_PNG))
time.sleep(3)
report = janitor(dry_run=True)
show('после 40 оборванных загрузок', report)
check(report['scanned'] == state and rows() == rows_state, 'interrupted upload left an object or a row')
for container in compose('ps', '-q', 'api').split():
listing = subprocess.run(['docker', 'exec', container, 'ls', '-A', '/tmp'], check=True, capture_output=True, text=True).stdout
check(listing == '', 'temporary files are left on a replica')
print('ok объектов и строк не прибавилось, каталог временных файлов пуст на всех репликах')
for _ in range(4):
last = upload()['json']
verify_download(last)
print('ok слоты не утекли: следующие загрузки проходят')
final = janitor(grace=MIN_GRACE, dry_run=True)
rows_final = rows()
print('итог: объектов %d, строк %d' % (final['scanned'], rows_final))
check(final['scanned'] == rows_final, 'objects and rows differ')
print('PASS: failures between S3 and PostgreSQL leave no unaccounted objects')
if __name__ == '__main__':
run(main)
+61
View File
@@ -0,0 +1,61 @@
#!/usr/bin/env python3
"""Отказ S3: вложения отвечают 503, остальное API работает, после возврата файл на месте.
Останавливает и запускает сервис s3 на текущем стенде; volume не трогает.
"""
import subprocess
import time
import uuid
from common import Client, ROOT, SAMPLE_PNG, arguments, check, run
COMPOSE = ['docker', 'compose', '--env-file', '.env']
RECOVERY_LIMIT = 90
def compose(*command):
subprocess.run(COMPOSE + list(command), cwd=ROOT, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
def main():
args = arguments('S3 outage scenario')
c = Client(args.base_url, args.ca_file, timeout=30)
alice, bob, _, chat = c.bootstrap()
upload = '/api/v1/chats/' + chat['id'] + '/attachments?filename=sample.png'
headers = {'Content-Type': 'image/png'}
att = c.call('POST', upload, 201, actor=alice, raw=SAMPLE_PNG, headers=headers, schema='Attachment')['json']
content = '/api/v1/attachments/' + att['id'] + '/content'
compose('stop', 's3')
print('s3 stopped')
try:
def measured(name, *call_args, **call_kwargs):
response = c.call(*call_args, **call_kwargs)
print('%-34s %d in %.2fs' % (name, response['status'], response['elapsed']))
return response
first = measured('upload without S3', 'POST', upload, 503, actor=alice, raw=SAMPLE_PNG, headers=headers)
check(first['json']['error']['code'] == 'unavailable', 'wrong error code')
check(first['elapsed'] < 15, 'answer slower than LB timeout')
measured('download without S3', 'GET', content, 503, actor=bob)
measured('metadata without S3', 'GET', '/api/v1/attachments/' + att['id'], 200, actor=bob, schema='Attachment')
measured('text message without S3', 'POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=alice,
body={'text': 'без S3'}, headers={'Idempotency-Key': uuid.uuid4().hex}, schema='Message')
measured('readiness without S3', 'GET', '/health/ready', 200, schema='Health')
finally:
compose('start', 's3')
started = time.monotonic()
while True:
response = c.call('GET', content, [200, 503], actor=bob)
if response['status'] == 200:
break
check(time.monotonic() - started < RECOVERY_LIMIT, 'S3 did not recover in time')
time.sleep(1)
check(response['bytes'] == SAMPLE_PNG, 'file changed across S3 outage')
print('download recovered in %.1fs after start, bytes match' % (time.monotonic() - started))
c.call('POST', upload, 201, actor=alice, raw=SAMPLE_PNG, headers=headers, schema='Attachment')
print('upload works again')
print('PASS: S3 outage is contained to attachments and loses no data')
if __name__ == '__main__':
run(main)
+50
View File
@@ -0,0 +1,50 @@
#!/usr/bin/env python3
"""Загрузка -> остановка реплики, ОБСЛУЖИВШЕЙ загрузку -> скачивание через другую.
Публичный resilience.py останавливает реплику, принявшую сообщение; сценарий README требует именно
реплику, принявшую файл, поэтому он проверяется отдельно. Реплику возвращает вызывающий скрипт.
"""
import hashlib
import os
import subprocess
import time
from common import Client, ROOT, SAMPLE_PNG, arguments, check, run
def main():
def configure(parser):
parser.add_argument('--avoid-instance', default='', help='Не останавливать эту реплику: так проверяется каждая по очереди')
args = arguments('Upload, stop the replica that served it, download via another', configure)
c = Client(args.base_url, args.ca_file, timeout=10)
alice, bob, _, chat = c.bootstrap()
path = '/api/v1/chats/' + chat['id'] + '/attachments?filename=sample.png'
for _ in range(10):
response = c.call('POST', path, 201, actor=alice, raw=SAMPLE_PNG, headers={'Content-Type': 'image/png'}, schema='Attachment')
target = response['headers']['X-Instance-Id']
if target != args.avoid_instance:
break
check(target != args.avoid_instance, 'all uploads were served by the replica to avoid')
attachment = response['json']
print('upload served by replica', target, 'status', response['status'])
env = dict(os.environ, TARGET_INSTANCE_ID=target)
subprocess.run([str(ROOT / 'scripts/stop-one.sh')], env=env, check=True, stdout=subprocess.DEVNULL)
print('replica', target, 'stopped')
url = '/api/v1/attachments/' + attachment['id'] + '/content'
served = set()
started = time.monotonic()
for _ in range(5):
download = c.call('GET', url, actor=bob)
served.add(download['headers']['X-Instance-Id'])
check(download['bytes'] == SAMPLE_PNG, 'downloaded bytes differ')
check(hashlib.sha256(download['bytes']).hexdigest() == attachment['sha256'], 'checksum differs')
check(target not in served, 'stopped replica still serves downloads')
print('downloaded 5 times via', sorted(served), 'in %.3fs, SHA-256 matches' % (time.monotonic() - started))
print('PASS: file survives stop of the replica that uploaded it')
print('STOPPED=' + target)
if __name__ == '__main__':
run(main)