This commit is contained in:
Максим Шептунов
2026-10-13 19:30:32 +03:00
parent 0ab3a341aa
commit 08d70c462c
65 changed files with 148882 additions and 18 deletions
+156
View File
@@ -0,0 +1,156 @@
"""Один профиль нагрузки для всех серий. Только синтетические данные, без токенов в отчёте."""
from concurrent.futures import ThreadPoolExecutor
from collections import Counter
import math
from pathlib import Path
import sys
import threading
import time
import uuid
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import Client, Failure
def context(base):
c = Client(base)
alice, bob, _, chat = c.bootstrap()
return dict(actor=alice, reader=bob, chat=chat)
def percentile(values, p):
if not values:
return None
return round(sorted(values)[max(0, math.ceil(p * len(values)) - 1)] * 1000, 3)
def measure(base, ctx, duration, concurrency, action=None, retry_writes=False):
gate = threading.Event()
started = time.monotonic()
deadline = started + duration
action_events = []
def perform_action():
nonlocal deadline
time.sleep(2)
start = time.monotonic()
try:
info = action()
deadline = max(deadline, time.monotonic() + 5)
action_events.append(dict(start_seconds=start-started, end_seconds=time.monotonic()-started,
result=info))
except Exception as exc:
action_events.append(dict(start_seconds=start-started, error=str(exc)))
def worker(worker):
c = Client(base, timeout=3)
gate.wait()
latencies, confirmed, bins = [], [], Counter()
errors, instances, failures, operation_counts = Counter(), Counter(), [], Counter()
step, pending = worker, None
while time.monotonic() < deadline or (action_thread and action_thread.is_alive()):
if time.monotonic() - started > 180:
raise RuntimeError('Infrastructure action exceeded workload time limit')
begin = time.monotonic()
# Один и тот же цикл: 60% POST, 20% история, 20% профиль.
operation = 'write' if pending or step % 5 < 3 else ('history' if step % 5 == 3 else 'profile')
operation_counts[operation] += 1
try:
if operation == 'write':
key, text = pending or (uuid.uuid4().hex, 'x' * 128)
response = c.message(ctx['actor'], ctx['chat'], text, key=key)
confirmed.append(response['json'])
pending = None
elif operation == 'history':
response = c.call('GET', '/api/v1/chats/' + ctx['chat']['id'] + '/messages?limit=50',
actor=ctx['reader'], schema='MessagePage')
else:
response = c.call('GET', '/api/v1/users/me', actor=ctx['actor'], schema='User')
elapsed = time.monotonic() - begin
latencies.append(elapsed)
instances[response['headers']['X-Instance-Id']] += 1
bins[int(time.monotonic() - started)] += 1
except Failure as exc:
# Сообщения ошибки клиента не содержат credentials/body.
errors[str(exc)] += 1
failures.append(round(time.monotonic()-started, 3))
if operation == 'write' and retry_writes:
pending = (key, text)
step += 1
# Последний timeout мог произойти после COMMIT. Уточняем результат тем же
# ключом вне измеряемого окна, иначе проверка ошибочно сочтёт его дубликатом.
finished = time.monotonic()
resolved = 0
if pending:
for attempt in range(10):
try:
confirmed.append(c.message(ctx['actor'], ctx['chat'], pending[1], key=pending[0])['json'])
pending = None
resolved = 1
break
except Failure:
time.sleep(.5)
if pending:
raise RuntimeError('Final uncertain write could not be resolved')
return dict(latencies=latencies, confirmed=confirmed, errors=errors, instances=instances,
failures=failures, bins=bins, operation_counts=operation_counts,
finished=finished, resolved_outside_window=resolved)
action_thread = threading.Thread(target=perform_action) if action else None
with ThreadPoolExecutor(max_workers=concurrency) as pool:
jobs = [pool.submit(worker, i) for i in range(concurrency)]
started = time.monotonic()
deadline = started + duration
if action_thread:
action_thread.start()
gate.set()
results = [job.result() for job in jobs]
elapsed = max(r['finished'] for r in results) - started
if action_thread:
action_thread.join(timeout=120)
if action_thread.is_alive():
raise RuntimeError('Infrastructure action did not finish')
if any('error' in e for e in action_events):
raise RuntimeError(str(action_events))
values = [x for r in results for x in r['latencies']]
errors, instances, bins, operation_counts = Counter(), Counter(), Counter(), Counter()
for r in results:
errors.update(r['errors']); instances.update(r['instances'])
bins.update(r['bins']); operation_counts.update(r['operation_counts'])
successes, failed = len(values), sum(errors.values())
report = dict(duration_requested=duration, elapsed_seconds=round(elapsed, 3), concurrency=concurrency,
profile='closed-loop: 60% POST text128, 20% first50 history, 20% profile',
retry_writes=retry_writes, successful_requests=successes, failed_attempts=failed,
uncertain_writes_resolved_after_window=sum(r['resolved_outside_window'] for r in results),
successful_rps=round(successes/elapsed, 3), error_ratio=failed/max(1, successes+failed),
successful_latency_ms={f'p{int(p*100)}': percentile(values, p) for p in [.5, .95, .99]},
instances=dict(instances), errors=dict(errors), operations=dict(operation_counts),
successful_per_second=dict(sorted(bins.items())),
failure_seconds=[x for r in results for x in r['failures']],
latency_samples_ms=[round(x*1000, 3) for x in values], action_events=action_events)
if not successes:
raise RuntimeError('No successful requests')
return report, [m for r in results for m in r['confirmed']]
def verify_confirmations(base, ctx, confirmations):
from urllib.parse import quote
c = Client(base)
path = '/api/v1/chats/' + ctx['chat']['id'] + '/messages?limit=100'
stored = {}
while True:
page = c.call('GET', path, actor=ctx['reader'], schema='MessagePage')['json']
for message in page['items']:
if message['id'] in stored:
raise AssertionError('Duplicate ID in history')
stored[message['id']] = message
if page['next_cursor'] is None:
break
path = '/api/v1/chats/' + ctx['chat']['id'] + '/messages?limit=100&cursor=' + quote(page['next_cursor'])
if not all(stored.get(m['id']) == m for m in confirmations):
raise AssertionError('Confirmed message missing after infrastructure action')
# В fault-сценарии нет seed. Каждый новый ключ должен породить одну строку.
expected = {m['id'] for m in confirmations}
if set(stored) - expected:
raise AssertionError('Retry created an extra message or left an unconfirmed result')
return dict(confirmed_messages=len(expected), stored_messages=len(stored), status='PASS')
+191
View File
@@ -0,0 +1,191 @@
"""Трек 1: цена масштабирования и отдельная проверка размера пула соединений."""
import argparse
import json
import os
from pathlib import Path
import statistics
import subprocess
import sys
import time
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from scripts.benchmark import context, measure
from scripts.monitor import Monitor
from scripts.stack import scale, save, command, containers
def seed(ctx):
data = json.dumps(dict(chat_id=ctx['chat']['id'], sender_id=ctx['actor']['id']))
running = [row for row in containers('api') if row['running']]
if not running:
raise RuntimeError('Нет запущенной API для заполнения истории')
subprocess.run(['docker', 'exec', '-i', running[0]['id'],
'python', 'scripts/seed_history.py'], input=data, text=True,
cwd=ROOT, check=True, timeout=60)
def summarize(rows):
groups = {}
for row in rows:
key = (row['series'], row['replicas'], row['concurrency'], row['pool'])
groups.setdefault(key, []).append(row)
result = []
for key, group in groups.items():
result.append(dict(series=key[0], replicas=key[1], concurrency=key[2], pool=key[3],
repetitions=len(group),
rps=round(statistics.median(r['successful_rps'] for r in group), 3),
p95_ms=round(statistics.median(r['successful_latency_ms']['p95'] for r in group), 3),
error_ratio=statistics.mean(r['error_ratio'] for r in group)))
return result
def plots(summary):
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
for metric, name in [('rps', 'Successful RPS'), ('p95_ms', 'p95, ms')]:
fig, axes = plt.subplots(1, 2, figsize=(10, 4))
for ax, series in zip(axes, ['fixed', 'growth']):
for n in [1, 2, 4]:
points = sorted((r for r in summary if r['series'] == series and r['replicas'] == n),
key=lambda r: r['concurrency'])
ax.plot([r['concurrency'] for r in points], [r[metric] for r in points],
marker='o', label=f'{n} replicas')
ax.set(title=series, xlabel='Concurrent clients', ylabel=name)
ax.grid(alpha=.3); ax.legend()
fig.tight_layout()
fig.savefig(ROOT / 'evidence' / f'scaling_{metric}.png', dpi=150)
plt.close(fig)
def conclusions(summary, rows):
lines = ['# Трек 1: фактические результаты', '',
'Медианы повторов; p95 считается только по успешным запросам. Ошибки показаны отдельно.', '',
'| Серия | API | Clients | Pool/API | RPS | p95 ms | Ошибки |',
'| --- | ---: | ---: | ---: | ---: | ---: | ---: |']
for r in summary:
lines.append(f"| {r['series']} | {r['replicas']} | {r['concurrency']} | {r['pool']} | "
f"{r['rps']} | {r['p95_ms']} | {r['error_ratio']:.2%} |")
lines += ['', '## Где рост нагрузки перестал давать заметный прирост RPS', '']
plateau = []
for series in ['fixed', 'growth']:
for n in [1, 2, 4]:
points = sorted((r for r in summary if r['series'] == series and r['replicas'] == n),
key=lambda r: r['concurrency'])
pairs = [(a, b) for a, b in zip(points, points[1:]) if b['rps'] <= a['rps'] * 1.10]
if pairs:
a, b = pairs[0]
plateau.append(dict(series=series, replicas=n, clients_from=a['concurrency'],
clients_to=b['concurrency']))
lines.append(f"- {series}, {n} API: clients {a['concurrency']} → {b['concurrency']}, "
f"RPS {a['rps']} → {b['rps']}; p95 {a['p95_ms']} → {b['p95_ms']} ms.")
if not plateau:
lines.append('Плато не найдено: увеличить список concurrency и повторить. Насыщение пока не доказано.')
before = next(r for r in summary if r['series'] == 'pool_before')
after = next(r for r in summary if r['series'] == 'pool_after')
increase_gain = after['rps'] / before['rps'] - 1
# Имена серий отражают исходную гипотезу 1 -> 8, а не заранее известный победитель.
# Сравниваем оба направления, сохраняя исходные замеры и номера повторов.
baseline, candidate = (after, before) if before['rps'] > after['rps'] else (before, after)
gain = candidate['rps'] / baseline['rps'] - 1
p95_reduction = 1 - candidate['p95_ms'] / baseline['p95_ms']
baseline_runs = {r['repetition']: r for r in rows if r['series'] == baseline['series']}
candidate_runs = {r['repetition']: r for r in rows if r['series'] == candidate['series']}
repeats = sorted(baseline_runs.keys() & candidate_runs.keys())
consistent = len(repeats) >= 3 and all(
candidate_runs[n]['successful_rps'] > baseline_runs[n]['successful_rps'] and
candidate_runs[n]['successful_latency_ms']['p95'] < baseline_runs[n]['successful_latency_ms']['p95'] and
candidate_runs[n]['error_ratio'] <= baseline_runs[n]['error_ratio'] + .005
for n in repeats)
improved = gain >= .05 and p95_reduction > 0 and consistent
queued = max((pool['stats'].get('requests_waiting', 0)
for r in rows if r['series'] == 'pool_before'
for sample in r['monitor'] for pool in sample.get('pools', [])), default=0)
lines += ['', '## Проверка одного изменения', '',
'Одинаковые 4 API, по 0.5 CPU и 256 MiB. Сравниваются DB_POOL_MAX=1 и 8; остальные лимиты неизменны.',
'Исходная гипотеза — увеличение пула 1 → 8; названия pool_before/pool_after сохранены.',
f'Изменение median RPS при 1 → 8: {increase_gain:+.1%}.',
f'Лучший измеренный вариант: pool={candidate["pool"]}; сравнение {baseline["pool"]} → {candidate["pool"]}.',
f'Median RPS: {baseline["rps"]} → {candidate["rps"]}; изменение {gain:+.1%}.',
f'Median p95: {baseline["p95_ms"]} → {candidate["p95_ms"]} ms; снижение {p95_reduction:.1%}.',
f'Число пар повторов: {len(repeats)}; одинаковое направление RPS/p95 без роста ошибок: {"да" if consistent else "нет"}.',
f'Максимум наблюдаемой очереди при pool=1: {queued}.',
'', 'Наличие очереди не доказывает, что нужно увеличивать пул. '
'Вывод о механизме проверяется по CPU/RAM и ожиданиям PG из monitor. '
'Результат относится к измеренному профилю и лимитам, не к любому серверу.']
confirmed = improved and queued > 0 and bool(plateau)
status = 'MEASURED_IMPROVEMENT' if confirmed else 'NEEDS_REVIEW'
lines += ['', f'Статус эксперимента: {status}.']
(ROOT / 'evidence' / 'track1_summary.md').write_text('\n'.join(lines) + '\n')
return dict(status=status, original_increase_rps_gain=increase_gain,
tested_change=f'{baseline["pool"]}_to_{candidate["pool"]}',
recommended_pool=candidate['pool'], rps_gain=gain, p95_reduction=p95_reduction,
paired_repetitions=len(repeats), consistent_pairs=consistent,
maximum_pool_queue_before=queued, plateau=plateau)
def main():
p = argparse.ArgumentParser()
p.add_argument('--duration', type=int, default=15)
p.add_argument('--warmup', type=int, default=3)
p.add_argument('--repeats', type=int, default=2)
p.add_argument('--concurrency', nargs='+', type=int, default=[1, 4, 16, 32])
p.add_argument('--summarize-only', action='store_true', help='Analyse saved raw data without load or Docker changes')
args = p.parse_args()
if args.summarize_only:
rows = json.loads((ROOT / 'evidence' / 'track1_raw.json').read_text())['runs']
summary = summarize(rows)
verdict = conclusions(summary, rows)
save('track1_summary.json', dict(groups=summary, conclusion=verdict))
print('Experiment status:', verdict['status'])
return
if min(args.duration, args.warmup, args.repeats, *args.concurrency) < 1:
p.error('All parameters must be positive')
base = os.getenv('BASE_URL', 'http://localhost:8080')
rows = []
metadata = dict(parameters=vars(args), docker_version=command(['docker', 'version', '--format', '{{.Server.Version}}']),
compose_version=command(['docker', 'compose', 'version', '--short']),
logical_cpus=os.cpu_count(), started_at=time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()),
database_and_lb_limits='Unchanged throughout; actual values in containers',
initial_history_per_case=10000, monitoring_interval_seconds=3,
pool_before_is_deliberately_constrained=True)
cases = []
for series in ['fixed', 'growth']:
for n in [1, 2, 4]:
cpu, memory = (2 / n, f'{1024 // n}m') if series == 'fixed' else (1, '256m')
for clients in args.concurrency:
for repeat in range(args.repeats):
cases.append((series, n, cpu, memory, 8, clients, repeat))
# Порядок AB/BA чередуется, чтобы рост базы и прогрев не помогали всегда одному варианту.
for repeat in range(max(3, args.repeats)):
for pool in ([1, 8] if repeat % 2 == 0 else [8, 1]):
cases.append(('pool_before' if pool == 1 else 'pool_after', 4, .5, '256m', pool,
max(args.concurrency), repeat))
try:
for index, (series, n, cpu, memory, pool, clients, repeat) in enumerate(cases, 1):
print(f'[{index}/{len(cases)}] {series}, API={n}, clients={clients}, pool={pool}', flush=True)
topology = scale(n, cpu, memory, pool)
ctx = context(base)
seed(ctx)
measure(base, ctx, args.warmup, clients)
with Monitor() as monitor:
report, _ = measure(base, ctx, args.duration, clients)
report.update(series=series, replicas=n, cpu_per_api=cpu, ram_per_api=memory,
pool=pool, repetition=repeat + 1, containers=containers(),
topology=topology, monitor=monitor.samples)
rows.append(report)
save('track1_raw.json', dict(metadata=metadata, runs=rows))
summary = summarize(rows)
verdict = conclusions(summary, rows)
save('track1_summary.json', dict(groups=summary, conclusion=verdict))
plots(summary)
print('Experiment status:', verdict['status'])
if verdict['status'] == 'NEEDS_REVIEW':
print('Изменение не подтверждено: проверьте ошибки, мониторинг и условия измерения.')
finally:
scale(2, 1, '256m', 8)
if __name__ == '__main__':
main()
+12
View File
@@ -0,0 +1,12 @@
#!/usr/bin/env python3
import json
import os
import urllib.request
host = "127.0.0.1"
port = os.getenv("APP_PORT", "8080")
with urllib.request.urlopen(f"http://{host}:{port}/health/ready", timeout=2) as response:
payload = json.load(response)
if response.status != 200 or payload != {"status": "ok"}:
raise SystemExit(1)
+44
View File
@@ -0,0 +1,44 @@
"""Редкие снимки Docker CPU/RAM и ожиданий PostgreSQL; overhead отражён в методике."""
import json
import threading
import time
from scripts.stack import command, containers
class Monitor:
def __init__(self):
self.samples = []
self.stop = threading.Event()
self.thread = threading.Thread(target=self.loop)
def __enter__(self):
self.started = time.monotonic()
self.thread.start()
return self
def __exit__(self, *args):
self.stop.set()
self.thread.join(timeout=120)
def loop(self):
while not self.stop.is_set():
try:
ids = [r['id'] for r in containers() if r['running'] and r['service'] != 'migrate']
raw = command(['docker', 'stats', '--no-stream', '--format', '{{json .}}', *ids])
stats = [json.loads(line) for line in raw.splitlines()]
query = "SELECT coalesce(json_agg(x),'[]') FROM (SELECT state,wait_event_type," \
"wait_event,count(*) FROM pg_stat_activity WHERE backend_type='client backend' " \
"AND pid<>pg_backend_pid() GROUP BY state,wait_event_type,wait_event) x"
waits = json.loads(command(['docker', 'compose', 'exec', '-T', 'db',
'psql', '-U', 'messenger', '-d', 'messenger', '-Atc', query]))
pools = []
for row in containers('api'):
if row['running']:
output = command(['docker', 'exec', row['id'], 'python', '-c',
'import urllib.request; print(urllib.request.urlopen("http://localhost:8080/internal/pool",timeout=3).read().decode())'])
pools.append(dict(instance=row['hostname'], stats=json.loads(output)))
self.samples.append(dict(seconds=round(time.monotonic()-self.started, 3),
docker=stats, postgres=waits, pools=pools))
except Exception as exc:
self.samples.append(dict(seconds=round(time.monotonic()-self.started, 3), error=str(exc)))
self.stop.wait(3)
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
docker compose stop lb api cache db
docker compose up -d --wait db cache
docker compose run --rm --no-deps migrate
docker compose up -d --no-deps --wait api
docker compose up -d --no-deps lb
python3 scripts/stack.py wait --count 2
+5
View File
@@ -0,0 +1,5 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
docker compose start api
python3 scripts/stack.py wait --count 2
+16
View File
@@ -0,0 +1,16 @@
"""Только эксперимент: фиксированная начальная история синтетического чата."""
import json
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from uuid import UUID
import psycopg
from src.config import DATABASE_URL
data = json.load(sys.stdin)
with psycopg.connect(DATABASE_URL) as db:
db.execute("INSERT INTO messages(id,chat_id,sender_id,text,created_at) "
"SELECT gen_random_uuid(),%s,%s,repeat('h',128), "
"clock_timestamp()-(10000-n)*interval '1 millisecond' FROM generate_series(1,10000) n",
(UUID(data['chat_id']), UUID(data['sender_id'])))
print('Synthetic history: 10000 messages')
+19
View File
@@ -0,0 +1,19 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
mkdir -p .secrets
chmod 700 .secrets
python3 - <<'PY'
from pathlib import Path
import secrets
password_file = Path('.secrets/db_password')
if not password_file.exists():
password_file.write_text(secrets.token_hex(24))
password = password_file.read_text().strip()
Path('.secrets/database_url').write_text(f'postgresql://messenger:{password}@db:5432/messenger')
for file in Path('.secrets').iterdir():
file.chmod(0o644 if file.name == "database_url" else 0o600)
if not Path('.env').exists():
Path('.env').write_text('APP_PORT=8080\nSESSION_TTL_SECONDS=3600\nDB_POOL_MAX=8\nAPI_CPU=1.0\nAPI_MEMORY=256m\n')
print('Локальные настройки подготовлены; секреты не выводятся.')
PY
+129
View File
@@ -0,0 +1,129 @@
"""Небольшие операции со стендом: состояние, ожидание, масштабирование и замена."""
import argparse
import json
import os
from pathlib import Path
import subprocess
import time
import urllib.request
ROOT = Path(__file__).resolve().parents[1]
def command(args, env=None):
result = subprocess.run(args, cwd=ROOT, env=env, text=True, capture_output=True, timeout=120)
if result.returncode:
raise RuntimeError(result.stderr[-2000:])
return result.stdout.strip()
def containers(service=None):
args = ['docker', 'compose', 'ps', '-a', '-q']
if service:
args.append(service)
ids = command(args).split()
if not ids:
return []
# Сохраняем только нужные поля, без environment с возможными секретами.
rows = json.loads(command(['docker', 'inspect', *ids]))
return [dict(id=r['Id'], name=r['Name'].lstrip('/'), hostname=r['Config']['Hostname'],
service=r['Config']['Labels']['com.docker.compose.service'],
running=r['State']['Running'], started_at=r['State']['StartedAt'],
cpu_limit=r['HostConfig']['NanoCpus'] / 1e9,
memory_limit_bytes=r['HostConfig']['Memory'],
published_ports=r['NetworkSettings']['Ports']) for r in rows]
def save(name, data):
path = ROOT / 'evidence' / name
path.parent.mkdir(exist_ok=True)
path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + '\n')
def wait(count, base=None):
base = base or os.getenv('BASE_URL', 'http://localhost:8080')
deadline = time.monotonic() + 75
while time.monotonic() < deadline:
observed = set()
for _ in range(max(12, count * 8)):
try:
with urllib.request.urlopen(base + '/health/ready', timeout=3) as response:
observed.add(response.headers['X-Instance-Id'])
except (OSError, ValueError):
break
if len(observed) == count and None not in observed:
return sorted(observed)
time.sleep(.5)
raise RuntimeError(f'Не дождались {count} готовых API через LB')
def stop(instance):
hostname = instance.split(':')[0]
found = [r for r in containers('api') if r['hostname'] == hostname and r['running']]
if len(found) != 1:
raise RuntimeError('Instance alias не соответствует одной работающей API-реплике')
before = containers()
command(['docker', 'stop', '--time', '3', found[0]['id']])
result = dict(target=instance, stopped_container=found[0]['id'], before=before, after=containers())
save('last_stop.json', result)
return result
def scale(count, cpu, memory, pool):
env = dict(os.environ, API_CPU=str(cpu), API_MEMORY=memory, DB_POOL_MAX=str(pool))
command(['docker', 'compose', 'up', '-d', '--no-deps', '--force-recreate',
'--scale', f'api={count}', 'api'], env)
instances = wait(count)
rows = containers('api')
if len(rows) != count or not all(r['running'] for r in rows):
raise RuntimeError('Фактическое число контейнеров отличается от запрошенного')
for row in rows:
if abs(row['cpu_limit'] - cpu) > .001:
raise RuntimeError('Docker не применил CPU limit')
if row['memory_limit_bytes'] != int(memory.rstrip('m')) * 1024 * 1024:
raise RuntimeError('Docker не применил RAM limit')
return dict(instances=instances, containers=rows)
def rolling():
old = [r['id'] for r in containers('api') if r['running']]
if len(old) != 2:
raise RuntimeError('Rolling проверяется на двух репликах обычного стенда')
before = containers()
command(['docker', 'compose', 'build', 'api'])
steps = []
for container in old:
# Не пересоздаём одновременно старые контейнеры при изменении image.
command(['docker', 'compose', 'up', '-d', '--no-deps', '--no-recreate', '--scale', 'api=3', 'api'])
wait(3)
command(['docker', 'stop', '--time', '10', container])
command(['docker', 'rm', container])
wait(2)
steps.append(containers('api'))
save('rolling_containers.json', dict(before=before, steps=steps, after=containers()))
def main():
p = argparse.ArgumentParser()
p.add_argument('action', choices=['wait', 'snapshot', 'stop', 'rolling'])
p.add_argument('--count', type=int, default=2)
p.add_argument('--instance')
p.add_argument('--output', default='containers.json')
args = p.parse_args()
if args.action == 'wait':
print('API ready:', ', '.join(wait(args.count)))
elif args.action == 'snapshot':
save(args.output, containers())
print('Container identities and limits saved')
elif args.action == 'stop':
if not args.instance:
p.error('--instance required')
stop(args.instance)
print('Selected API stopped')
else:
rolling()
print('API replaced one at a time')
if __name__ == '__main__':
main()
+5
View File
@@ -0,0 +1,5 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
docker compose up -d --build --wait
python3 scripts/stack.py wait --count 2
+5
View File
@@ -0,0 +1,5 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
: "${TARGET_INSTANCE_ID:?TARGET_INSTANCE_ID is required}"
python3 scripts/stack.py stop --instance "$TARGET_INSTANCE_ID"
+11
View File
@@ -0,0 +1,11 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
restore() {
docker compose up -d --no-deps --force-recreate --scale api=2 api
python3 scripts/stack.py wait --count 2
}
trap restore EXIT
SESSION_TTL_SECONDS=2 docker compose up -d --no-deps --force-recreate --scale api=2 api
python3 scripts/stack.py wait --count 2
python3 student-tests/checks.py --expiry
+17
View File
@@ -0,0 +1,17 @@
"""Ожидание готовности API без сторонних библиотек."""
import os
import time
import urllib.request
url = os.getenv('BASE_URL', 'http://localhost:8080') + '/health/ready'
for attempt in range(90):
try:
with urllib.request.urlopen(url, timeout=2) as response:
if response.status == 200:
print('API ready')
break
except OSError:
pass
time.sleep(1)
else:
raise SystemExit('API не стал готов за 90 попыток')