lab4
This commit is contained in:
Executable
+80
@@ -0,0 +1,80 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Upload through one API replica, stop it, download through another.
|
||||
|
||||
Run against a live stand:
|
||||
python3 student-tests/attachment_failover.py --base-url http://localhost:8080
|
||||
"""
|
||||
import hashlib
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
|
||||
from client import Client, Failure, arguments, check, run # noqa: E402
|
||||
from tests_helpers import ROOT, compose # noqa: E402
|
||||
|
||||
FIXTURE = Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png'
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Attachment failover across API replicas (lab4)')
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
alice, bob, _, chat = client.bootstrap()
|
||||
content = FIXTURE.read_bytes()
|
||||
|
||||
response = client.call(
|
||||
'POST',
|
||||
'/api/v1/chats/' + chat['id'] + '/attachments?filename=' + quote('failover.png'),
|
||||
201,
|
||||
actor=alice,
|
||||
raw=content,
|
||||
headers={'Content-Type': 'image/png'},
|
||||
schema='Attachment',
|
||||
)
|
||||
attachment = response['json']
|
||||
instance = response['headers'].get('X-Instance-Id')
|
||||
check(bool(instance), 'upload response has no X-Instance-Id')
|
||||
check(attachment['sha256'] == hashlib.sha256(content).hexdigest(), 'upload checksum mismatch')
|
||||
|
||||
stop = subprocess.run(
|
||||
[str(ROOT / 'scripts/stop-one.sh')],
|
||||
cwd=ROOT,
|
||||
env={**os.environ, 'TARGET_INSTANCE_ID': instance},
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
check(stop.returncode == 0, 'stop-one.sh failed: ' + stop.stderr.strip())
|
||||
|
||||
deadline = time.monotonic() + 30
|
||||
last_error = None
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
download = client.call(
|
||||
'GET', '/api/v1/attachments/' + attachment['id'] + '/content', actor=bob,
|
||||
)
|
||||
if download['bytes'] == content:
|
||||
metadata = client.call(
|
||||
'GET', '/api/v1/attachments/' + attachment['id'], actor=bob, schema='Attachment',
|
||||
)['json']
|
||||
check(metadata['sha256'] == attachment['sha256'], 'metadata changed after failover')
|
||||
print('PASS: lab4 attachment failover; served by', instance)
|
||||
return
|
||||
last_error = 'downloaded bytes differ from the original'
|
||||
except Failure as error:
|
||||
last_error = str(error)
|
||||
|
||||
time.sleep(1)
|
||||
|
||||
raise Failure('download did not recover within 30s: ' + str(last_error))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
run(main)
|
||||
finally:
|
||||
compose('up', '-d', '--no-deps', 'api', check=False)
|
||||
Executable
+119
@@ -0,0 +1,119 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Negative attachment scenarios required by lab4 level 4.
|
||||
|
||||
Run against a live stand:
|
||||
python3 student-tests/attachments_negative.py --base-url http://localhost:8080
|
||||
"""
|
||||
import hashlib
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
|
||||
from client import Client, Failure, arguments, check, run # noqa: E402
|
||||
|
||||
FIXTURE = Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png'
|
||||
|
||||
|
||||
def upload(client, actor, chat, content, filename='sample.png', content_type='image/png', expected=201):
|
||||
path = '/api/v1/chats/' + chat['id'] + '/attachments?filename=' + quote(filename, safe='')
|
||||
return client.call('POST', path, expected, actor=actor, raw=content, headers={'Content-Type': content_type})
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Attachment negative scenarios (lab4)')
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
fixture = FIXTURE.read_bytes()
|
||||
|
||||
# Oversized body: rejected before any image parsing.
|
||||
upload(client, alice, chat, b'\x00' * (10 * 1024 * 1024 + 1), expected=413)
|
||||
print('10 MiB + 1 body: 413')
|
||||
|
||||
# Empty body is not a valid image.
|
||||
upload(client, alice, chat, b'', expected=415)
|
||||
print('empty body: 415')
|
||||
|
||||
# Corrupt PNG: flip one IDAT payload byte, CRC no longer matches.
|
||||
corrupt = bytearray(fixture)
|
||||
index = corrupt.index(b'IDAT') + 8
|
||||
corrupt[index] ^= 0xFF
|
||||
upload(client, alice, chat, bytes(corrupt), expected=415)
|
||||
print('corrupt PNG (IDAT CRC): 415')
|
||||
|
||||
# Declared JPEG but the bytes are PNG.
|
||||
upload(client, alice, chat, fixture, filename='photo.jpg', content_type='image/jpeg', expected=415)
|
||||
print('MIME spoof (PNG declared as JPEG): 415')
|
||||
|
||||
# Dangerous display names.
|
||||
for name in ('../x.png', 'a/b.png', 'a\\b.png', 'a\x00.png', 'a\n.png'):
|
||||
upload(client, alice, chat, fixture, filename=name, expected=400)
|
||||
print('dangerous filenames: 400')
|
||||
|
||||
# A member of one chat cannot read an attachment of another chat.
|
||||
other = client.call(
|
||||
'POST', '/api/v1/chats', 201, actor=alice,
|
||||
body={'title': 'Другой чат', 'member_ids': [alice['id'], eve['id']]}, schema='Chat',
|
||||
)['json']
|
||||
foreign, foreign_content = client.attachment(eve, other)
|
||||
client.call('GET', '/api/v1/attachments/' + foreign['id'], 404, actor=bob)
|
||||
client.call('GET', '/api/v1/attachments/' + foreign['id'] + '/content', 404, actor=bob)
|
||||
print('foreign attachment metadata/content: 404')
|
||||
|
||||
# Message rules: empty text without attachments, attachment from another chat.
|
||||
client.call(
|
||||
'POST', '/api/v1/chats/' + chat['id'] + '/messages', 400, actor=alice,
|
||||
body={'text': ''}, headers={'Idempotency-Key': uuid.uuid4().hex},
|
||||
)
|
||||
print('empty text without attachments: 400')
|
||||
client.call(
|
||||
'POST', '/api/v1/chats/' + chat['id'] + '/messages', 404, actor=alice,
|
||||
body={'text': 'чужое', 'attachment_ids': [foreign['id']]},
|
||||
headers={'Idempotency-Key': uuid.uuid4().hex},
|
||||
)
|
||||
print('attachment from another chat: 404')
|
||||
|
||||
# Contract limits: 11 unique IDs and duplicate IDs are rejected by the schema.
|
||||
client.call(
|
||||
'POST', '/api/v1/chats/' + chat['id'] + '/messages', 400, actor=alice,
|
||||
body={'text': 'много', 'attachment_ids': [str(uuid.uuid4()) for _ in range(11)]},
|
||||
headers={'Idempotency-Key': uuid.uuid4().hex},
|
||||
)
|
||||
print('11 attachment ids: 400')
|
||||
duplicate = str(uuid.uuid4())
|
||||
client.call(
|
||||
'POST', '/api/v1/chats/' + chat['id'] + '/messages', 400, actor=alice,
|
||||
body={'text': 'дубликат', 'attachment_ids': [duplicate, duplicate]},
|
||||
headers={'Idempotency-Key': uuid.uuid4().hex},
|
||||
)
|
||||
print('duplicate attachment ids: 400')
|
||||
|
||||
# The only variant in the lab4 contract is original; other values are 400.
|
||||
own, content = client.attachment(alice, chat)
|
||||
client.call('GET', '/api/v1/attachments/' + own['id'] + '/content?variant=thumbnail', 400, actor=alice)
|
||||
|
||||
# Attachment-only message is valid.
|
||||
client.message(alice, chat, '', attachments=[own['id']])
|
||||
print('attachment-only message: 201')
|
||||
|
||||
# Object keys are server-generated; anonymous direct access must be denied.
|
||||
key = 'attachments/' + chat['id'] + '/' + own['id']
|
||||
request = urllib.request.Request('http://127.0.0.1:8333/messenger-attachments/' + key, method='GET')
|
||||
try:
|
||||
urllib.request.urlopen(request, timeout=5)
|
||||
except urllib.error.HTTPError as error:
|
||||
check(error.code == 403, 'anonymous S3 GET must be 403, got ' + str(error.code))
|
||||
else:
|
||||
raise Failure('anonymous S3 GET unexpectedly succeeded')
|
||||
|
||||
print('anonymous direct S3 GET: 403')
|
||||
check(hashlib.sha256(content).hexdigest() == own['sha256'], 'fixture checksum mismatch')
|
||||
print('PASS: lab4 attachment negative scenarios')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,156 @@
|
||||
#!/usr/bin/env python3
|
||||
import os
|
||||
import json
|
||||
import sys
|
||||
import urllib.request
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from statistics import median
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
# Собственный тест живёт в student-tests/ (CONTRIBUTING), публичный клиент — в tests/.
|
||||
sys.path.insert(0, os.path.join(ROOT, 'tests'))
|
||||
|
||||
from client import Client, check # noqa: E402
|
||||
COMPOSE = os.environ.get('COMPOSE_BIN', 'docker-compose')
|
||||
BASE_URL = os.environ.get('BASE_URL', 'http://localhost:8080')
|
||||
USERS = 4
|
||||
CHATS_PER_USER = 15
|
||||
REQUESTS_PER_USER = 250
|
||||
WORKERS = 8
|
||||
|
||||
for proxy_name in ('HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'http_proxy', 'https_proxy', 'all_proxy'):
|
||||
os.environ.pop(proxy_name, None)
|
||||
os.environ['NO_PROXY'] = 'localhost,127.0.0.1,::1'
|
||||
os.environ['no_proxy'] = os.environ['NO_PROXY']
|
||||
|
||||
|
||||
def restart_api(cache_enabled):
|
||||
env = dict(os.environ)
|
||||
env['REDIS_ENABLED'] = 'true'
|
||||
env['CACHE_ENABLED'] = 'true' if cache_enabled else 'false'
|
||||
subprocess.run(
|
||||
[COMPOSE, '-f', 'docker-compose.local.yaml', 'up', '-d', '--force-recreate', 'api'],
|
||||
cwd=ROOT,
|
||||
env=env,
|
||||
check=True,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
)
|
||||
|
||||
deadline = time.monotonic() + 90
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
Client(BASE_URL, timeout=2).call('GET', '/health/ready', schema='Health')
|
||||
return
|
||||
except Exception:
|
||||
time.sleep(0.5)
|
||||
raise RuntimeError('API did not become ready after restart')
|
||||
|
||||
|
||||
def percentile(values, percent):
|
||||
values = sorted(values)
|
||||
index = max(0, (len(values) * percent + 99) // 100 - 1)
|
||||
return values[index]
|
||||
|
||||
|
||||
def benchmark(actors):
|
||||
requests = [(actor, i) for i in range(REQUESTS_PER_USER) for actor in actors]
|
||||
latencies = []
|
||||
failures = []
|
||||
started = time.monotonic()
|
||||
|
||||
def request(item):
|
||||
actor, _ = item
|
||||
request_started = time.monotonic()
|
||||
request = urllib.request.Request(
|
||||
BASE_URL + '/api/v1/chats?limit=50',
|
||||
headers={
|
||||
'Accept': 'application/json',
|
||||
'Authorization': 'Bearer ' + actor['token'],
|
||||
},
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=10) as response:
|
||||
data = response.read()
|
||||
status = response.status
|
||||
check(status == 200,
|
||||
'unexpected HTTP status: ' + str(status) + ' body=' + data.decode())
|
||||
result = json.loads(data)
|
||||
check(len(result['items']) == 30, 'unexpected chat count')
|
||||
check(all(actor['id'] in chat['member_ids'] for chat in result['items']),
|
||||
'response contains another user chat')
|
||||
return time.monotonic() - request_started, None
|
||||
except Exception as exc:
|
||||
return 0, type(exc).__name__ + ': ' + str(exc)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=WORKERS) as pool:
|
||||
for latency, error in pool.map(request, requests):
|
||||
if error is None:
|
||||
latencies.append(latency)
|
||||
else:
|
||||
failures.append(error)
|
||||
|
||||
duration = time.monotonic() - started
|
||||
if failures:
|
||||
raise RuntimeError(
|
||||
'API benchmark failed: %d/%d requests; first error: %s'
|
||||
% (len(failures), len(requests), failures[0])
|
||||
)
|
||||
return {
|
||||
'requests': len(latencies),
|
||||
'workers': WORKERS,
|
||||
'duration_seconds': duration,
|
||||
'rps': len(latencies) / duration,
|
||||
'p50_ms': median(latencies) * 1000,
|
||||
'p95_ms': percentile(latencies, 95) * 1000,
|
||||
'p99_ms': percentile(latencies, 99) * 1000,
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
client = Client(BASE_URL, timeout=10)
|
||||
actors = [client.user('perf_api_' + str(i)) for i in range(USERS)]
|
||||
|
||||
for index, owner in enumerate(actors):
|
||||
member = actors[(index + 1) % len(actors)]
|
||||
for chat_index in range(CHATS_PER_USER):
|
||||
client.call(
|
||||
'POST',
|
||||
'/api/v1/chats',
|
||||
expected=201,
|
||||
actor=owner,
|
||||
body={
|
||||
'title': 'API performance chat ' + str(index) + '-' + str(chat_index),
|
||||
'member_ids': [owner['id'], member['id']],
|
||||
},
|
||||
schema='Chat',
|
||||
)
|
||||
|
||||
results = []
|
||||
try:
|
||||
for trial in range(2):
|
||||
for enabled in (False, True):
|
||||
restart_api(enabled)
|
||||
for actor in actors:
|
||||
for _ in range(5):
|
||||
client.call('GET', '/api/v1/chats?limit=50', actor=actor, schema='ChatPage')
|
||||
print(
|
||||
'running trial %d, cache=%s, requests=%d' %
|
||||
(trial + 1, enabled, len(actors) * REQUESTS_PER_USER),
|
||||
flush=True,
|
||||
)
|
||||
result = benchmark(actors)
|
||||
result.update(trial=trial + 1, cache_enabled=enabled)
|
||||
results.append(result)
|
||||
print(json.dumps(result), flush=True)
|
||||
finally:
|
||||
restart_api(True)
|
||||
print(json.dumps({'results': results, 'users': USERS, 'chats': USERS * CHATS_PER_USER,
|
||||
'sessions_cached_in_both_modes': True}), flush=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Executable
+144
@@ -0,0 +1,144 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Параллельная проверка общей идемпотентности отправки сообщения (lab3+).
|
||||
|
||||
Публичный smoke проверяет только последовательный повтор. Здесь один и тот же
|
||||
Idempotency-Key отправляется одновременно несколькими потоками через LB, то есть
|
||||
запросы попадают на разные API-реплики: ровно одно сообщение должно быть создано,
|
||||
а повтор с другим payload обязан получить 409.
|
||||
|
||||
Запуск (стенд уже поднят, LB на 8080):
|
||||
python3 student-tests/idempotency_parallel.py --base-url http://localhost:8080
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
import uuid
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
|
||||
from client import Client, LAB, Failure, arguments, check, run # noqa: E402
|
||||
|
||||
WORKERS = 12
|
||||
|
||||
|
||||
def messages_path(chat):
|
||||
return '/api/v1/chats/' + chat['id'] + '/messages'
|
||||
|
||||
|
||||
def history(client, actor, chat):
|
||||
page = client.call('GET', messages_path(chat) + '?limit=100', actor=actor, schema='MessagePage')['json']
|
||||
return page['items']
|
||||
|
||||
|
||||
def replay_confirmed(client, actor, chat, workers=WORKERS):
|
||||
"""Один payload, один ключ, одновременные запросы через LB."""
|
||||
key = uuid.uuid4().hex
|
||||
text = 'Параллельный повтор ' + key
|
||||
|
||||
with ThreadPoolExecutor(max_workers=workers) as pool:
|
||||
responses = list(pool.map(lambda _: client.message(actor, chat, text, key=key), range(workers)))
|
||||
|
||||
ids = {response['json']['id'] for response in responses}
|
||||
check(len(ids) == 1, 'параллельные повторы вернули разные сообщения: ' + str(len(ids)))
|
||||
instances = {response['headers']['X-Instance-Id'] for response in responses}
|
||||
check(len(instances) >= 2, 'запросы не разошлись по репликам: ' + str(sorted(instances)))
|
||||
|
||||
stored = [message for message in history(client, actor, chat) if message['text'] == text]
|
||||
check(len(stored) == 1, 'параллельный повтор создал ' + str(len(stored)) + ' сообщений')
|
||||
check(stored[0]['id'] == next(iter(ids)), 'в истории не то сообщение, что вернул POST')
|
||||
|
||||
return {'workers': workers, 'instances': sorted(instances), 'message_id': stored[0]['id']}
|
||||
|
||||
|
||||
def conflicting_payloads(client, actor, chat, workers=WORKERS):
|
||||
"""Один ключ, разные payload одновременно: один 201, остальные 409."""
|
||||
key = uuid.uuid4().hex
|
||||
texts = ['Конфликт ' + key + ' #' + str(index) for index in range(workers)]
|
||||
|
||||
def post(text):
|
||||
return client.call(
|
||||
'POST',
|
||||
messages_path(chat),
|
||||
(201, 409),
|
||||
actor=actor,
|
||||
body={'text': text},
|
||||
headers={'Idempotency-Key': key},
|
||||
schema='Message',
|
||||
)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=workers) as pool:
|
||||
responses = list(pool.map(post, texts))
|
||||
|
||||
accepted = [response for response in responses if response['status'] == 201]
|
||||
conflicts = [response for response in responses if response['status'] == 409]
|
||||
check(len(accepted) == 1, 'принято запросов с одним ключом: ' + str(len(accepted)))
|
||||
check(len(conflicts) == workers - 1, 'конфликтов: ' + str(len(conflicts)))
|
||||
|
||||
stored = [message for message in history(client, actor, chat) if message['id'] == accepted[0]['json']['id']]
|
||||
check(len(stored) == 1, 'конфликтующий ключ создал не одно сообщение')
|
||||
|
||||
return {'workers': workers, 'accepted': len(accepted), 'conflicts': len(conflicts)}
|
||||
|
||||
|
||||
def replayed_body_is_stable(client, actor, chat):
|
||||
"""Повтор того же смысла, но другого JSON, возвращает исходное сообщение."""
|
||||
key = uuid.uuid4().hex
|
||||
text = 'Форматирование ' + key
|
||||
first = client.message(actor, chat, text, key=key)
|
||||
|
||||
# Тот же payload, другой порядок пробелов в JSON: контракт требует тот же 201
|
||||
# и то же сообщение.
|
||||
spaced = json.dumps({'text': text}, ensure_ascii=False).replace('":', '" :')
|
||||
replay = client.call(
|
||||
'POST',
|
||||
messages_path(chat),
|
||||
201,
|
||||
actor=actor,
|
||||
raw=spaced.encode('utf-8'),
|
||||
headers={'Idempotency-Key': key, 'Content-Type': 'application/json'},
|
||||
schema='Message',
|
||||
)
|
||||
check(replay['json'] == first['json'], 'повтор вернул другое сообщение')
|
||||
|
||||
return {'message_id': first['json']['id']}
|
||||
|
||||
|
||||
def key_is_required(client, actor, chat):
|
||||
client.call('POST', messages_path(chat), 400, actor=actor, body={'text': 'без ключа'}, schema='Error')
|
||||
|
||||
result = client.call(
|
||||
'POST',
|
||||
messages_path(chat),
|
||||
400,
|
||||
actor=actor,
|
||||
body={'text': 'кривой ключ'},
|
||||
headers={'Idempotency-Key': 'bad key!'},
|
||||
schema='Error',
|
||||
)
|
||||
check(result['status'] == 400, 'некорректный ключ обязан быть 400')
|
||||
|
||||
return {'status': result['status']}
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Параллельная идемпотентность сообщений (lab3+); создаёт синтетические данные')
|
||||
check(LAB >= 3, 'параллельная идемпотентность требует lab3+')
|
||||
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
|
||||
summary = {
|
||||
'replay': replay_confirmed(client, alice, chat),
|
||||
'conflict': conflicting_payloads(client, alice, chat),
|
||||
'stable_body': replayed_body_is_stable(client, alice, chat),
|
||||
'key_required': key_is_required(client, alice, chat),
|
||||
}
|
||||
|
||||
print(json.dumps(summary, ensure_ascii=False))
|
||||
print('PASS: параллельный повтор с одним Idempotency-Key создаёт ровно одно сообщение')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Executable
+148
@@ -0,0 +1,148 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Presigned direct-upload track (lab4 level 5).
|
||||
|
||||
The mandatory proxy endpoint stays available; this script exercises the
|
||||
optional extension: presign -> direct PUT to S3 -> complete -> message.
|
||||
|
||||
Run against a live stand:
|
||||
python3 student-tests/presign_flow.py --base-url http://localhost:8080
|
||||
|
||||
Set PRESIGN_EXPIRY_WAIT=seconds to also verify that an expired URL is rejected
|
||||
(the stand must run with a matching S3_PRESIGN_TTL).
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
|
||||
from client import Client, Failure, arguments, check, run # noqa: E402
|
||||
|
||||
FIXTURE = Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png'
|
||||
|
||||
|
||||
def presign(client, actor, chat, content, filename='presigned.png', content_type='image/png'):
|
||||
body = {
|
||||
'filename': filename,
|
||||
'content_type': content_type,
|
||||
'size_bytes': len(content),
|
||||
'sha256': hashlib.sha256(content).hexdigest(),
|
||||
}
|
||||
response = client.call(
|
||||
'POST', '/api/v1/chats/' + chat['id'] + '/attachments/presign', 201,
|
||||
actor=actor, body=body,
|
||||
)
|
||||
return json.loads(response['bytes'])
|
||||
|
||||
|
||||
def put(url, content, content_type='image/png'):
|
||||
request = urllib.request.Request(
|
||||
url, data=content, method='PUT', headers={'Content-Type': content_type},
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=15) as response:
|
||||
return response.status
|
||||
except urllib.error.HTTPError as error:
|
||||
return error.code
|
||||
|
||||
|
||||
def complete(client, actor, attachment_id, digest, expected=200):
|
||||
return client.call(
|
||||
'POST', '/api/v1/attachments/' + attachment_id + '/complete', expected,
|
||||
actor=actor, body={'sha256': digest}, schema='Attachment' if expected == 200 else None,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Presigned upload flow (lab4 track 1)')
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
content = FIXTURE.read_bytes()
|
||||
digest = hashlib.sha256(content).hexdigest()
|
||||
|
||||
# Happy path: direct PUT, completion, message, download.
|
||||
presigned = presign(client, alice, chat, content)
|
||||
check(presigned['method'] == 'PUT', 'presign method must be PUT')
|
||||
check('content-length' in presigned['upload_url'], 'content-length must be signed into the URL')
|
||||
check(put(presigned['upload_url'], content) == 200, 'direct PUT failed')
|
||||
attachment = complete(client, alice, presigned['attachment_id'], digest)['json']
|
||||
check(attachment['sha256'] == digest and attachment['size_bytes'] == len(content), 'completed metadata mismatch')
|
||||
print('happy path: direct PUT 200, complete ready, checksum/size match')
|
||||
|
||||
client.message(alice, chat, '', attachments=[attachment['id']])
|
||||
download = client.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content', actor=bob)
|
||||
check(download['bytes'] == content, 'download differs from the presigned original')
|
||||
print('message with attachment downloaded as the second chat member')
|
||||
|
||||
# Completion is idempotent.
|
||||
again = complete(client, alice, presigned['attachment_id'], digest)['json']
|
||||
check(again['id'] == attachment['id'], 'repeated complete returned another attachment')
|
||||
print('repeated complete is idempotent')
|
||||
|
||||
# A foreign user cannot complete someone else's pending upload.
|
||||
pending = presign(client, alice, chat, content)
|
||||
complete(client, bob, pending['attachment_id'], digest, expected=404)
|
||||
print('foreign complete: 404')
|
||||
|
||||
# Incomplete upload: complete before PUT.
|
||||
incomplete = presign(client, alice, chat, content)
|
||||
complete(client, alice, incomplete['attachment_id'], digest, expected=409)
|
||||
print('complete before PUT: 409')
|
||||
|
||||
# Wrong checksum: the object is rejected and removed.
|
||||
mismatch = presign(client, alice, chat, content)
|
||||
check(put(mismatch['upload_url'], content) == 200, 'direct PUT failed')
|
||||
complete(client, alice, mismatch['attachment_id'], '0' * 64, expected=409)
|
||||
print('wrong completion checksum: 409')
|
||||
|
||||
# Content-Length is signed, so S3 rejects a different number of bytes at
|
||||
# write time instead of storing an oversized staging object.
|
||||
oversized = presign(client, alice, chat, content)
|
||||
check(put(oversized['upload_url'], content + b'x') == 403, 'oversized PUT must be rejected by S3')
|
||||
complete(client, alice, oversized['attachment_id'], digest, expected=409)
|
||||
print('oversized direct PUT: 403 from S3; complete: 409 (nothing stored)')
|
||||
|
||||
# Last PUT wins before completion; the declared checksum must describe it.
|
||||
# The replacement is the same length because Content-Length is signed.
|
||||
overwrite = presign(client, alice, chat, content)
|
||||
corrupt = bytearray(content)
|
||||
corrupt[0] ^= 0xFF
|
||||
check(put(overwrite['upload_url'], bytes(corrupt)) == 200, 'first PUT failed')
|
||||
check(put(overwrite['upload_url'], content) == 200, 'second PUT failed')
|
||||
overwritten = complete(client, alice, overwrite['attachment_id'], digest)['json']
|
||||
check(overwritten['sha256'] == digest, 'last PUT was not the completed object')
|
||||
print('same-size overwrite: last PUT wins, checksum verified')
|
||||
|
||||
# A user outside the chat cannot obtain a presigned URL.
|
||||
other = client.call(
|
||||
'POST', '/api/v1/chats', 201, actor=alice,
|
||||
body={'title': 'Приватный чат', 'member_ids': [alice['id'], eve['id']]}, schema='Chat',
|
||||
)['json']
|
||||
client.call(
|
||||
'POST', '/api/v1/chats/' + other['id'] + '/attachments/presign', 404,
|
||||
actor=bob,
|
||||
body={
|
||||
'filename': 'x.png', 'content_type': 'image/png',
|
||||
'size_bytes': len(content), 'sha256': digest,
|
||||
},
|
||||
)
|
||||
|
||||
wait = float(os.environ.get('PRESIGN_EXPIRY_WAIT', '0'))
|
||||
if wait > 0:
|
||||
expired = presign(client, alice, chat, content)
|
||||
time.sleep(wait)
|
||||
status = put(expired['upload_url'], content)
|
||||
check(status == 403, 'expired presigned URL must be 403, got ' + str(status))
|
||||
print('EXPIRED: presigned URL rejected after', wait, 'seconds')
|
||||
|
||||
print('PASS: lab4 presigned upload flow')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Executable
+197
@@ -0,0 +1,197 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Последовательная остановка каждой API-реплики с измерениями (lab3).
|
||||
|
||||
Отличие от публичного `make test-failover`: здесь реплика выбирается явно
|
||||
(сначала первая, затем вторая), печатается реально остановленный контейнер и
|
||||
собираются метрики: успешные записи, ошибки, время восстановления записи через
|
||||
LB, набор реплик после отказа и отсутствие дублей при повторе одного ключа.
|
||||
|
||||
Запуск (стенд поднят, LB на 8080, hooks в scripts/):
|
||||
python3 student-tests/replica_failover.py --action-script scripts/stop-one.sh
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
|
||||
from client import Client, LAB, Failure, arguments, check, run # noqa: E402
|
||||
from tests_helpers import compose, containers_by_hostname, messages_path # noqa: E402
|
||||
|
||||
WINDOW_SECONDS = 15.0
|
||||
RECOVERY_DEADLINE_SECONDS = 10.0
|
||||
STOP_DELAY_SECONDS = 0.5
|
||||
|
||||
|
||||
def observed_instances(client, actor, tries=40):
|
||||
seen = {}
|
||||
|
||||
for _ in range(tries):
|
||||
response = client.call('GET', '/api/v1/users/me', actor=actor, schema='User')
|
||||
instance = response['headers']['X-Instance-Id']
|
||||
seen[instance] = seen.get(instance, 0) + 1
|
||||
|
||||
return seen
|
||||
|
||||
|
||||
def stop_replica(script, instance):
|
||||
started = time.monotonic()
|
||||
env = dict(os.environ, TARGET_INSTANCE_ID=instance)
|
||||
proc = subprocess.run([str(script)], env=env, capture_output=True, text=True)
|
||||
|
||||
return {
|
||||
'returncode': proc.returncode,
|
||||
'seconds': round(time.monotonic() - started, 3),
|
||||
'stdout': proc.stdout.strip(),
|
||||
'stderr': proc.stderr.strip(),
|
||||
}
|
||||
|
||||
|
||||
def measure_outage(client, actor, chat, target, script):
|
||||
"""Пишет сообщения сквозь LB, пока hook останавливает выбранную реплику."""
|
||||
hook = ThreadPoolExecutor(max_workers=1)
|
||||
stop_started = time.monotonic()
|
||||
hook_future = hook.submit(lambda: (time.sleep(STOP_DELAY_SECONDS), stop_replica(script, target))[1])
|
||||
|
||||
successes, failures, uncertain = 0, 0, 0
|
||||
instances_after = []
|
||||
first_recovery = None
|
||||
key, text = None, None
|
||||
stop_finished = None
|
||||
|
||||
try:
|
||||
while time.monotonic() - stop_started < WINDOW_SECONDS:
|
||||
if key is None:
|
||||
key = uuid.uuid4().hex
|
||||
text = 'Отказ ' + target + ' ' + key
|
||||
|
||||
try:
|
||||
response = client.message(actor, chat, text, key=key)
|
||||
except Failure:
|
||||
failures += 1
|
||||
uncertain += 1
|
||||
continue
|
||||
|
||||
successes += 1
|
||||
instances_after.append(response['headers']['X-Instance-Id'])
|
||||
key, text = None, None
|
||||
|
||||
if hook_future.done() and stop_finished is None:
|
||||
stop_finished = time.monotonic() - stop_started
|
||||
first_recovery = first_recovery or round(stop_finished, 3)
|
||||
|
||||
time.sleep(0.1)
|
||||
finally:
|
||||
stopped = hook_future.result()
|
||||
|
||||
if first_recovery is None:
|
||||
first_recovery = round(time.monotonic() - stop_started, 3)
|
||||
|
||||
elapsed = time.monotonic() - stop_started
|
||||
|
||||
return {
|
||||
'stopped_container': stopped['stdout'],
|
||||
'hook_returncode': stopped['returncode'],
|
||||
'hook_seconds': stopped['seconds'],
|
||||
'hook_error': stopped['stderr'],
|
||||
'successful_writes': successes,
|
||||
'successful_rps': round(successes / elapsed, 2) if elapsed else None,
|
||||
'failed_attempts': failures,
|
||||
'uncertain_retries': uncertain,
|
||||
'first_recovery_seconds': first_recovery,
|
||||
'instances_after_recovery': sorted(set(instances_after[-5:])),
|
||||
}
|
||||
|
||||
|
||||
def all_messages(client, actor, chat, limit=2000):
|
||||
"""Вся история чата с keyset-пагинацией (проверка дублей не должна зависеть от одной страницы)."""
|
||||
items = []
|
||||
cursor = None
|
||||
|
||||
while True:
|
||||
query = messages_path(chat) + '?limit=100'
|
||||
if cursor:
|
||||
query += '&cursor=' + quote(cursor, safe='')
|
||||
|
||||
page = client.call('GET', query, actor=actor, schema='MessagePage')['json']
|
||||
items.extend(page['items'])
|
||||
cursor = page['next_cursor']
|
||||
|
||||
if not cursor:
|
||||
return items
|
||||
|
||||
check(len(items) <= limit, 'история больше защитного предела проверки')
|
||||
|
||||
|
||||
def ensure_no_duplicates(client, actor, chat):
|
||||
items = all_messages(client, actor, chat)
|
||||
texts = [message['text'] for message in items]
|
||||
ids = [message['id'] for message in items]
|
||||
check(len(texts) == len(set(texts)), 'повтор с тем же ключом создал дубль')
|
||||
check(len(ids) == len(set(ids)), 'дубли ID в истории')
|
||||
|
||||
return len(items)
|
||||
|
||||
|
||||
def restore(instance, timeout=90):
|
||||
started = time.monotonic()
|
||||
compose('up', '-d', '--no-deps', 'api')
|
||||
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
hosts = containers_by_hostname()
|
||||
if instance in hosts:
|
||||
return {'seconds': round(time.monotonic() - started, 3), 'instances': sorted(hosts)}
|
||||
|
||||
time.sleep(1)
|
||||
|
||||
raise Failure('реплика ' + instance + ' не вернулась в строй')
|
||||
|
||||
|
||||
def main():
|
||||
def configure(parser):
|
||||
parser.add_argument('--action-script', required=True, help='stop-one hook, executable, authored by student')
|
||||
|
||||
args = arguments('Последовательная остановка реплик с метриками (lab3)', configure)
|
||||
check(LAB >= 3, 'отказ API-реплики требует lab3+')
|
||||
|
||||
script = Path(args.action_script).expanduser().resolve()
|
||||
check(script.is_file() and os.access(script, os.X_OK), 'hook должен существовать и быть исполняемым')
|
||||
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
|
||||
observed = observed_instances(client, alice)
|
||||
check(len(observed) >= 2, 'через LB видно меньше двух реплик: ' + str(sorted(observed)))
|
||||
|
||||
report = {'before': {'instances': sorted(observed)}, 'replicas': []}
|
||||
|
||||
for instance in sorted(observed):
|
||||
result = measure_outage(client, alice, chat, instance, script)
|
||||
check(result['hook_returncode'] == 0, 'hook завершился неуспешно: ' + result['hook_error'])
|
||||
check(
|
||||
result['first_recovery_seconds'] <= RECOVERY_DEADLINE_SECONDS,
|
||||
'запись не восстановилась за ' + str(RECOVERY_DEADLINE_SECONDS) + ' c',
|
||||
)
|
||||
check(result['successful_writes'] >= 5, 'слишком мало подтверждённых записей после отказа')
|
||||
check(instance not in result['instances_after_recovery'], 'остановленная реплика продолжает обслуживать')
|
||||
result['messages_in_history'] = ensure_no_duplicates(client, alice, chat)
|
||||
|
||||
restored = restore(instance)
|
||||
result['restored_seconds'] = restored['seconds']
|
||||
result['instances_restored'] = restored['instances']
|
||||
|
||||
report['replicas'].append({'stopped': instance, **result})
|
||||
|
||||
print(json.dumps(report, ensure_ascii=False, indent=2))
|
||||
print('PASS: каждая реплика остановлена по очереди; записи продолжились, дублей и потерь нет')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Executable
+157
@@ -0,0 +1,157 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Толерантный генератор записи для сценариев отказа (lab3).
|
||||
|
||||
Публичный `tests/load.py` не переживает разрыв соединения во время удаления
|
||||
реплики: он падает на уровне http.client. Этот генератор создан для измерений
|
||||
во время rolling update и отказов: он считает успешные запросы, ошибки по видам
|
||||
и увиденные реплики, а не падает на обрыве.
|
||||
|
||||
python3 student-tests/rolling_update_load.py --duration 60 --concurrency 16 --output evidence/rolling-update/load.json
|
||||
"""
|
||||
import json
|
||||
import math
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
|
||||
from client import Client, LAB, Failure, arguments, check, run # noqa: E402
|
||||
|
||||
|
||||
def classify(error):
|
||||
name = type(error).__name__
|
||||
message = str(error)
|
||||
|
||||
if name == 'Failure':
|
||||
# client.call сообщает о проблемах соединения как Failure с этим текстом,
|
||||
# отделяя их от HTTP-статусов, которые тоже приходят как Failure.
|
||||
if 'connection/TLS failure' in message:
|
||||
return 'connection_broken'
|
||||
|
||||
return 'http_error'
|
||||
if name in ('RemoteDisconnected', 'BadStatusLine', 'IncompleteRead', 'ConnectionResetError'):
|
||||
return 'connection_broken'
|
||||
if name in ('TimeoutError', 'socket.timeout'):
|
||||
return 'timeout'
|
||||
|
||||
return name
|
||||
|
||||
|
||||
def main():
|
||||
def configure(parser):
|
||||
parser.add_argument('--duration', type=float, default=30)
|
||||
parser.add_argument('--concurrency', type=int, default=8)
|
||||
parser.add_argument('--output', default=None)
|
||||
|
||||
args = arguments('Запись сообщений сквозь LB с учётом ошибок (lab3)', configure)
|
||||
check(LAB >= 3, 'сценарий требует lab3+')
|
||||
check(1 <= args.duration <= 3600, 'duration должен быть 1..3600')
|
||||
check(1 <= args.concurrency <= 128, 'concurrency должен быть 1..128')
|
||||
|
||||
bootstrap = Client(args.base_url, args.ca_file)
|
||||
|
||||
# Стенд в момент старта может быть в переходном состоянии (например, сразу
|
||||
# после возврата БД), поэтому однократный 502 на bootstrap не должен ломать
|
||||
# измерение: пробуем несколько раз и сообщаем, сколько попыток понадобилось.
|
||||
attempts = 0
|
||||
while True:
|
||||
attempts += 1
|
||||
try:
|
||||
alice, _, _, chat = bootstrap.bootstrap()
|
||||
break
|
||||
except Failure as error:
|
||||
if attempts >= 10:
|
||||
raise
|
||||
print('bootstrap attempt %d failed: %s' % (attempts, error), file=sys.stderr)
|
||||
time.sleep(2)
|
||||
|
||||
if attempts > 1:
|
||||
print('bootstrap attempts: %d' % attempts, file=sys.stderr)
|
||||
|
||||
barrier = threading.Barrier(args.concurrency)
|
||||
lock = threading.Lock()
|
||||
latencies = []
|
||||
errors = {}
|
||||
instances = {}
|
||||
|
||||
def worker(worker_id):
|
||||
client = Client(args.base_url, args.ca_file, timeout=5)
|
||||
local_latencies = []
|
||||
local_errors = {}
|
||||
local_instances = {}
|
||||
barrier.wait()
|
||||
|
||||
deadline = time.monotonic() + args.duration
|
||||
index = 0
|
||||
|
||||
while time.monotonic() < deadline:
|
||||
started = time.monotonic()
|
||||
|
||||
try:
|
||||
response = client.message(alice, chat, 'rolling-%s-%s' % (worker_id, index), key=uuid.uuid4().hex)
|
||||
except Exception as error: # noqa: BLE001 - протокол и сеть дают разные типы
|
||||
category = classify(error)
|
||||
local_errors[category] = local_errors.get(category, 0) + 1
|
||||
else:
|
||||
local_latencies.append(time.monotonic() - started)
|
||||
instance = response['headers']['X-Instance-Id']
|
||||
local_instances[instance] = local_instances.get(instance, 0) + 1
|
||||
|
||||
index += 1
|
||||
|
||||
with lock:
|
||||
latencies.extend(local_latencies)
|
||||
|
||||
for category, count in local_errors.items():
|
||||
errors[category] = errors.get(category, 0) + count
|
||||
|
||||
for instance, count in local_instances.items():
|
||||
instances[instance] = instances.get(instance, 0) + count
|
||||
|
||||
started = time.monotonic()
|
||||
|
||||
with ThreadPoolExecutor(max_workers=args.concurrency) as pool:
|
||||
list(pool.map(worker, range(args.concurrency)))
|
||||
|
||||
elapsed = time.monotonic() - started
|
||||
ordered = sorted(latencies)
|
||||
|
||||
def percentile(value):
|
||||
return round(1000 * ordered[max(0, math.ceil(value * len(ordered)) - 1)], 3) if ordered else None
|
||||
|
||||
failed = sum(errors.values())
|
||||
|
||||
report = {
|
||||
'lab': LAB,
|
||||
'workload': 'closed-loop POST messages; failures counted, not raised',
|
||||
'requested_duration_seconds': args.duration,
|
||||
'elapsed_seconds': round(elapsed, 3),
|
||||
'concurrency': args.concurrency,
|
||||
'successful_requests': len(ordered),
|
||||
'failed_requests': failed,
|
||||
'error_ratio': round(failed / (failed + len(ordered)), 6) if (failed + len(ordered)) else None,
|
||||
'errors_by_kind': errors,
|
||||
'successful_rps': round(len(ordered) / elapsed, 3),
|
||||
'successful_latency_ms': {'p50': percentile(.50), 'p95': percentile(.95), 'p99': percentile(.99)},
|
||||
'instances': instances,
|
||||
'bootstrap_attempts': attempts,
|
||||
'note': 'Percentiles cover successful writes only; transitional errors are expected during a rolling update.',
|
||||
}
|
||||
|
||||
text = json.dumps(report, ensure_ascii=False, indent=2)
|
||||
print(text)
|
||||
|
||||
if args.output:
|
||||
destination = Path(args.output)
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
destination.write_text(text + '\n')
|
||||
|
||||
check(bool(ordered), 'не было ни одной успешной записи')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Обвязки для собственных проверок ЛР3: docker compose и карта реплик.
|
||||
|
||||
Собственные тесты лежат в student-tests/ (CONTRIBUTING.md). X-Instance-Id равен
|
||||
hostname контейнера, поэтому по нему можно найти реально обслуживший контейнер.
|
||||
"""
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def compose(*args, check=True):
|
||||
command = [*os.environ.get('COMPOSE_BIN', 'docker compose').split(), '--env-file', '.env', '-f', 'compose.yaml', *args]
|
||||
|
||||
return subprocess.run(command, cwd=ROOT, capture_output=True, text=True, check=check)
|
||||
|
||||
|
||||
def containers_by_hostname(service='api'):
|
||||
"""{hostname: {id, name, status}} для контейнеров сервиса."""
|
||||
project = os.environ.get('COMPOSE_PROJECT_NAME', 'mtusi-messenger-lab4')
|
||||
listed = subprocess.run(
|
||||
[
|
||||
'docker', 'ps', '-q',
|
||||
'--filter', 'label=com.docker.compose.project=' + project,
|
||||
'--filter', 'label=com.docker.compose.service=' + service,
|
||||
],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True,
|
||||
).stdout.split()
|
||||
|
||||
result = {}
|
||||
for container in listed:
|
||||
info = subprocess.run(
|
||||
['docker', 'inspect', '--format', '{{.Config.Hostname}} {{.Name}} {{.State.Status}}', container],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True,
|
||||
).stdout.split()
|
||||
|
||||
result[info[0]] = {'id': container[:12], 'name': info[1].lstrip('/'), 'status': info[2]}
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def messages_path(chat):
|
||||
return '/api/v1/chats/' + chat['id'] + '/messages'
|
||||
Reference in New Issue
Block a user