243 lines
13 KiB
Python
243 lines
13 KiB
Python
"""Реальные 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()
|