Реализовать версии pipeline, fencing и автоматические сценарии отказов
This commit is contained in:
@@ -0,0 +1,94 @@
|
||||
"""Closed-loop: полный путь upload -> ready; ограничение генератора явно в отчёте."""
|
||||
import argparse
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import random
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import zlib
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, check
|
||||
|
||||
|
||||
def png(width, height):
|
||||
def chunk(name, data):
|
||||
return struct.pack('>I', len(data)) + name + data + struct.pack('>I', zlib.crc32(name + data))
|
||||
rng = random.Random(2301)
|
||||
data = b''.join(b'\0' + rng.randbytes(width * 3) for _ in range(height))
|
||||
return (b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', width, height, 8, 2, 0, 0, 0))
|
||||
+ chunk(b'IDAT', zlib.compress(data)) + chunk(b'IEND', b''))
|
||||
|
||||
|
||||
def percentile(values, q):
|
||||
return round(sorted(values)[min(len(values)-1, int((len(values)-1)*q))], 4) if values else None
|
||||
|
||||
|
||||
def main(args):
|
||||
client = Client(args.base_url)
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
profiles = [('320x200', (ROOT / 'tests/fixtures/sample.png').read_bytes()), ('1024x768', png(1024, 768))]
|
||||
rows = []
|
||||
for profile, raw in profiles:
|
||||
for repeat in range(args.repeats):
|
||||
samples = []
|
||||
failures = []
|
||||
stats = []
|
||||
stop = threading.Event()
|
||||
def sample():
|
||||
while not stop.is_set():
|
||||
ids = subprocess.check_output(['docker', 'compose', '-p', args.project, 'ps', '-q'], text=True).split()
|
||||
result = subprocess.check_output(['docker', 'stats', '--no-stream', '--format', '{{json .}}', *ids], text=True)
|
||||
stats.append(dict(at_seconds=round(time.monotonic()-start, 3), containers=[json.loads(line) for line in result.splitlines()]))
|
||||
stop.wait(2)
|
||||
def one():
|
||||
c = Client(args.base_url)
|
||||
begin = time.monotonic()
|
||||
att = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=load.png', 202,
|
||||
raw=raw, actor=alice, headers={'Content-Type': 'image/png'})['json']
|
||||
accepted = time.monotonic()
|
||||
ready = c.wait_ready(alice, att)
|
||||
check(len(ready['variants']) == 3 and ready['sha256'] == hashlib.sha256(raw).hexdigest(), 'bad load result')
|
||||
return dict(upload_seconds=accepted-begin, ready_seconds=time.monotonic()-begin)
|
||||
# Один завершённый прогрев на профиль/повтор, не входит в измерение.
|
||||
one()
|
||||
start = time.monotonic()
|
||||
sampler = threading.Thread(target=sample)
|
||||
sampler.start()
|
||||
def loop(_):
|
||||
while time.monotonic()-start < args.duration:
|
||||
try:
|
||||
samples.append(one())
|
||||
except Exception as exc:
|
||||
failures.append(type(exc).__name__ + ': ' + str(exc))
|
||||
with ThreadPoolExecutor(max_workers=args.concurrency) as pool:
|
||||
list(pool.map(loop, range(args.concurrency)))
|
||||
elapsed = time.monotonic()-start
|
||||
stop.set()
|
||||
sampler.join()
|
||||
times = [x['ready_seconds'] for x in samples]
|
||||
row = dict(profile=profile, bytes_per_image=len(raw), repeat=repeat+1, concurrency=args.concurrency,
|
||||
requested_duration=args.duration, elapsed_seconds=round(elapsed, 3), warmup_completed=1,
|
||||
completed=len(samples), successful_rps=round(len(samples)/elapsed, 3), failures=failures,
|
||||
error_fraction=len(failures)/max(1,len(samples)+len(failures)),
|
||||
p50=percentile(times,.5), p95=percentile(times,.95), p99=percentile(times,.99),
|
||||
upload_p95=percentile([x['upload_seconds'] for x in samples],.95), stats=stats)
|
||||
rows.append(row)
|
||||
(ROOT / 'evidence/load-pipeline.json').write_text(json.dumps(rows, indent=2), encoding='utf-8')
|
||||
print(json.dumps({k:v for k,v in row.items() if k != 'stats'}), flush=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument('--base-url', default='http://127.0.0.1:8085')
|
||||
p.add_argument('--project', default='lyakhonov-lab5')
|
||||
p.add_argument('--duration', type=int, default=20)
|
||||
p.add_argument('--concurrency', type=int, default=2)
|
||||
p.add_argument('--repeats', type=int, default=3)
|
||||
main(p.parse_args())
|
||||
@@ -0,0 +1,242 @@
|
||||
"""Реальные fault-injection и инварианты. Запускать только на своём lab5 стенде."""
|
||||
import argparse
|
||||
import base64
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import zlib
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, check
|
||||
|
||||
|
||||
class Experiment:
|
||||
def __init__(self, args):
|
||||
self.args = args
|
||||
self.compose = ['docker', 'compose', '-p', args.project]
|
||||
self.c = Client(args.base_url)
|
||||
self.alice, self.bob, self.eve, self.chat = self.c.bootstrap()
|
||||
path = ROOT / 'evidence/pipeline.json'
|
||||
self.rows = json.loads(path.read_text(encoding='utf-8')) if args.resume and path.exists() else []
|
||||
|
||||
def command(self, *args):
|
||||
return subprocess.check_output([*self.compose, *args], cwd=ROOT, text=True, encoding='utf-8', stderr=subprocess.PIPE)
|
||||
|
||||
def probe(self, action, **kwargs):
|
||||
script = 'ARGS=' + repr(dict(action=action, **kwargs)) + '\n' + (ROOT / 'student-tests/probe.py').read_text(encoding='utf-8')
|
||||
invocation = ([*self.compose, 'run', '--rm', '--no-deps', '-T', 'inspector', 'python', '-']
|
||||
if action == 'objects' else [*self.compose, 'exec', '-T', '--index', '1', 'api', 'python', '-'])
|
||||
result = subprocess.run(invocation,
|
||||
input=script, text=True, encoding='utf-8', capture_output=True, cwd=ROOT)
|
||||
check(result.returncode == 0, 'probe failed: ' + result.stderr)
|
||||
return json.loads(result.stdout)
|
||||
|
||||
def sql(self, query, *params):
|
||||
return self.probe('sql', query=query, params=list(params))
|
||||
|
||||
def job(self, att, version=1):
|
||||
return self.sql('SELECT * FROM attachment_jobs WHERE attachment_id=%s AND pipeline_version=%s', att['id'], version)[0]
|
||||
|
||||
@staticmethod
|
||||
def envelope(job):
|
||||
from datetime import datetime, timezone
|
||||
created = datetime.fromisoformat(job['created_at']).astimezone(timezone.utc).isoformat(timespec='microseconds').replace('+00:00', 'Z')
|
||||
return dict(schema_version=1, type='attachment.process.v1', job_id=job['id'], attachment_id=job['attachment_id'],
|
||||
pipeline_version=job['pipeline_version'], attempt=job['attempt'], created_at=created)
|
||||
|
||||
def upload(self):
|
||||
return self.c.attachment(self.alice, self.chat)[0]
|
||||
|
||||
def arm(self, job, point, action='crash'):
|
||||
self.sql('INSERT INTO experiment_faults(job_id,point,action) VALUES (%s,%s,%s)', job['id'], point, action)
|
||||
|
||||
def hit(self, job, point):
|
||||
deadline = time.monotonic() + 45
|
||||
while time.monotonic() < deadline:
|
||||
row = self.sql('SELECT * FROM experiment_faults WHERE job_id=%s AND point=%s', job['id'], point)[0]
|
||||
if row['hit_at']:
|
||||
return row
|
||||
time.sleep(.3)
|
||||
raise AssertionError('fault not hit: ' + point)
|
||||
|
||||
def snapshot(self):
|
||||
ids = self.command('ps', '-a', '-q').split()
|
||||
raw = subprocess.check_output(['docker', 'inspect', *ids], text=True, encoding='utf-8')
|
||||
return [dict(id=x['Id'], name=x['Name'], started_at=x['State']['StartedAt'],
|
||||
running=x['State']['Running'], restart_count=x['RestartCount'], exit_code=x['State']['ExitCode']) for x in json.loads(raw)]
|
||||
|
||||
def invariant(self, att, version=1):
|
||||
ready = self.c.wait_ready(self.alice, att, wait_seconds=120)
|
||||
check(len(ready['variants']) == 3, 'three variants required')
|
||||
row = self.sql('SELECT published_pipeline_version,target_pipeline_version FROM attachments WHERE id=%s', att['id'])[0]
|
||||
check(row['published_pipeline_version'] == version, 'wrong published version')
|
||||
variants = self.sql('SELECT * FROM attachment_variants WHERE attachment_id=%s AND pipeline_version=%s', att['id'], version)
|
||||
check(len(variants) == 3, 'duplicate/missing manifests')
|
||||
digest = {}
|
||||
for name in ('original', 'thumbnail', 'crop', 'optimized'):
|
||||
response = self.c.call('GET', '/api/v1/attachments/' + att['id'] + '/content?variant=' + name, actor=self.alice)
|
||||
sha = hashlib.sha256(response['bytes']).hexdigest()
|
||||
expected = att['sha256'] if name == 'original' else next(v['sha256'] for v in variants if v['name'] == name)
|
||||
check(sha == expected, 'download checksum mismatch')
|
||||
digest[name] = sha
|
||||
return digest
|
||||
|
||||
def record(self, name, started, **details):
|
||||
self.rows.append(dict(scenario=name, seconds=round(time.monotonic() - started, 3), **details))
|
||||
(ROOT / 'evidence/pipeline.json').write_text(json.dumps(self.rows, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
print('PASS:', name, flush=True)
|
||||
|
||||
def crashes(self):
|
||||
for repeat in range(self.args.repeats):
|
||||
for point in ('before_publish', 'after_publish', 'before_effect', 'after_original', 'after_variants', 'after_commit'):
|
||||
start = time.monotonic()
|
||||
service = 'dispatcher' if 'publish' in point else 'worker'
|
||||
self.command('stop', '-t', '2', service)
|
||||
att = self.upload()
|
||||
job = self.job(att)
|
||||
self.arm(job, point)
|
||||
before = self.snapshot()
|
||||
self.command('start', service)
|
||||
hit = self.hit(job, point)
|
||||
self.invariant(att)
|
||||
self.record(point, start, repeat=repeat + 1, attachment_id=att['id'], fault=hit,
|
||||
job_after=self.job(att), before=before, after=self.snapshot())
|
||||
|
||||
def durable(self):
|
||||
start = time.monotonic()
|
||||
self.command('stop', '-t', '2', 'worker')
|
||||
att = self.upload()
|
||||
self.c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', 409, actor=self.alice)
|
||||
self.probe('cleanup')
|
||||
check(any(obj['key'].startswith('staging/') for obj in self.probe('objects', id=att['id'])), 'active staging deleted')
|
||||
self.c.message(self.alice, self.chat, '', attachments=[att['id']])
|
||||
time.sleep(2)
|
||||
before = self.snapshot()
|
||||
self.command('restart', '-t', '2', 'api', 'broker')
|
||||
self.command('start', 'worker')
|
||||
self.invariant(att)
|
||||
self.record('accepted_survives_api_broker_restart', start, attachment_id=att['id'], before=before, after=self.snapshot())
|
||||
|
||||
def versions(self):
|
||||
for repeat in range(self.args.repeats):
|
||||
start = time.monotonic()
|
||||
self.command('stop', '-t', '2', 'worker')
|
||||
att = self.upload()
|
||||
old = self.job(att)
|
||||
self.arm(old, 'after_variants', 'pause')
|
||||
self.command('start', 'worker')
|
||||
self.hit(old, 'after_variants')
|
||||
self.probe('upgrade', id=att['id'])
|
||||
new = self.job(att, 2)
|
||||
# Новая работа, затем старая, затем 24 чередующихся дубля.
|
||||
self.probe('publish', messages=[self.envelope(new), self.envelope(old)] * 13)
|
||||
first = self.invariant(att, 2)
|
||||
objects = self.probe('objects', id=att['id'])
|
||||
self.sql('UPDATE experiment_faults SET released=true WHERE job_id=%s', old['id'])
|
||||
time.sleep(2)
|
||||
check(self.invariant(att, 2) == first, 'stale worker changed new result')
|
||||
self.probe('publish', messages=[self.envelope(old), self.envelope(new)] * 13)
|
||||
time.sleep(2)
|
||||
check(self.invariant(att, 2) == first, 'reorder changed new result')
|
||||
current = self.probe('objects', id=att['id'])
|
||||
check([x for x in current if not x['key'].startswith('staging/')] ==
|
||||
[x for x in objects if not x['key'].startswith('staging/')], 'duplicate wrote more objects')
|
||||
check(self.probe('replay', id=att['id']) is None, 'ready replay must no-op')
|
||||
self.record('stale_running_worker_and_reordered_duplicates', start, repeat=repeat + 1,
|
||||
attachment_id=att['id'], before_digest=first, after_digest=self.invariant(att, 2),
|
||||
versions=self.sql('SELECT pipeline_version,state,attempt FROM attachment_jobs WHERE attachment_id=%s ORDER BY pipeline_version', att['id']), objects=current)
|
||||
start = time.monotonic()
|
||||
att = self.upload()
|
||||
old_digest = self.invariant(att)
|
||||
self.probe('cleanup')
|
||||
self.probe('upgrade', id=att['id'])
|
||||
deadline = time.monotonic() + 60
|
||||
while self.job(att, 2)['state'] != 'ready':
|
||||
check(time.monotonic() < deadline, 'ready upgrade timeout')
|
||||
time.sleep(.3)
|
||||
new_digest = self.invariant(att, 2)
|
||||
check(new_digest['original'] == old_digest['original'], 'upgrade changed original')
|
||||
check(new_digest['thumbnail'] != old_digest['thumbnail'], 'versions must have a real different effect')
|
||||
self.record('upgrade_ready_after_staging_cleanup', start, repeat=repeat + 1, attachment_id=att['id'], before_digest=old_digest, after_digest=new_digest)
|
||||
|
||||
def errors(self):
|
||||
for kind in ('permanent', 'transient'):
|
||||
start = time.monotonic()
|
||||
self.command('stop', '-t', '2', 'worker')
|
||||
att = self.upload()
|
||||
if kind == 'permanent':
|
||||
self.probe('corrupt_staging', id=att['id'])
|
||||
else:
|
||||
self.probe('remove_staging', id=att['id'])
|
||||
self.command('start', 'worker')
|
||||
observed = []
|
||||
deadline = time.monotonic() + 120
|
||||
while True:
|
||||
job = self.job(att)
|
||||
observed.append(dict(attempt=job['attempt'], state=job['state'], next_publish_at=job['next_publish_at'], last_error=job['last_error']))
|
||||
if job['state'] == 'failed':
|
||||
break
|
||||
check(time.monotonic() < deadline, 'failed registry timeout')
|
||||
time.sleep(.3)
|
||||
check(job['attempt'] == (1 if kind == 'permanent' else job['attempt_limit']), 'wrong retry budget')
|
||||
self.c.call('POST', '/api/v1/chats/' + self.chat['id'] + '/messages', 409, actor=self.alice,
|
||||
headers={'Idempotency-Key': os.urandom(12).hex()}, body={'text': '', 'attachment_ids': [att['id']]})
|
||||
self.probe('restore_staging', id=att['id'], data=base64.b64encode((ROOT / 'tests/fixtures/sample.png').read_bytes()).decode())
|
||||
check(self.probe('replay', id=att['id']) is not None, 'failed replay missing')
|
||||
self.invariant(att)
|
||||
self.record(kind + '_error_and_explicit_replay', start, attachment_id=att['id'], attempts=observed,
|
||||
audit=self.sql('SELECT attempt,reason FROM attachment_replays WHERE job_id=%s', job['id']))
|
||||
|
||||
def negatives(self):
|
||||
start = time.monotonic()
|
||||
path = '/api/v1/chats/' + self.chat['id'] + '/attachments?filename=x.png'
|
||||
def upload(raw, expected, path=path, actor=None, mime='image/png'):
|
||||
self.c.call('POST', path, expected, actor=actor or self.alice, raw=raw, headers={'Content-Type': mime})
|
||||
upload(b'bad', 415)
|
||||
upload(b'x' * (10 * 1024 * 1024 + 1), 413)
|
||||
raw = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
upload(raw, 415, mime='image/jpeg')
|
||||
upload(raw, 400, path=path.replace('x.png', '..%2Fx.png'))
|
||||
upload(raw, 404, actor=self.eve)
|
||||
# Валидный PNG header >40 MP: отклонение до декодирования большого bitmap.
|
||||
def chunk(name, data):
|
||||
return struct.pack('>I', len(data)) + name + data + struct.pack('>I', zlib.crc32(name + data))
|
||||
huge = b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', 10000, 10000, 8, 2, 0, 0, 0)) + chunk(b'IDAT', zlib.compress(b'')) + chunk(b'IEND', b'')
|
||||
upload(huge, 413)
|
||||
att = self.upload()
|
||||
self.invariant(att)
|
||||
self.c.call('GET', '/api/v1/attachments/' + att['id'], 404, actor=self.eve)
|
||||
self.c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', 404, actor=self.eve)
|
||||
key = os.urandom(16).hex()
|
||||
with ThreadPoolExecutor(max_workers=12) as pool:
|
||||
responses = list(pool.map(lambda _: self.c.message(self.alice, self.chat, 'concurrent', key=key)['json']['id'], range(24)))
|
||||
check(len(set(responses)) == 1, 'message idempotency violated')
|
||||
self.record('negative_upload_acl_and_24_concurrent_messages', start, checks=9, message_ids=len(set(responses)))
|
||||
|
||||
def main(self):
|
||||
try:
|
||||
if not self.args.resume:
|
||||
self.negatives()
|
||||
self.durable()
|
||||
self.crashes()
|
||||
self.versions()
|
||||
self.errors()
|
||||
finally:
|
||||
self.sql('UPDATE experiment_faults SET released=true WHERE NOT released')
|
||||
self.command('start', 'api', 'broker', 'dispatcher', 'worker')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--project', default='lyakhonov-lab5')
|
||||
parser.add_argument('--base-url', default='http://127.0.0.1:8085')
|
||||
parser.add_argument('--repeats', type=int, default=3)
|
||||
parser.add_argument('--resume', action='store_true', help='Сохранить уже выполненные crash-результаты; выполнить version/error suite')
|
||||
Experiment(parser.parse_args()).main()
|
||||
@@ -0,0 +1,55 @@
|
||||
"""Исполняется внутри API через stdin; наружу возвращает только безопасные данные."""
|
||||
import json
|
||||
import sys
|
||||
from uuid import UUID
|
||||
|
||||
from src import broker, jobs
|
||||
from src.objects import BUCKET, client
|
||||
from src.storage import storage
|
||||
|
||||
|
||||
def run(args):
|
||||
action = args['action']
|
||||
if action == 'sql':
|
||||
with storage.pool.connection() as conn:
|
||||
cursor = conn.execute(args['query'], args.get('params', []))
|
||||
return cursor.fetchall() if cursor.description else []
|
||||
if action == 'publish':
|
||||
with broker.channel() as (_, channel):
|
||||
channel.confirm_delivery()
|
||||
for message in args['messages']:
|
||||
broker.publish(channel, message)
|
||||
return True
|
||||
if action == 'upgrade':
|
||||
return jobs.upgrade(UUID(args['id']), args.get('version', 2))
|
||||
if action == 'replay':
|
||||
return jobs.replay(UUID(args['id']))
|
||||
if action == 'cleanup':
|
||||
from src.staging import cleanup
|
||||
return cleanup(client(), 60)
|
||||
if action == 'objects':
|
||||
s3 = client()
|
||||
result = []
|
||||
for prefix in (f"originals/{args['id']}", f"variants/{args['id']}/", f"staging/{args['id']}"):
|
||||
for page in s3.get_paginator('list_objects_v2').paginate(Bucket=BUCKET, Prefix=prefix):
|
||||
result.extend({'key': row['Key'], 'etag': row['ETag'], 'size': row['Size']}
|
||||
for row in page.get('Contents', []))
|
||||
return result
|
||||
if action == 'remove_staging':
|
||||
client().delete_object(Bucket=BUCKET, Key=f"staging/{args['id']}")
|
||||
return True
|
||||
if action == 'corrupt_staging':
|
||||
client().put_object(Bucket=BUCKET, Key=f"staging/{args['id']}", Body=b'broken')
|
||||
return True
|
||||
if action == 'restore_staging':
|
||||
import base64
|
||||
client().put_object(Bucket=BUCKET, Key=f"staging/{args['id']}", Body=base64.b64decode(args['data']))
|
||||
return True
|
||||
raise ValueError('unknown probe action')
|
||||
|
||||
|
||||
storage.pool.open(wait=True)
|
||||
try:
|
||||
print(json.dumps(run(ARGS), default=str))
|
||||
finally:
|
||||
storage.pool.close()
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Публичные resilience и отдельный принудительный отказ каждой API-реплики."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, Failure, check
|
||||
|
||||
COMPOSE = ['docker', 'compose', '-p', 'lyakhonov-lab5']
|
||||
|
||||
|
||||
def docker(*args):
|
||||
return subprocess.check_output(['docker', *args], cwd=ROOT, text=True, encoding='utf-8')
|
||||
|
||||
|
||||
def snapshot():
|
||||
ids = docker('compose', '-p', 'lyakhonov-lab5', 'ps', '-a', '-q').split()
|
||||
raw = json.loads(docker('inspect', *ids))
|
||||
return [dict(id=x['Id'], name=x['Name'], started_at=x['State']['StartedAt'], running=x['State']['Running']) for x in raw]
|
||||
|
||||
|
||||
def public(mode):
|
||||
before = snapshot()
|
||||
script = ROOT / 'scripts' / (('restart' if mode == 'persistence' else 'stop-one') + ('.cmd' if sys.platform == 'win32' else '.sh'))
|
||||
result = subprocess.run([sys.executable, '-X', 'utf8', 'tests/resilience.py', '--mode', mode,
|
||||
'--base-url', 'http://127.0.0.1:8085', '--action-script', str(script)],
|
||||
cwd=ROOT, text=True, encoding='utf-8', capture_output=True)
|
||||
after = snapshot()
|
||||
(ROOT / f'evidence/{mode}.json').write_text(json.dumps(dict(command=result.args, exit_code=result.returncode,
|
||||
output=result.stdout + result.stderr, before=before, after=after), ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
print(result.stdout, flush=True)
|
||||
check(result.returncode == 0, result.stderr)
|
||||
subprocess.check_call([*COMPOSE, 'start', 'api'], cwd=ROOT)
|
||||
|
||||
|
||||
def targeted():
|
||||
c = Client('http://127.0.0.1:8085', timeout=2)
|
||||
alice, _, _, chat = c.bootstrap()
|
||||
ids = docker('compose', '-p', 'lyakhonov-lab5', 'ps', '-q', 'api').split()
|
||||
evidence = []
|
||||
for index, target in enumerate(ids):
|
||||
before = snapshot()
|
||||
responses, errors = [], []
|
||||
first = None
|
||||
begin = time.monotonic()
|
||||
subprocess.check_call(['docker', 'stop', '-t', '2', target], stdout=subprocess.DEVNULL)
|
||||
try:
|
||||
while time.monotonic() - begin < 15:
|
||||
key = f'explicit-{index}-{len(responses)}'
|
||||
try:
|
||||
response = c.message(alice, chat, 'replica failure', key=key)
|
||||
first = first or time.monotonic()-begin
|
||||
responses.append(response['json'])
|
||||
except Failure as exc:
|
||||
errors.append(str(exc))
|
||||
time.sleep(.05)
|
||||
check(first is not None and first <= 10, 'slow API failover')
|
||||
page = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=100', actor=alice)['json']
|
||||
messages = list(page['items'])
|
||||
while page['next_cursor']:
|
||||
from urllib.parse import quote
|
||||
page = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=100&cursor=' + quote(page['next_cursor'], safe=''), actor=alice)['json']
|
||||
messages.extend(page['items'])
|
||||
found = {m['id'] for m in messages}
|
||||
check(all(m['id'] in found for m in responses), 'acknowledged message lost')
|
||||
check(len(found) == len(messages), 'duplicate messages')
|
||||
evidence.append(dict(target=target, before=before, after=snapshot(), successes=len(responses),
|
||||
errors=errors, recovery_seconds=round(first, 3)))
|
||||
finally:
|
||||
subprocess.check_call(['docker', 'start', target], stdout=subprocess.DEVNULL)
|
||||
time.sleep(3)
|
||||
(ROOT / 'evidence/failover-each.json').write_text(json.dumps(evidence, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
print('PASS: both real API containers independently stopped and restored')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
public('persistence')
|
||||
public('failover')
|
||||
targeted()
|
||||
Reference in New Issue
Block a user