Lab3 - оценка 5

This commit is contained in:
2026-10-16 01:30:10 +03:00
parent 0ab3a341aa
commit da019afaa0
126 changed files with 11325 additions and 20 deletions
+59
View File
@@ -0,0 +1,59 @@
#!/usr/bin/env python3
import argparse
import json
import sys
import threading
import uuid
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / 'tests'))
from client import Client
def main():
p = argparse.ArgumentParser()
p.add_argument('--base-url', default='http://localhost:8080')
p.add_argument('--parallel', type=int, default=20)
a = p.parse_args()
c = Client(a.base_url)
alice, bob, _eve, chat = c.bootstrap()
path = '/api/v1/chats/' + chat['id'] + '/messages'
r = c.call('POST', path, 400, actor=alice, body={'text': 'без ключа'})
print('1) POST без Idempotency-Key ->', r['status'], r['json']['error']['code'])
key = 'demo-' + uuid.uuid4().hex[:8]
r1 = c.message(alice, chat, 'Привет', key=key)
r2 = c.message(alice, chat, 'Привет', key=key)
print('2) ключ %s: первый ответ %s id=%s (реплика %s)' % (key, r1['status'], r1['json']['id'], r1['headers']['X-Instance-Id']))
print(' повтор того же: %s id=%s (реплика %s) -> %s' % (
r2['status'], r2['json']['id'], r2['headers']['X-Instance-Id'],
'ТО ЖЕ сообщение' if r1['json'] == r2['json'] else 'ОШИБКА: другое'))
r = c.call('POST', path, 409, actor=alice, body={'text': 'Другой текст'}, headers={'Idempotency-Key': key})
print('3) тот же ключ, другое тело ->', r['status'], r['json']['error']['code'])
key = 'race-' + uuid.uuid4().hex[:8]
barrier = threading.Barrier(a.parallel)
def send(_):
local = Client(a.base_url)
barrier.wait()
x = local.message(alice, chat, 'Гонка', key=key)
return x['json']['id'], x['headers']['X-Instance-Id']
with ThreadPoolExecutor(a.parallel) as pool:
res = list(pool.map(send, range(a.parallel)))
ids = {i for i, _ in res}
inst = {s for _, s in res}
history = c.call('GET', path + '?limit=100', actor=bob, schema='MessagePage')['json']['items']
stored = [m for m in history if m['text'] == 'Гонка']
print('4) %d параллельных POST с ключом %s через реплики %s' % (a.parallel, key, sorted(inst)))
print(' разных id в ответах: %d; сообщений в истории: %d -> %s' % (
len(ids), len(stored), 'дублей нет' if len(ids) == 1 and len(stored) == 1 else 'ДУБЛЬ!'))
print('История чата:', json.dumps([m['text'] for m in history], ensure_ascii=False))
if __name__ == '__main__':
main()
+37
View File
@@ -0,0 +1,37 @@
#!/usr/bin/env python3
import argparse
import collections
import subprocess
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / 'tests'))
from client import Client
def containers():
out = subprocess.run(['docker', 'ps', '--filter', 'label=com.docker.compose.service=api',
'--format', '{{.ID}} {{.Names}}'], capture_output=True, text=True).stdout
return dict(line.split(' ', 1) for line in out.split('\n') if line.strip())
def main():
p = argparse.ArgumentParser()
p.add_argument('--base-url', default='http://localhost:8080')
p.add_argument('--n', type=int, default=10)
a = p.parse_args()
c = Client(a.base_url)
user = c.user('demo')
print('Пользователь %s вошёл ОДИН раз (токен не печатается).' % user['user']['username'])
names = containers()
seen = collections.Counter()
for i in range(1, a.n + 1):
r = c.call('GET', '/api/v1/users/me', actor=user, schema='User')
iid = r['headers']['X-Instance-Id']
seen[iid] += 1
print('запрос %2d -> 200, X-Instance-Id=%s (контейнер %s)' % (i, iid, names.get(iid, '?')))
print('Итого: %d разных реплик обслужили одну сессию: %s' % (len(seen), dict(seen)))
if __name__ == '__main__':
main()
+84
View File
@@ -0,0 +1,84 @@
#!/usr/bin/env python3
import argparse
import json
import threading
import time
from pathlib import Path
from lab3lib import WriteLoad, api_containers, ps_snapshot, sh, wait_healthy
def main():
p = argparse.ArgumentParser()
p.add_argument('--base-url', default='http://localhost:8080')
p.add_argument('--mode', choices=['stop', 'kill'], default='stop')
p.add_argument('--workers', type=int, default=8)
p.add_argument('--observe', type=float, default=12.0, help='seconds after the failure')
p.add_argument('--output', default=None)
a = p.parse_args()
replicas = [r for r in api_containers() if r['state'] == 'running']
assert len(replicas) >= 2, 'need >=2 running api replicas'
load = WriteLoad(a.base_url, workers=a.workers)
load.start()
time.sleep(5)
rounds = []
for r in replicas:
cid = r['id']
base = (time.monotonic() - 5, time.monotonic())
before = ps_snapshot()
t_fail = time.monotonic()
done = {}
def act():
sh('docker', a.mode, cid)
done['t'] = time.monotonic()
th = threading.Thread(target=act)
th.start()
time.sleep(a.observe)
th.join()
during = ps_snapshot()
t_restore = time.monotonic()
sh('docker', 'start', cid)
healthy = wait_healthy(cid, 60)
t_healthy = time.monotonic()
t_back = None
while time.monotonic() - t_healthy < 15:
if any(e[1] and e[2] == cid and e[0] > t_healthy for e in list(load.events)):
t_back = time.monotonic()
break
time.sleep(0.1)
time.sleep(3)
ev = [e for e in list(load.events) if t_fail <= e[0] < t_restore]
errs = [e for e in ev if not e[1]]
served_target = [e for e in ev if e[1] and e[2] == cid]
rounds.append({
'replica_name': r['name'], 'instance_id': cid, 'action': 'docker ' + a.mode,
'action_duration_s': round(done['t'] - t_fail, 2),
'baseline_5s': load.window(*base),
'after_failure': load.window(t_fail, t_restore),
'first_1s_after_failure': load.window(t_fail, t_fail + 1),
'last_error_after_failure_s': round(max(e[0] for e in errs) - t_fail, 2) if errs else None,
'target_last_served_after_failure_s': round(max(e[0] + e[3] for e in served_target) - t_fail, 2) if served_target else None,
'restored_healthy_after_s': round(t_healthy - t_restore, 2) if healthy else None,
'restored_back_in_rotation_after_s': round(t_back - t_restore, 2) if t_back else None,
'errors_sample': sorted({e[2] for e in errs})[:3],
'docker_ps_before': before.splitlines(), 'docker_ps_during': during.splitlines(),
})
print(json.dumps({k: v for k, v in rounds[-1].items() if not k.startswith('docker_ps')}, ensure_ascii=False))
load.stop()
result = {'mode': a.mode, 'workers': a.workers, 'client_timeout_s': load.timeout,
'total': load.window(load.t0, time.monotonic()), 'client_retries': load.retries,
'rounds': rounds, 'data_check': load.verify_history(),
'docker_ps_end': ps_snapshot().splitlines()}
print(json.dumps(result['data_check']))
ok = result['data_check']['lost_confirmed'] == 0 and result['data_check']['duplicate_texts'] == 0
print('PASS' if ok else 'FAIL', 'data integrity across', len(rounds), 'failures')
if a.output:
Path(a.output).write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
raise SystemExit(0 if ok else 1)
if __name__ == '__main__':
main()
+39
View File
@@ -0,0 +1,39 @@
#!/usr/bin/env python3
import secrets
import shutil
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
SECRETS = ROOT / 'secrets'
def write(name, value):
path = SECRETS / name
if path.exists():
print('keep secrets/' + name)
return path.read_text().strip()
path.write_text(value + '\n', newline='\n')
print('created secrets/' + name)
return value
def main():
SECRETS.mkdir(exist_ok=True)
pg = write('pg_password', secrets.token_urlsafe(24))
write('database_url', 'postgres://messenger:%s@postgres:5432/messenger?sslmode=disable' % pg)
vk_conf = SECRETS / 'valkey_auth.conf'
if vk_conf.exists():
vk = vk_conf.read_text().split()[-1]
print('keep secrets/valkey_auth.conf')
else:
vk = secrets.token_urlsafe(24)
write('valkey_auth.conf', 'requirepass ' + vk)
write('cache_url', 'redis://:%s@valkey:6379/0' % vk)
env = ROOT / '.env'
if not env.exists():
shutil.copy(ROOT / '.env.example', env)
print('created .env from .env.example')
if __name__ == '__main__':
main()
+130
View File
@@ -0,0 +1,130 @@
import json
import subprocess
import sys
import threading
import time
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, Failure
PROJECT = 'mtusi-lab3'
def sh(*args, check=True):
r = subprocess.run(list(args), cwd=ROOT, capture_output=True, text=True, encoding='utf-8')
if check and r.returncode != 0:
raise RuntimeError('%s failed: %s' % (' '.join(args[:3]), r.stderr.strip()[:300]))
return r.stdout.strip()
def api_containers(all_states=False):
out = sh('docker', 'ps', *(['-a'] if all_states else []), '--no-trunc',
'--filter', 'label=com.docker.compose.project=' + PROJECT,
'--filter', 'label=com.docker.compose.service=api',
'--format', '{{json .}}')
rows = []
for line in out.splitlines():
d = json.loads(line)
rows.append({'id': d['ID'][:12], 'name': d['Names'], 'state': d['State'], 'status': d['Status']})
return sorted(rows, key=lambda r: r['name'])
def health(cid):
return sh('docker', 'inspect', '-f', '{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}', cid)
def wait_healthy(cid, timeout=60):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
if health(cid) == 'healthy':
return True
time.sleep(0.25)
return False
def ps_snapshot():
return sh('docker', 'compose', 'ps', '-a', '--format', '{{.Name}}\t{{.State}}\t{{.Status}}')
class WriteLoad:
def __init__(self, base_url, workers=8, timeout=2.0, pause=0.0):
self.base = base_url
self.workers = workers
self.timeout = timeout
self.pause = pause
self.events = []
self.confirmed = []
self.retries = 0
self._lock = threading.Lock()
self._stop = threading.Event()
self._threads = []
c = Client(base_url, timeout=10)
self.alice, self.bob, _eve, self.chat = c.bootstrap()
self.reader = c
def _worker(self, wid):
c = Client(self.base, timeout=self.timeout)
key = text = None
n = 0
while not self._stop.is_set():
if key is None:
key = uuid.uuid4().hex
text = 'load-%d-%d-%s' % (wid, n, key[:8])
start = time.monotonic()
try:
r = c.message(self.alice, self.chat, text, key=key)
with self._lock:
self.events.append((start, True, r['headers']['X-Instance-Id'], time.monotonic() - start))
self.confirmed.append(r['json'])
key = None
n += 1
except Failure as exc:
with self._lock:
self.events.append((start, False, str(exc)[-60:], time.monotonic() - start))
self.retries += 1
time.sleep(0.05)
if self.pause:
time.sleep(self.pause)
def start(self):
for i in range(self.workers):
t = threading.Thread(target=self._worker, args=(i,), daemon=True)
t.start()
self._threads.append(t)
self.t0 = time.monotonic()
def stop(self):
self._stop.set()
for t in self._threads:
t.join(timeout=15)
def window(self, a, b):
ev = [e for e in self.events if a <= e[0] < b]
ok = [e for e in ev if e[1]]
lat = sorted(e[3] for e in ok)
pct = lambda p: round(1000 * lat[min(len(lat) - 1, int(p * len(lat)))], 1) if lat else None
return {'seconds': round(b - a, 2), 'ok': len(ok), 'errors': len(ev) - len(ok),
'ok_rps': round(len(ok) / (b - a), 1) if b > a else None,
'p50_ms': pct(.5), 'p95_ms': pct(.95), 'p99_ms': pct(.99)}
def verify_history(self):
items, cursor = [], None
path = '/api/v1/chats/' + self.chat['id'] + '/messages?limit=100'
while True:
page = self.reader.call('GET', path + ('&cursor=' + cursor if cursor else ''),
actor=self.bob, schema='MessagePage')['json']
items += page['items']
cursor = page['next_cursor']
if not cursor:
break
by_id = {m['id']: m for m in items}
texts = [m['text'] for m in items]
lost = [m for m in self.confirmed if by_id.get(m['id']) != m]
return {'stored_messages': len(items), 'confirmed_201': len(self.confirmed),
'lost_confirmed': len(lost), 'duplicate_ids': len(items) - len(by_id),
'duplicate_texts': len(texts) - len(set(texts)),
'unique_confirmed': len({m['id'] for m in self.confirmed})}
+5
View File
@@ -0,0 +1,5 @@
@echo off
cd /d "%~dp0.."
docker compose stop lb api || exit /b 1
docker compose restart postgres valkey || exit /b 1
docker compose start api lb || exit /b 1
+6
View File
@@ -0,0 +1,6 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
docker compose stop lb api
docker compose restart postgres valkey
docker compose start api lb
+87
View File
@@ -0,0 +1,87 @@
#!/usr/bin/env python3
import argparse
import json
import os
import time
from pathlib import Path
from lab3lib import WriteLoad, api_containers, ps_snapshot, sh, wait_healthy
def image_label(cid):
return sh('docker', 'inspect', '-f', '{{index .Config.Labels "org.opencontainers.image.revision"}}', cid)
def main():
p = argparse.ArgumentParser()
p.add_argument('--base-url', default='http://localhost:8080')
p.add_argument('--build-label', default=time.strftime('rollout-%Y%m%dT%H%M%S'))
p.add_argument('--workers', type=int, default=8)
p.add_argument('--output', default=None)
a = p.parse_args()
old = [r for r in api_containers() if r['state'] == 'running']
n = len(old)
assert n >= 2, 'need >=2 running replicas'
log = []
say = lambda *x: (print(*x), log.append(' '.join(map(str, x))))
say('old replicas:', [(r['name'], r['id'], image_label(r['id'])) for r in old])
load = WriteLoad(a.base_url, workers=a.workers)
load.start()
time.sleep(5)
t_begin = time.monotonic()
env = dict(os.environ, APP_BUILD=a.build_label)
t = time.monotonic()
import subprocess
subprocess.run(['docker', 'compose', 'build', '-q', 'migrate'], check=True, env=env,
cwd=Path(__file__).resolve().parents[1])
say('built image with label', a.build_label, 'in %.1fs' % (time.monotonic() - t))
sh('docker', 'compose', 'run', '--rm', '--no-deps', 'migrate')
say('migrations applied once (advisory lock, idempotent)')
for r in old:
before = {x['id'] for x in api_containers()}
sh('docker', 'compose', 'up', '-d', '--no-deps', '--no-recreate', '--scale', 'api=%d' % (n + 1), 'api')
new = [x for x in api_containers() if x['id'] not in before]
assert len(new) == 1, 'expected exactly one new replica, got %s' % new
cid = new[0]['id']
assert wait_healthy(cid, 60), 'new replica not healthy'
t_h = time.monotonic()
while not any(e[1] and e[2] == cid and e[0] > t_h for e in list(load.events)):
assert time.monotonic() - t_h < 15, 'new replica not in LB rotation'
time.sleep(0.1)
say('new %s (%s) healthy and serving; label=%s' % (new[0]['name'], cid, image_label(cid)))
t_s = time.monotonic()
sh('docker', 'stop', '-t', '15', r['id'])
sh('docker', 'rm', r['id'])
say('old %s (%s) drained+removed in %.1fs' % (r['name'], r['id'], time.monotonic() - t_s))
t_end = time.monotonic()
time.sleep(5)
load.stop()
now = api_containers()
say('new replicas:', [(x['name'], x['id'], image_label(x['id'])) for x in now])
result = {
'build_label': a.build_label, 'replicas': n, 'workers': a.workers,
'before_rollout_5s': load.window(t_begin - 5, t_begin),
'during_rollout': load.window(t_begin, t_end),
'after_rollout_5s': load.window(t_end, t_end + 5),
'client_retries': load.retries,
'error_samples': sorted({e[2] for e in load.events if not e[1]})[:5],
'all_new_label': all(image_label(x['id']) == a.build_label for x in now),
'data_check': load.verify_history(), 'log': log, 'docker_ps_end': ps_snapshot().splitlines(),
}
print(json.dumps({k: result[k] for k in ('before_rollout_5s', 'during_rollout', 'after_rollout_5s',
'client_retries', 'all_new_label', 'data_check')}, indent=1))
ok = result['all_new_label'] and result['data_check']['lost_confirmed'] == 0 \
and result['data_check']['duplicate_texts'] == 0 and len(now) == n
print('PASS' if ok else 'FAIL', 'rolling update')
if a.output:
Path(a.output).write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
raise SystemExit(0 if ok else 1)
if __name__ == '__main__':
main()
+10
View File
@@ -0,0 +1,10 @@
@echo off
setlocal
cd /d "%~dp0.."
if "%TARGET_INSTANCE_ID%"=="" exit /b 2
echo %TARGET_INSTANCE_ID%| findstr /r /x "[0-9a-f][0-9a-f]*" >nul || exit /b 2
set CID=
for /f %%i in ('docker ps -q --filter "id=%TARGET_INSTANCE_ID%" --filter "label=com.docker.compose.project=mtusi-lab3" --filter "label=com.docker.compose.service=api"') do set CID=%%i
if "%CID%"=="" exit /b 3
docker stop -t 15 %CID% >nul || exit /b 1
echo stopped api container %CID%
+14
View File
@@ -0,0 +1,14 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
case "$TARGET_INSTANCE_ID" in
*[!0-9a-f]*) echo "unexpected instance id format" >&2; exit 2 ;;
esac
cid=$(docker ps -q --filter "id=$TARGET_INSTANCE_ID" \
--filter "label=com.docker.compose.project=mtusi-lab3" \
--filter "label=com.docker.compose.service=api")
[ -n "$cid" ] || { echo "no running api replica matches" >&2; exit 3; }
[ "$(printf '%s\n' "$cid" | wc -l)" -eq 1 ] || { echo "ambiguous id" >&2; exit 3; }
docker stop -t 15 "$cid" >/dev/null
echo "stopped api container $cid"
+190
View File
@@ -0,0 +1,190 @@
#!/usr/bin/env python3
import json
import statistics as st
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
OUT = ROOT / 'evidence' / 'track1'
RAW = OUT / 'raw'
ORDER = ['f1x2.0', 'f2x1.0', 'f4x0.5', 'g1', 'g2', 'g4', 'g8']
def load():
runs = [json.loads(p.read_text(encoding='utf-8')) for p in sorted(RAW.glob('*.json'))
if not p.name.endswith('.k6.json')]
groups = {}
for r in runs:
groups.setdefault(r['config'], []).append(r)
return groups
def summarize(runs):
def agg(vals):
return {'mean': round(st.mean(vals), 1), 'min': round(min(vals), 1), 'max': round(max(vals), 1)}
first = runs[0]
svc = lambda name, key: [r['docker_stats'].get(name, {}).get(key, 0) for r in runs]
return {
'replicas': first['replicas'], 'cpus_per_replica': first['cpus_per_replica'],
'mem_per_replica': first['mem_per_replica'], 'db_pool_per_replica': first['db_pool_per_replica'],
'extra_env': first.get('extra_env', {}), 'repeats': len(runs), 'vus': first['vus'],
'duration': first['duration'],
'rps': agg([r['rps'] for r in runs]),
'p50_ms': agg([r['latency_ms']['p(50)'] for r in runs]),
'p95_ms': agg([r['latency_ms']['p(95)'] for r in runs]),
'p99_ms': agg([r['latency_ms']['p(99)'] for r in runs]),
'error_ratio_max': max(r['error_ratio'] for r in runs),
'cpu_pct': {s: round(st.mean(svc(s, 'cpu_pct_mean')), 1) for s in ('api', 'postgres', 'lb', 'valkey')},
'api_cpu_max_one_replica_pct': round(max(svc('api', 'cpu_pct_max_one_container')), 1),
'mem_mib': {s: round(st.mean(svc(s, 'mem_mib_mean')), 1) for s in ('api', 'postgres', 'lb', 'valkey')},
'pg_active_backends': round(st.mean(r['postgres']['active_backends_mean'] for r in runs), 1),
'pg_top_waits': top_waits(runs),
}
def top_waits(runs):
acc = {}
for r in runs:
for k, v in r['postgres']['wait_events_mean'].items():
acc[k] = acc.get(k, 0) + v / len(runs)
return {k: round(v, 2) for k, v in sorted(acc.items(), key=lambda x: -x[1])[:4]}
FONT = 'font-family="system-ui,Segoe UI,Arial" font-size="12"'
C1, C2, C3, C4 = '#2563eb', '#dc2626', '#16a34a', '#9333ea'
def svg_wrap(w, h, body, title):
return ('<svg xmlns="http://www.w3.org/2000/svg" width="%d" height="%d" viewBox="0 0 %d %d" %s>'
'<rect width="100%%" height="100%%" fill="#fff"/>'
'<text x="%d" y="20" text-anchor="middle" font-size="14" font-weight="600">%s</text>%s</svg>\n'
% (w, h, w, h, FONT, w // 2, title, body))
def axis(x0, y0, x1, y1, ymax, ylabel, ticks=5, right=False, color='#333'):
b = ''
xa = x1 if right else x0
for i in range(ticks + 1):
v = ymax * i / ticks
y = y1 - (y1 - y0) * i / ticks
if not right:
b += '<line x1="%d" y1="%.1f" x2="%d" y2="%.1f" stroke="#e5e7eb"/>' % (x0, y, x1, y)
b += '<text x="%d" y="%.1f" text-anchor="%s" fill="%s">%g</text>' % (
xa + (6 if right else -6), y + 4, 'start' if right else 'end', color, round(v, 1))
b += '<text transform="translate(%d,%d) rotate(-90)" text-anchor="middle" fill="%s">%s</text>' % (
xa + (48 if right else -48), (y0 + y1) // 2, color, ylabel)
return b
def nice(v):
for e in range(0, 7):
for m in (1, 1.2, 1.5, 2, 2.5, 3, 4, 5, 6, 8):
c = m * 10 ** e
if c >= v:
return c
return v
def bar_chart(names, series, title, ylabel, path):
w, h, x0, y0, x1, y1 = 640, 380, 70, 40, 610, 300
ymax = nice(max(v[2] for _, _, vals in series for v in vals) * 1.1)
b = axis(x0, y0, x1, y1, ymax, ylabel)
gw = (x1 - x0) / len(names)
bw = gw * 0.7 / len(series)
for i, n in enumerate(names):
b += '<text x="%.1f" y="%d" text-anchor="middle">%s</text>' % (x0 + gw * (i + .5), y1 + 18, n)
for j, (lab, col, vals) in enumerate(series):
mean, lo, hi = vals[i]
x = x0 + gw * i + gw * 0.15 + bw * j
y = y1 - (y1 - y0) * mean / ymax
b += '<rect x="%.1f" y="%.1f" width="%.1f" height="%.1f" fill="%s"/>' % (x, y, bw - 2, y1 - y, col)
ylo, yhi = (y1 - (y1 - y0) * v / ymax for v in (lo, hi))
cx = x + (bw - 2) / 2
b += '<line x1="%.1f" y1="%.1f" x2="%.1f" y2="%.1f" stroke="#111"/>' % (cx, ylo, cx, yhi)
b += '<text x="%.1f" y="%.1f" text-anchor="middle" font-size="11">%g</text>' % (cx, y - 6 if yhi > y - 4 else yhi - 4, round(mean))
lx = x0
for lab, col, _ in series:
b += '<rect x="%d" y="%d" width="12" height="12" fill="%s"/><text x="%d" y="%d">%s</text>' % (lx, y1 + 32, col, lx + 16, y1 + 42, lab)
lx += 20 + 8 * len(lab)
b += '<text x="%d" y="%d" fill="#666" font-size="11">столбец = среднее, отрезок = min..max по повторам</text>' % (x0, h - 8)
path.write_text(svg_wrap(w, h, b, title), encoding='utf-8')
def line_chart(xs, left, right, title, xlabel, ylabel_l, ylabel_r, path, rmax=None):
w, h, x0, y0, x1, y1 = 680, 380, 80, 40, 600, 300
lmax = nice(max(v for _, _, vals, _ in left for v in vals) * 1.1)
rmax = rmax or nice(max(v for _, _, vals, _ in right for v in vals) * 1.1)
b = axis(x0, y0, x1, y1, lmax, ylabel_l) + axis(x0, y0, x1, y1, rmax, ylabel_r, right=True, color='#555')
px = lambda i: x0 + (x1 - x0) * i / (len(xs) - 1)
for i, x in enumerate(xs):
b += '<text x="%.1f" y="%d" text-anchor="middle">%s</text>' % (px(i), y1 + 18, x)
b += '<text x="%d" y="%d" text-anchor="middle">%s</text>' % ((x0 + x1) // 2, y1 + 36, xlabel)
for group, ymax in ((left, lmax), (right, rmax)):
for lab, col, vals, dashed in group:
pts = ' '.join('%.1f,%.1f' % (px(i), y1 - (y1 - y0) * v / ymax) for i, v in enumerate(vals))
b += '<polyline points="%s" fill="none" stroke="%s" stroke-width="2.5"%s/>' % (
pts, col, ' stroke-dasharray="6 4"' if dashed else '')
for i, v in enumerate(vals):
b += '<circle cx="%.1f" cy="%.1f" r="3.5" fill="%s"/>' % (px(i), y1 - (y1 - y0) * v / ymax, col)
lx = x0
for lab, col, _, dashed in left + right:
b += '<line x1="%d" y1="%d" x2="%d" y2="%d" stroke="%s" stroke-width="2.5"%s/><text x="%d" y="%d">%s</text>' % (
lx, y1 + 56, lx + 18, y1 + 56, col, ' stroke-dasharray="6 4"' if dashed else '', lx + 22, y1 + 60, lab)
lx += 34 + 7 * len(lab)
path.write_text(svg_wrap(w, h, b, title), encoding='utf-8')
def main():
groups = load()
res = {k: summarize(v) for k, v in groups.items()}
keys = [k for k in ORDER if k in res] + sorted(k for k in res if k not in ORDER)
(OUT / 'results.json').write_text(json.dumps({k: res[k] for k in keys}, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
lines = ['| Конфигурация | Реплики × CPU / RAM, пул | RPS mean (min–max) | p50 / p95 / p99, мс | ошибки | CPU% api / pg / lb | PG active, топ ожиданий |',
'| --- | --- | --- | --- | --- | --- | --- |']
for k in keys:
r = res[k]
lines.append('| %s | %d × %s / %s, %d | %g (%g–%g) | %g / %g / %g | %g | %g / %g / %g | %g; %s |' % (
k, r['replicas'], r['cpus_per_replica'], r['mem_per_replica'], r['db_pool_per_replica'],
r['rps']['mean'], r['rps']['min'], r['rps']['max'], r['p50_ms']['mean'], r['p95_ms']['mean'],
r['p99_ms']['mean'], r['error_ratio_max'], r['cpu_pct']['api'], r['cpu_pct']['postgres'],
r['cpu_pct']['lb'], r['pg_active_backends'],
', '.join('%s %g' % kv for kv in list(r['pg_top_waits'].items())[:2])))
(OUT / 'summary.md').write_text('\n'.join(lines) + '\n', encoding='utf-8')
print('\n'.join(lines))
fixed = [k for k in ('f1x2.0', 'f2x1.0', 'f4x0.5') if k in res]
if fixed:
g = lambda key: [(res[k][key]['mean'], res[k][key]['min'], res[k][key]['max']) for k in fixed]
bar_chart(['1 × 2.0 CPU', '2 × 1.0 CPU', '4 × 0.5 CPU'][:len(fixed)], [('RPS', C1, g('rps'))],
'Фиксированный бюджет API (2 CPU, 512 MiB, 20 соединений): RPS', 'успешные запросы/с', OUT / 'fixed-rps.svg')
bar_chart(['1 × 2.0 CPU', '2 × 1.0 CPU', '4 × 0.5 CPU'][:len(fixed)],
[('p50', C3, g('p50_ms')), ('p95', C1, g('p95_ms')), ('p99', C2, g('p99_ms'))],
'Фиксированный бюджет API: задержка', 'мс', OUT / 'fixed-latency.svg')
growth = [k for k in ('g1', 'g2', 'g4', 'g8') if k in res]
if len(growth) >= 2:
xs = [res[k]['replicas'] for k in growth]
line_chart(xs, [('RPS', C1, [res[k]['rps']['mean'] for k in growth], False)],
[('CPU API (сумма)', C3, [res[k]['cpu_pct']['api'] for k in growth], True),
('CPU PostgreSQL', C2, [res[k]['cpu_pct']['postgres'] for k in growth], True),
('CPU HAProxy', C4, [res[k]['cpu_pct']['lb'] for k in growth], True)],
'Рост числа реплик (по 1 CPU), PostgreSQL 2 CPU', 'API-реплик',
'успешные запросы/с', 'CPU, % ядра', OUT / 'growth.svg')
line_chart(xs, [('p95, мс', C1, [res[k]['p95_ms']['mean'] for k in growth], False),
('p99, мс', C2, [res[k]['p99_ms']['mean'] for k in growth], False)],
[('активных backend PG', C3, [res[k]['pg_active_backends'] for k in growth], True)],
'Рост числа реплик: задержка и очередь в PostgreSQL', 'API-реплик', 'мс',
'активные сессии PG', OUT / 'growth-latency.svg')
ab = [('g2-tx', 'g2-oneshot'), ('g4-tx', 'g4-oneshot')]
if all(k in res for pair in ab for k in pair):
g = lambda keys, m: [(res[k][m]['mean'], res[k][m]['min'], res[k][m]['max']) for k in keys]
bar_chart(['2 реплики', '4 реплики'], [('tx: 5 round trip', C2, g([a for a, _ in ab], 'rps')),
('oneshot: 1 запрос', C3, g([b for _, b in ab], 'rps'))],
'Улучшение: запись сообщения одним SQL-оператором', 'успешные запросы/с', OUT / 'improvement-rps.svg')
bar_chart(['2 реплики', '4 реплики'], [('tx p95', C2, g([a for a, _ in ab], 'p95_ms')),
('oneshot p95', C3, g([b for _, b in ab], 'p95_ms'))],
'Улучшение: p95 задержки', 'мс', OUT / 'improvement-p95.svg')
if __name__ == '__main__':
main()
+194
View File
@@ -0,0 +1,194 @@
#!/usr/bin/env python3
import argparse
import json
import os
import re
import subprocess
import threading
import time
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
RAW = ROOT / 'evidence' / 'track1' / 'raw'
PROJECT = 'mtusi-lab3'
SERIES = {
'fixed': {'f1x2.0': (1, '2.0', '512M', 20), 'f2x1.0': (2, '1.0', '256M', 10), 'f4x0.5': (4, '0.5', '128M', 5)},
'growth': {'g1': (1, '1.0', '256M', 10), 'g2': (2, '1.0', '256M', 10),
'g4': (4, '1.0', '256M', 10), 'g8': (8, '1.0', '256M', 10)},
}
def sh(args, env=None, check=True):
r = subprocess.run(args, cwd=ROOT, capture_output=True, text=True, encoding='utf-8', env=env)
if check and r.returncode != 0:
raise RuntimeError(' '.join(args[:4]) + ': ' + r.stderr[-400:])
return r.stdout
def compose_env(cfg, extra):
n, cpus, mem, pool = cfg
env = dict(os.environ, API_REPLICAS=str(n), API_CPUS=cpus, API_MEMORY=mem, DB_MAX_CONNS=str(pool))
env.update(extra)
return env
def apply(cfg, extra):
env = compose_env(cfg, extra)
sh(['docker', 'compose', 'up', '-d', '--wait', '--force-recreate', '--no-deps', 'api'], env=env)
sh(['docker', 'compose', 'up', '-d', '--wait', '--no-deps', 'lb'], env=env)
deadline = time.monotonic() + 60
while time.monotonic() < deadline:
seen = set()
for _ in range(4 * cfg[0] + 4):
with urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=2) as r:
seen.add(r.headers['X-Instance-Id'])
if len(seen) == cfg[0]:
return sorted(seen)
time.sleep(1)
raise RuntimeError('LB does not see %d replicas' % cfg[0])
def parse_mem(s):
m = re.match(r'([\d.]+)\s*([KMG]i?B|B)', s.strip())
if not m:
return None
k = {'B': 1 / 2**20, 'KiB': 1 / 1024, 'KB': 1 / 1024, 'MiB': 1, 'MB': 1, 'GiB': 1024, 'GB': 1024}[m.group(2)]
return float(m.group(1)) * k
class Sampler(threading.Thread):
def __init__(self):
super().__init__(daemon=True)
self.stop = threading.Event()
self.stats = []
self.pg = []
def run(self):
while not self.stop.is_set():
out = sh(['docker', 'stats', '--no-stream', '--format', '{{json .}}'], check=False)
snap = {}
for line in out.splitlines():
try:
d = json.loads(line)
except ValueError:
continue
m = re.match(PROJECT + r'-(\w+?)-\d+$', d['Name'])
if not m:
continue
cpu = float(d['CPUPerc'].rstrip('%') or 0)
s = snap.setdefault(m.group(1), {'cpu': 0.0, 'mem_mib': 0.0, 'max_cpu': 0.0, 'n': 0})
s['cpu'] += cpu
s['max_cpu'] = max(s['max_cpu'], cpu)
s['mem_mib'] += parse_mem(d['MemUsage'].split('/')[0]) or 0
s['n'] += 1
if snap:
self.stats.append(snap)
q = ("SELECT coalesce(wait_event_type,'CPU')||':'||coalesce(wait_event,'-'), count(*) "
"FROM pg_stat_activity WHERE state='active' AND backend_type='client backend' "
"AND pid<>pg_backend_pid() GROUP BY 1")
out = sh(['docker', 'compose', 'exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger',
'-At', '-F', '|', '-c', q], check=False)
waits = {}
for line in out.splitlines():
if '|' in line:
k, v = line.rsplit('|', 1)
waits[k] = int(v)
self.pg.append({'active': sum(waits.values()), 'waits': waits})
K6_CPUS = '4'
def k6(name, vus, duration, run_id, summary=None):
args = ['docker', 'run', '--rm', '--network', PROJECT + '_app', '--cpus', K6_CPUS,
'-v', str(ROOT / 'infra' / 'k6') + ':/scripts:ro',
'-e', 'VUS=%d' % vus, '-e', 'DURATION=' + duration, '-e', 'RUN_ID=' + run_id]
if summary:
args += ['-v', str(RAW) + ':/out']
args += ['grafana/k6:0.54.0', 'run', '--quiet']
if summary:
args += ['--summary-export', '/out/' + summary]
args += ['/scripts/track1.js']
env = dict(os.environ, MSYS_NO_PATHCONV='1')
sh(args, env=env)
def aggregate(sampler):
svc = {}
for snap in sampler.stats:
for k, v in snap.items():
svc.setdefault(k, []).append(v)
out = {}
for k, vals in svc.items():
out[k] = {'cpu_pct_mean': round(sum(v['cpu'] for v in vals) / len(vals), 1),
'cpu_pct_max_one_container': round(max(v['max_cpu'] for v in vals), 1),
'mem_mib_mean': round(sum(v['mem_mib'] for v in vals) / len(vals), 1),
'containers': vals[-1]['n']}
waits = {}
for s in sampler.pg:
for k, v in s['waits'].items():
waits[k] = waits.get(k, 0) + v
n = max(1, len(sampler.pg))
return out, {'samples': len(sampler.pg),
'active_backends_mean': round(sum(s['active'] for s in sampler.pg) / n, 1),
'wait_events_mean': {k: round(v / n, 2) for k, v in sorted(waits.items(), key=lambda x: -x[1])}}
def main():
p = argparse.ArgumentParser()
p.add_argument('--series', choices=list(SERIES), required=True)
p.add_argument('--only', nargs='*', default=None, help='subset of config names')
p.add_argument('--repeat', type=int, default=3)
p.add_argument('--vus', type=int, default=128)
p.add_argument('--warmup', default='10s')
p.add_argument('--duration', default='30s')
p.add_argument('--tag', default='', help='suffix for an experiment variant, e.g. "-v2"')
p.add_argument('--env', nargs='*', default=[], help='extra compose env KEY=VALUE')
p.add_argument('--start-repeat', type=int, default=1, help='number of the first repeat (to interleave variants)')
p.add_argument('--k6-cpus', default='4')
a = p.parse_args()
global K6_CPUS
K6_CPUS = a.k6_cpus
RAW.mkdir(parents=True, exist_ok=True)
extra = dict(kv.split('=', 1) for kv in a.env)
cfgs = {k: v for k, v in SERIES[a.series].items() if not a.only or k in a.only}
for rep in range(a.start_repeat, a.start_repeat + a.repeat):
for name, cfg in cfgs.items():
label = '%s%s-r%d' % (name, a.tag, rep)
print('==', label, cfg, flush=True)
replicas = apply(cfg, extra)
k6(name, a.vus, a.warmup, 'w%s%d' % (name.replace('.', ''), int(time.time())))
sampler = Sampler()
sampler.start()
t0 = time.time()
run_id = 'm%s%d' % (name.replace('.', ''), int(t0))
k6(name, a.vus, a.duration, run_id, summary=label + '.k6.json')
sampler.stop.set()
sampler.join(timeout=20)
stats, pg = aggregate(sampler)
summary_path = RAW / (label + '.k6.json')
k6sum = json.loads(summary_path.read_text(encoding='utf-8'))
k6sum.pop('setup_data', None)
summary_path.write_text(json.dumps(k6sum, indent=2) + '\n', encoding='utf-8')
k = k6sum['metrics']
dur = k['http_req_duration']
rec = {'label': label, 'config': name + a.tag, 'series': a.series, 'repeat': rep,
'replicas': cfg[0], 'cpus_per_replica': cfg[1], 'mem_per_replica': cfg[2],
'db_pool_per_replica': cfg[3], 'extra_env': extra, 'k6_cpus': K6_CPUS, 'vus': a.vus, 'duration': a.duration,
'started_unix': int(t0), 'instances': replicas,
'rps': round(k['http_reqs']['rate'], 1),
'error_ratio': round(k['http_req_failed']['value'], 6),
'latency_ms': {q: round(dur[q], 2) for q in ('p(50)', 'p(95)', 'p(99)', 'max')},
'docker_stats': stats, 'postgres': pg}
(RAW / (label + '.json')).write_text(json.dumps(rec, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
print(' rps=%s err=%s p95=%s api_cpu=%s pg_cpu=%s lb_cpu=%s pg_active=%s' % (
rec['rps'], rec['error_ratio'], rec['latency_ms']['p(95)'],
stats.get('api', {}).get('cpu_pct_mean'), stats.get('postgres', {}).get('cpu_pct_mean'),
stats.get('lb', {}).get('cpu_pct_mean'), pg['active_backends_mean']), flush=True)
apply((2, '1.0', '256M', 10), {})
if __name__ == '__main__':
main()