forked from mtusi2026/mtusi2026lab3
Сессия и ключ идемпотентности общие для реплик, миграция выполняется один раз, остановка одной реплики не теряет подтверждённые сообщения.
207 lines
7.8 KiB
Python
207 lines
7.8 KiB
Python
"""Track 1. Fixed total CPU/RAM, then a growing budget, then one pool change.
|
|
|
|
The strict cap takes one global lock per message. The shipped default is cap off.
|
|
This script measures both and writes evidence/track1.json plus evidence/track1.svg.
|
|
"""
|
|
import json
|
|
import platform
|
|
import subprocess
|
|
import sys
|
|
import threading
|
|
import time
|
|
from pathlib import Path
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
|
|
from client import Client
|
|
import stand
|
|
|
|
ROOT = stand.ROOT
|
|
DURATION = 12
|
|
CONCURRENCY = 8
|
|
|
|
RUNS = [
|
|
{'series': 'fixed-strict', 'replicas': 1, 'cpus': '1.0', 'memory': '1024M', 'cap': 'strict', 'pool': 4},
|
|
{'series': 'fixed-strict', 'replicas': 2, 'cpus': '0.50', 'memory': '512M', 'cap': 'strict', 'pool': 4},
|
|
{'series': 'fixed-strict', 'replicas': 4, 'cpus': '0.25', 'memory': '256M', 'cap': 'strict', 'pool': 4},
|
|
{'series': 'fixed-off', 'replicas': 1, 'cpus': '1.0', 'memory': '1024M', 'cap': 'off', 'pool': 4},
|
|
{'series': 'fixed-off', 'replicas': 2, 'cpus': '0.50', 'memory': '512M', 'cap': 'off', 'pool': 4},
|
|
{'series': 'fixed-off', 'replicas': 4, 'cpus': '0.25', 'memory': '256M', 'cap': 'off', 'pool': 4},
|
|
{'series': 'grow-off', 'replicas': 1, 'cpus': '0.50', 'memory': '256M', 'cap': 'off', 'pool': 4},
|
|
{'series': 'grow-off', 'replicas': 2, 'cpus': '0.50', 'memory': '256M', 'cap': 'off', 'pool': 4},
|
|
{'series': 'grow-off', 'replicas': 4, 'cpus': '0.50', 'memory': '256M', 'cap': 'off', 'pool': 4},
|
|
{'series': 'pool-16', 'replicas': 4, 'cpus': '0.50', 'memory': '256M', 'cap': 'off', 'pool': 16},
|
|
]
|
|
|
|
|
|
def deploy(cfg):
|
|
stand.compose(
|
|
['up', '-d', '--no-deps', '--force-recreate', '--scale', 'api=%d' % cfg['replicas'], 'api'],
|
|
extra_env={
|
|
'API_CPUS': cfg['cpus'],
|
|
'API_MEMORY': cfg['memory'],
|
|
'CAP_MODE': cfg['cap'],
|
|
'POOL_MAX': str(cfg['pool']),
|
|
'API_REPLICAS': str(cfg['replicas']),
|
|
},
|
|
)
|
|
stand.wait_ready(timeout=120)
|
|
|
|
|
|
def run_load(output):
|
|
samples = []
|
|
stop = {'flag': False}
|
|
|
|
def stats():
|
|
while not stop['flag']:
|
|
try:
|
|
samples.append(stand.sample_stats())
|
|
except Exception:
|
|
pass
|
|
time.sleep(2)
|
|
|
|
thread = threading.Thread(target=stats)
|
|
thread.start()
|
|
completed = subprocess.run(
|
|
[
|
|
sys.executable,
|
|
str(ROOT / 'tests' / 'load.py'),
|
|
'--base-url', stand.BASE,
|
|
'--duration', str(DURATION),
|
|
'--concurrency', str(CONCURRENCY),
|
|
'--output', str(output),
|
|
],
|
|
cwd=ROOT,
|
|
text=True,
|
|
capture_output=True,
|
|
)
|
|
stop['flag'] = True
|
|
thread.join()
|
|
report = json.loads(output.read_text(encoding='utf-8')) if output.exists() else {}
|
|
report['load_exit'] = completed.returncode
|
|
if completed.returncode != 0 and 'successful_requests' not in report:
|
|
report['stderr_tail'] = (completed.stderr or completed.stdout or '')[-400:]
|
|
return report, samples
|
|
|
|
|
|
def svg(rows):
|
|
width, height = 920, 420
|
|
groups = []
|
|
for series in ('fixed-strict', 'fixed-off', 'grow-off', 'pool-16'):
|
|
items = [row for row in rows if row['series'] == series]
|
|
if items:
|
|
groups.append((series, items))
|
|
bar_w = 28
|
|
gap = 14
|
|
group_gap = 36
|
|
max_rps = max((row['successful_rps'] or 0) for row in rows) or 1
|
|
parts = [
|
|
'<svg xmlns="http://www.w3.org/2000/svg" width="%d" height="%d">' % (width, height),
|
|
'<rect width="100%" height="100%" fill="#f7f4ee"/>',
|
|
'<text x="24" y="32" font-family="sans-serif" font-size="18">Successful RPS, closed loop, %ds, concurrency %d</text>' % (DURATION, CONCURRENCY),
|
|
]
|
|
x = 48
|
|
colors = {
|
|
'fixed-strict': '#8c4a3a',
|
|
'fixed-off': '#2f6f4e',
|
|
'grow-off': '#24577a',
|
|
'pool-16': '#a56b12',
|
|
}
|
|
labels = {
|
|
'fixed-strict': 'fixed CPU, strict cap',
|
|
'fixed-off': 'fixed CPU, cap off',
|
|
'grow-off': 'CPU grows with replicas',
|
|
'pool-16': 'pool 16',
|
|
}
|
|
for series, items in groups:
|
|
parts.append('<text x="%d" y="58" font-family="sans-serif" font-size="12">%s</text>' % (x, labels[series]))
|
|
for item in items:
|
|
rps = item['successful_rps'] or 0
|
|
bar_h = int(280 * rps / max_rps)
|
|
y = 340 - bar_h
|
|
parts.append('<rect x="%d" y="%d" width="%d" height="%d" fill="%s"/>' % (x, y, bar_w, bar_h, colors[series]))
|
|
parts.append('<text x="%d" y="%d" font-family="sans-serif" font-size="11">%s</text>' % (x, y - 4, round(rps, 1)))
|
|
parts.append('<text x="%d" y="360" font-family="sans-serif" font-size="11">x%d</text>' % (x, item['replicas']))
|
|
x += bar_w + gap
|
|
x += group_gap
|
|
parts.append('<text x="24" y="400" font-family="sans-serif" font-size="12">xN is the API replica count. Fixed series keeps 1.0 CPU and 1024 MiB in total.</text>')
|
|
parts.append('</svg>')
|
|
return '\n'.join(parts)
|
|
|
|
|
|
def restore():
|
|
stand.compose(
|
|
['up', '-d', '--no-deps', '--force-recreate', '--scale', 'api=2', 'api'],
|
|
extra_env={
|
|
'API_CPUS': '0.50',
|
|
'API_MEMORY': '512M',
|
|
'CAP_MODE': 'off',
|
|
'POOL_MAX': '4',
|
|
'API_REPLICAS': '2',
|
|
},
|
|
)
|
|
stand.wait_ready(timeout=120)
|
|
|
|
|
|
def main():
|
|
info = subprocess.run(['docker', 'info', '--format', '{{.NCPU}} {{.MemTotal}}'], text=True, capture_output=True)
|
|
stand.wait_ready()
|
|
client = Client(stand.BASE, timeout=10)
|
|
alice = client.user('track')
|
|
rows = []
|
|
for cfg in RUNS:
|
|
print('run %s x%s' % (cfg['series'], cfg['replicas']), flush=True)
|
|
deploy(cfg)
|
|
seen = stand.observe_instances(alice, cfg['replicas'], attempts=60)
|
|
output = ROOT / 'evidence' / ('load-%s-%s.json' % (cfg['series'], cfg['replicas']))
|
|
report, samples = run_load(output)
|
|
rows.append({
|
|
'series': cfg['series'],
|
|
'replicas': cfg['replicas'],
|
|
'cpus_each': cfg['cpus'],
|
|
'memory_each': cfg['memory'],
|
|
'cap': cfg['cap'],
|
|
'pool_max': cfg['pool'],
|
|
'instances_seen': len(seen),
|
|
'successful_rps': report.get('successful_rps'),
|
|
'failed_requests': report.get('failed_requests'),
|
|
'successful_requests': report.get('successful_requests'),
|
|
'latency_ms': report.get('successful_latency_ms'),
|
|
'cpu_api_mean': stand.mean_cpu(samples, '-api-'),
|
|
'cpu_postgres_mean': stand.mean_cpu(samples, '-postgres-'),
|
|
'cpu_lb_mean': stand.mean_cpu(samples, '-lb-'),
|
|
'load_exit': report.get('load_exit'),
|
|
})
|
|
evidence = {
|
|
'hypothesis': 'A global message-cap lock saturates before extra API replicas help. Removing it raises RPS until Postgres or the pool does.',
|
|
'profile': {
|
|
'tool': 'tests/load.py closed-loop POST messages',
|
|
'duration_seconds': DURATION,
|
|
'concurrency': CONCURRENCY,
|
|
'fixed_total': '1.0 CPU and 1024 MiB split across 1/2/4 replicas',
|
|
'grow': '0.50 CPU and 256 MiB per replica, count 1/2/4',
|
|
},
|
|
'host': {
|
|
'platform': platform.platform(),
|
|
'python': platform.python_version(),
|
|
'cpu_count': os_cpu(),
|
|
'docker_info': (info.stdout or '').strip(),
|
|
},
|
|
'runs': rows,
|
|
}
|
|
dest = ROOT / 'evidence' / 'track1.json'
|
|
dest.write_text(json.dumps(evidence, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
|
|
(ROOT / 'evidence' / 'track1.svg').write_text(svg(rows), encoding='utf-8')
|
|
restore()
|
|
print(json.dumps(rows, ensure_ascii=False, indent=2))
|
|
|
|
|
|
def os_cpu():
|
|
import os
|
|
return os.cpu_count()
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|