diff --git a/student-tests/pipeline_ops.py b/student-tests/pipeline_ops.py index 9f3597b..84800dc 100755 --- a/student-tests/pipeline_ops.py +++ b/student-tests/pipeline_ops.py @@ -103,6 +103,42 @@ def check_variants(c, actor, meta, original): 'optimized_bytes': vs['optimized']['size_bytes'], 'original_bytes': len(original)} +def rabbit_healthy(timeout=90): + end = time.time() + timeout + while time.time() < end: + st = sh('docker', 'inspect', '-f', '{{.State.Health.Status}}', compose('ps', '-q', 'rabbitmq').stdout.strip(), + check=False).stdout.strip() + if st == 'healthy': + return + time.sleep(1) + raise Failure('rabbitmq not healthy') + + +def queues(): + """Сообщений в очередях RabbitMQ (без строки заголовка).""" + rabbit_healthy() + out = compose('exec', '-T', 'rabbitmq', 'rabbitmqctl', '-q', 'list_queues', '--no-table-headers', + 'name', 'messages').stdout + res = {} + for line in out.splitlines(): + parts = line.split() + if len(parts) == 2 and parts[1].isdigit(): + res[parts[0]] = int(parts[1]) + return res + + +def drain(timeout=180): + """Изоляция сценариев: все сервисы pipeline запущены, незавершённых заданий нет.""" + compose('up', '-d', '--no-deps', '--wait', 'worker', 'relay', 'rabbitmq', 's3', timeout=240) + end = time.time() + timeout + while time.time() < end: + busy = psql("SELECT count(*) FROM jobs WHERE state IN ('queued', 'processing')") + if busy == '0': + return + time.sleep(1) + raise Failure('pipeline did not drain: %s jobs pending' % busy) + + def recreate(service, **env): """Пересоздать сервис с переменными окружения (точки сбоя, таймауты).""" compose('up', '-d', '--no-deps', '--wait', service, env=env, timeout=180) @@ -130,8 +166,7 @@ def scenario_demo(c): sh('sh', 'scripts/restore.sh') wait_ready_api(c) timeline.append('api and rabbitmq restarted (volumes kept), outbox published=%s' % published) - queued = compose('exec', '-T', 'rabbitmq', 'rabbitmqctl', '-q', 'list_queues', 'name', 'messages').stdout - timeline.append('rabbitmq queues after restart: ' + ' '.join(queued.split())) + timeline.append('rabbitmq queues after restart: %s' % queues()) t0 = time.time() compose('start', 'worker') meta = wait_status(c, bob, att['id'], ('ready',), timeout=90) @@ -170,6 +205,7 @@ def scenario_outbox_gap(c): recreate('relay') worker_log = compose('logs', '--no-color', 'worker').stdout dup_seen = worker_log.count(jid2) >= 2 + check(int(restarts) >= 1, 'fault relay.after_publish did not crash the relay') check(attempt2 == 1, 'duplicate publish must not create a second attempt') part2 = {'attachment_id': att2['id'], 'relay_restarts': int(restarts), 'outbox_publish_attempts': int(attempts or 0), 'worker_saw_message_twice': dup_seen, 'job_attempt': attempt2, 'invariants': invariants(att2['id'], chat['id'])} @@ -187,7 +223,7 @@ def scenario_crash_effect(c): cid = compose('ps', '-q', 'worker').stdout.split()[0] restarts = sh('docker', 'inspect', '-f', '{{.RestartCount}}', cid).stdout.strip() recreate('worker') - check(attempt == 2, 'expected recovery on attempt 2, got %d' % attempt) + check(attempt == 2, 'expected recovery on attempt 2, got %d; events=%s' % (attempt, events(jid))) ev = events(jid) check('lease_expired_requeued' in ev, 'lease expiry recovery missing: ' + ev) return {'attachment_id': att['id'], 'job_id': jid, 'worker_restarts': int(restarts), 'attempt': attempt, @@ -207,6 +243,7 @@ def scenario_crash_commit(c): log = compose('logs', '--no-color', 'worker').stdout noop = any(jid in l and 'duplicate delivery of finished job' in l for l in log.splitlines()) recreate('worker') + check(int(restarts) >= 1, 'fault worker.after_commit did not crash the worker') check(attempt == 1 and state == 'done', 'redelivery after commit must be a no-op: %s %d' % (state, attempt)) return {'attachment_id': att['id'], 'job_id': jid, 'worker_restarts': int(restarts), 'attempt': attempt, 'redelivery_acked_as_noop': noop, 'invariants': invariants(att['id'], chat['id'])} @@ -221,19 +258,13 @@ def scenario_broker_restart(c): if psql("SELECT count(*) FROM outbox WHERE job_id='%s' AND published_at IS NOT NULL" % jid) == '1': break time.sleep(0.5) - before = compose('exec', '-T', 'rabbitmq', 'rabbitmqctl', '-q', 'list_queues', 'name', 'messages').stdout + before = queues() compose('restart', 'rabbitmq') - for _ in range(60): - st = sh('docker', 'inspect', '-f', '{{.State.Health.Status}}', compose('ps', '-q', 'rabbitmq').stdout.strip()).stdout.strip() - if st == 'healthy': - break - time.sleep(1) - after = compose('exec', '-T', 'rabbitmq', 'rabbitmqctl', '-q', 'list_queues', 'name', 'messages').stdout + after = queues() compose('start', 'worker') wait_status(c, bob, att['id'], ('ready',)) - q = lambda out: {l.split()[0]: int(l.split()[1]) for l in out.splitlines() if len(l.split()) == 2} - check(q(after).get('attachment.process', 0) >= 1, 'message lost on broker restart: %s' % after) - return {'attachment_id': att['id'], 'queue_before_restart': q(before), 'queue_after_restart': q(after), + check(after.get('attachment.process', 0) >= 1, 'message lost on broker restart: %s' % after) + return {'attachment_id': att['id'], 'queue_before_restart': before, 'queue_after_restart': after, 'invariants': invariants(att['id'], chat['id'])} @@ -256,7 +287,7 @@ def scenario_transient(c): meta = wait_status(c, bob, att['id'], ('ready',), timeout=150) _, state, attempt = job_of(att['id']) details = psql("SELECT string_agg(detail, ' | ' ORDER BY id) FROM job_events WHERE job_id='%s' AND event='retry_scheduled'" % jid) - check(attempt >= 2 and state == 'done', 'expected retries then success') + check(attempt >= 2 and state == 'done', 'expected retries then success: %s/%d events=%s' % (state, attempt, events(jid))) return {'attachment_id': att['id'], 'attempts': attempt, 'final_status': meta['status'], 'retry_details': details, 'events': events(jid), 'invariants': invariants(att['id'], chat['id'])} @@ -293,8 +324,7 @@ def scenario_failed_replay(c): psql("INSERT INTO outbox (job_id, payload) VALUES ('%s', '{\"schema_version\": 99}'::jsonb)" % jid) dead = 0 for _ in range(30): - out = compose('exec', '-T', 'rabbitmq', 'rabbitmqctl', '-q', 'list_queues', 'name', 'messages').stdout - dead = {l.split()[0]: int(l.split()[1]) for l in out.splitlines() if len(l.split()) == 2}.get('attachment.dead', 0) + dead = queues().get('attachment.dead', 0) if dead >= 1: break time.sleep(1) @@ -385,7 +415,12 @@ def main(): p.add_argument('--output', default=None) args = arguments('Lab5 pipeline scenarios on the Docker stand', configure) c = Client(args.base_url, args.ca_file, timeout=60) - result = SCENARIOS[args.scenario](c) + drain() + try: + result = SCENARIOS[args.scenario](c) + finally: + # Сценарий мог остановить сервисы или включить точки сбоя: возвращаем штатную конфигурацию. + compose('up', '-d', '--no-deps', '--wait', 'worker', 'relay', 'rabbitmq', 's3', 'api', timeout=300, check=False) text = json.dumps({'scenario': args.scenario, 'result': result}, ensure_ascii=False, indent=2) if args.output: open(args.output, 'w', encoding='utf-8').write(text + '\n')