Done Track 4
This commit is contained in:
@@ -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())
|
||||
Reference in New Issue
Block a user