Поставить несколько реплик API за общий балансировщик.

Сессия и ключ идемпотентности общие для реплик, миграция выполняется один раз, остановка одной реплики не теряет подтверждённые сообщения.
This commit is contained in:
2026-10-30 01:15:28 +03:00
parent 0ab3a341aa
commit 59f8c55f93
45 changed files with 3367 additions and 36 deletions
+138
View File
@@ -0,0 +1,138 @@
"""Helpers for the local compose stand. No tokens are printed or stored."""
import json
import os
import subprocess
import time
import urllib.error
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
BASE = 'http://127.0.0.1:8080'
def compose(args, extra_env=None, check=True):
env = os.environ.copy()
if extra_env:
env.update({key: str(value) for key, value in extra_env.items()})
command = ['docker', 'compose', '--env-file', str(ROOT / '.env'), *args]
result = subprocess.run(command, cwd=ROOT, env=env, text=True, capture_output=True)
if check and result.returncode != 0:
raise SystemExit((result.stderr or result.stdout or 'compose failed').strip())
return result
def inspect(cid, template):
result = subprocess.run(
['docker', 'inspect', '-f', template, cid],
text=True,
capture_output=True,
check=True,
)
return result.stdout.strip()
def api_containers(running_only=True):
args = ['ps', '-q', 'api'] if running_only else ['ps', '-aq', 'api']
result = compose(args)
found = []
for line in result.stdout.splitlines():
cid = line.strip()
if not cid:
continue
hostname = inspect(cid, '{{.Config.Hostname}}')
name = inspect(cid, '{{.Name}}').lstrip('/')
found.append({'id': cid, 'hostname': hostname, 'name': name})
return found
def wait_ready(timeout=90):
deadline = time.monotonic() + timeout
last = 'none'
while time.monotonic() < deadline:
try:
with urllib.request.urlopen(BASE + '/health/ready', timeout=2) as response:
if response.status == 200 and response.headers.get('X-Instance-Id'):
return response.headers.get('X-Instance-Id')
except (urllib.error.URLError, TimeoutError, OSError) as exc:
last = type(exc).__name__
time.sleep(0.4)
raise SystemExit('load balancer did not become ready (%s)' % last)
def observe_instances(actor, expect, attempts=40):
import sys
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client
seen = set()
client = Client(BASE, timeout=3)
for _ in range(attempts):
try:
seen.add(client.call('GET', '/api/v1/users/me', actor=actor, schema='User')['headers']['X-Instance-Id'])
except Exception:
time.sleep(0.3)
continue
if len(seen) >= expect:
return seen
time.sleep(0.05)
return seen
def started_at():
result = subprocess.run(
['docker', 'ps', '-a', '--filter', 'label=com.docker.compose.project=mtusi-lab3', '--format', '{{.Names}}\t{{.Status}}\t{{.ID}}'],
text=True,
capture_output=True,
check=True,
)
rows = []
for line in result.stdout.splitlines():
if not line.strip():
continue
name = line.split('\t', 1)[0]
rows.append({
'name': name,
'started_at': inspect(name, '{{.State.StartedAt}}'),
'status': inspect(name, '{{.State.Status}}'),
})
return rows
def sample_stats():
result = subprocess.run(
['docker', 'stats', '--no-stream', '--format', '{{json .}}'],
text=True,
capture_output=True,
check=True,
)
rows = []
for line in result.stdout.splitlines():
if not line.strip():
continue
item = json.loads(line)
name = item.get('Name', '')
if 'mtusi-lab3' not in name:
continue
rows.append({
'name': name,
'cpu': item.get('CPUPerc'),
'mem': item.get('MemUsage'),
})
return rows
def mean_cpu(samples, role):
values = []
for sample in samples:
for row in sample:
if role not in row['name']:
continue
text = (row.get('cpu') or '').strip().rstrip('%')
try:
values.append(float(text))
except ValueError:
continue
if not values:
return None
return round(sum(values) / len(values), 2)