forked from mtusi2026/mtusi2026lab4
chore: carry over lab3 implementation
This commit is contained in:
Executable
+162
@@ -0,0 +1,162 @@
|
||||
#!/bin/sh
|
||||
set -u
|
||||
cd "$(dirname "$0")/.."
|
||||
mkdir -p evidence
|
||||
|
||||
COMMIT="$(git rev-parse --short HEAD)$(git diff --quiet HEAD -- src prisma test scripts infra compose.yaml Dockerfile || echo ' (dirty)')"
|
||||
|
||||
header() {
|
||||
printf '# %s\n# date: %s\n# commit: %s\n\n' "$1" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$COMMIT"
|
||||
}
|
||||
|
||||
run() {
|
||||
echo "\$ $*"
|
||||
"$@" 2>&1 || echo "EXIT CODE $?"
|
||||
echo
|
||||
}
|
||||
|
||||
started() {
|
||||
docker inspect -f '{{.Name}} {{.State.Status}} started={{.State.StartedAt}}' $(docker compose ps -aq postgres redis api lb)
|
||||
}
|
||||
|
||||
api_states() {
|
||||
docker inspect -f '{{.Name}} id={{slice .Id 0 12}} {{.State.Status}} exit={{.State.ExitCode}} finished={{.State.FinishedAt}}' $(docker compose ps -aq api)
|
||||
}
|
||||
|
||||
restore_api() {
|
||||
for id in $(docker compose ps -aq --status exited api); do
|
||||
docker start "$id" >/dev/null
|
||||
done
|
||||
python3 scripts/probe.py ready >/dev/null
|
||||
sleep 3
|
||||
}
|
||||
|
||||
echo 'container.txt'
|
||||
{
|
||||
header 'Стенд: сервисы, порты, лимиты, секреты, миграции'
|
||||
run docker compose ps -a --format 'table {{.Service}}\t{{.Name}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}'
|
||||
echo '## CPU/RAM-лимиты (NanoCpus: 1e9 = 1 CPU; Memory в байтах)'
|
||||
run sh -c "docker inspect -f '{{.Name}} cpus={{.HostConfig.NanoCpus}} memory={{.HostConfig.Memory}}' \$(docker compose ps -q)"
|
||||
echo '## container_name не задан (одно имя сервиса масштабируется)'
|
||||
run sh -c "docker compose config | grep -c container_name || true"
|
||||
echo '## Секреты: каждый сервис видит только свои файлы'
|
||||
for service in postgres redis api; do
|
||||
run docker compose exec -T "$service" ls /run/secrets
|
||||
done
|
||||
run docker compose exec -T lb sh -c 'ls /run/secrets 2>/dev/null || echo "no /run/secrets"'
|
||||
run docker compose exec -T lb haproxy -v
|
||||
run docker compose exec -T postgres postgres --version
|
||||
run docker compose exec -T redis redis-server --version
|
||||
echo '## Миграции: отдельный one-shot сервис, повторный запуск ничего не применяет'
|
||||
run docker compose run --rm migrate
|
||||
run docker compose run --rm --no-deps migrate sh -c 'export DATABASE_URL="$(cat "$DATABASE_URL_FILE")"; npx prisma migrate diff --from-url "$DATABASE_URL" --to-schema-datamodel prisma/schema.prisma --exit-code'
|
||||
run docker compose exec -T postgres psql -U messenger -d messenger -c 'SELECT migration_name, finished_at FROM _prisma_migrations ORDER BY started_at'
|
||||
} > evidence/container.txt
|
||||
|
||||
echo 'tests.txt'
|
||||
{
|
||||
header 'Собственные e2e-тесты (PostgreSQL + Redis из compose.test.yaml)'
|
||||
docker compose -f compose.test.yaml build -q tests
|
||||
run docker compose -f compose.test.yaml run --rm tests npx jest --config ./test/jest-e2e.json --verbose
|
||||
docker compose -f compose.test.yaml down >/dev/null 2>&1
|
||||
} > evidence/tests.txt
|
||||
|
||||
echo 'smoke.txt'
|
||||
{
|
||||
header 'Публичные проверки через LB; разные реплики обслуживают одну сессию'
|
||||
run make check
|
||||
run make test
|
||||
run sh -c "docker compose ps -q api | cut -c1-12"
|
||||
run python3 scripts/probe.py instances 6
|
||||
} > evidence/smoke.txt
|
||||
|
||||
echo 'persistence.txt'
|
||||
{
|
||||
header 'make test-persistence: restart.sh перезапускает postgres, redis, api, lb с сохранением volumes'
|
||||
echo '## до'
|
||||
started
|
||||
echo
|
||||
run make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
echo '## после'
|
||||
started
|
||||
} > evidence/persistence.txt
|
||||
|
||||
echo 'failover.txt'
|
||||
{
|
||||
header 'make test-failover: stop-one.sh останавливает реплику, обслужившую тест; затем вторую'
|
||||
for round in 1 2; do
|
||||
echo "## Прогон $round"
|
||||
echo '### до'
|
||||
api_states
|
||||
echo
|
||||
since=$(date -u +%Y-%m-%dT%H:%M:%SZ)
|
||||
run make test-failover ACTION_SCRIPT=scripts/stop-one.sh
|
||||
echo '### после: остановленная реплика Exited (0) — штатное завершение по SIGTERM'
|
||||
api_states
|
||||
echo
|
||||
echo '### журнал HAProxy'
|
||||
docker compose logs --no-log-prefix --since "$since" lb 2>&1 | grep -E 'is DOWN|is UP|maintenance|READY' | grep -v '^\[WARNING\]'
|
||||
echo
|
||||
restore_api
|
||||
python3 scripts/probe.py status GET /health/live >/dev/null
|
||||
done
|
||||
echo '## Проверка guard: stop-one.sh отказывается останавливать не api'
|
||||
run env TARGET_INSTANCE_ID="$(docker compose ps -q postgres | cut -c1-12)" sh scripts/stop-one.sh
|
||||
} > evidence/failover.txt
|
||||
|
||||
echo 'experiments: idempotency, failover, failover --kill, rolling'
|
||||
python3 scripts/experiment.py idempotency --output evidence/idempotency.json >/dev/null 2>&1
|
||||
python3 scripts/experiment.py failover --output evidence/failover-stop.json >/dev/null 2>&1
|
||||
python3 scripts/experiment.py failover --kill --output evidence/failover-kill.json >/dev/null 2>&1
|
||||
docker compose build -q api >/dev/null 2>&1
|
||||
python3 scripts/experiment.py rolling --output evidence/rolling.json >/dev/null 2>&1
|
||||
|
||||
echo 'failures.txt'
|
||||
{
|
||||
header 'Отказы зависимостей, ошибки LB, expiry'
|
||||
echo '## 1. Redis остановлен: вход и Bearer через PostgreSQL; logout — 503 без отзыва (токен остаётся действующим)'
|
||||
run docker compose stop redis
|
||||
run python3 scripts/probe.py logout
|
||||
run docker compose start redis
|
||||
sleep 3
|
||||
echo '## 2. Redis снова доступен: logout отзывает токен на всех репликах'
|
||||
run python3 scripts/probe.py logout
|
||||
echo '## 3. PostgreSQL остановлен: live 200, запрос с токеном — 503 без внутренних деталей, аноним — 401'
|
||||
run docker compose stop postgres
|
||||
run python3 scripts/probe.py status GET /health/live
|
||||
run python3 scripts/probe.py status GET /api/v1/chats 'Bearer unknown-token'
|
||||
run python3 scripts/probe.py status GET /api/v1/users/me
|
||||
run docker compose start postgres
|
||||
run python3 scripts/probe.py ready
|
||||
echo '## 4. Все реплики API остановлены: LB отвечает 503 в формате ошибки контракта'
|
||||
run docker compose stop api
|
||||
run python3 scripts/probe.py status GET /api/v1/users/me
|
||||
run docker compose start api
|
||||
run python3 scripts/probe.py ready
|
||||
echo '## 5. Живая, но неготовая реплика: PostgreSQL отклоняет подключения только от одной API (pg_hba reject)'
|
||||
target=$(docker compose ps -q api | head -1 | cut -c1-12)
|
||||
ip=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "$target")
|
||||
hba=/var/lib/postgresql/data/pg_hba.conf
|
||||
echo "target=$target ip=$ip"
|
||||
since=$(date -u +%Y-%m-%dT%H:%M:%SZ)
|
||||
docker compose exec -T postgres sh -c "cp $hba /tmp/pg_hba.bak && { echo 'host all all $ip/32 reject'; cat /tmp/pg_hba.bak; } > $hba && chown postgres:postgres $hba && chmod 600 $hba"
|
||||
docker compose exec -T postgres psql -U messenger -d messenger -tAc "SELECT pg_reload_conf(); SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE client_addr = '$ip'" >/dev/null
|
||||
sleep 4
|
||||
run docker exec "$target" node -e "let n=0;const g=p=>require('http').get('http://127.0.0.1:8080'+p,r=>{console.log(p,r.statusCode);r.resume();if(++n===2)process.exit(0)});g('/health/live');g('/health/ready')"
|
||||
run python3 scripts/probe.py instances 10
|
||||
docker compose logs --no-log-prefix --since "$since" lb 2>&1 | grep -E 'is DOWN|is UP' | grep -v '^\[WARNING\]'
|
||||
echo
|
||||
docker compose exec -T postgres sh -c "cp /tmp/pg_hba.bak $hba && chown postgres:postgres $hba && chmod 600 $hba"
|
||||
docker compose exec -T postgres psql -U messenger -d messenger -tAc "SELECT pg_reload_conf()" >/dev/null
|
||||
sleep 4
|
||||
echo '### доступ возвращён: реплика снова готова и получает запросы'
|
||||
run python3 scripts/probe.py instances 6
|
||||
echo '## 6. Expiry: реплики пересозданы с SESSION_TTL_SECONDS=2'
|
||||
SESSION_TTL_SECONDS=2 docker compose up -d --no-deps --wait api >/dev/null 2>&1
|
||||
run sh -c "docker exec \$(docker compose ps -q api | head -1) printenv SESSION_TTL_SECONDS"
|
||||
run python3 scripts/probe.py expiry 2
|
||||
docker compose up -d --no-deps --wait api >/dev/null 2>&1
|
||||
run python3 scripts/probe.py ready
|
||||
} > evidence/failures.txt
|
||||
|
||||
echo 'done'
|
||||
Executable
+255
@@ -0,0 +1,255 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, Failure
|
||||
|
||||
BASE_URL = os.environ.get('BASE_URL', 'http://lb:8080')
|
||||
|
||||
|
||||
def docker(*args):
|
||||
return subprocess.run(['docker', *args], check=True, capture_output=True, text=True).stdout.strip()
|
||||
|
||||
|
||||
def api_containers():
|
||||
return [cid[:12] for cid in docker('compose', 'ps', '-q', 'api').split()]
|
||||
|
||||
|
||||
def describe(cid):
|
||||
return docker('inspect', '-f', '{{.Name}} {{.State.Status}} image={{slice .Image 7 19}}', cid)
|
||||
|
||||
|
||||
def wait_healthy(cid, timeout=60):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
if docker('inspect', '-f', '{{.State.Health.Status}}', cid) == 'healthy':
|
||||
return
|
||||
time.sleep(0.2)
|
||||
raise SystemExit(cid + ' did not become healthy')
|
||||
|
||||
|
||||
class Load:
|
||||
def __init__(self, client, actor, chat, workers):
|
||||
self.client, self.actor, self.chat = client, actor, chat
|
||||
self.workers = workers
|
||||
self.lock = threading.Lock()
|
||||
self.events = []
|
||||
self.confirmed = []
|
||||
self.stop_flag = threading.Event()
|
||||
self.threads = [threading.Thread(target=self.worker, args=(i,)) for i in range(workers)]
|
||||
self.started = None
|
||||
|
||||
def worker(self, index):
|
||||
local = Client(BASE_URL, timeout=2)
|
||||
key = uuid.uuid4().hex
|
||||
while not self.stop_flag.is_set():
|
||||
try:
|
||||
response = local.message(self.actor, self.chat, 'load ' + key, key=key)
|
||||
with self.lock:
|
||||
self.events.append((time.monotonic(), True, response['headers']['X-Instance-Id'], response['elapsed']))
|
||||
self.confirmed.append(response['json'])
|
||||
key = uuid.uuid4().hex
|
||||
except Failure:
|
||||
with self.lock:
|
||||
self.events.append((time.monotonic(), False, None, None))
|
||||
time.sleep(0.05)
|
||||
|
||||
def __enter__(self):
|
||||
self.started = time.monotonic()
|
||||
for thread in self.threads:
|
||||
thread.start()
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
self.stop_flag.set()
|
||||
for thread in self.threads:
|
||||
thread.join()
|
||||
|
||||
def window(self, start, end):
|
||||
with self.lock:
|
||||
events = [e for e in self.events if start <= e[0] < end]
|
||||
ok = sorted(e[0] for e in events if e[1])
|
||||
latencies = sorted(e[3] for e in events if e[1])
|
||||
points = [start, *ok, end]
|
||||
|
||||
def percentile(p):
|
||||
return round(1000 * latencies[max(0, math.ceil(p * len(latencies)) - 1)], 1) if latencies else None
|
||||
|
||||
return {
|
||||
'seconds': round(end - start, 3),
|
||||
'successful_writes': len(ok),
|
||||
'failed_attempts': len(events) - len(ok),
|
||||
'error_ratio': round((len(events) - len(ok)) / len(events), 4) if events else None,
|
||||
'successful_rps': round(len(ok) / (end - start), 1),
|
||||
'latency_ms_successful': {'p50': percentile(0.5), 'p95': percentile(0.95), 'p99': percentile(0.99)},
|
||||
'max_write_gap_seconds': round(max(b - a for a, b in zip(points, points[1:])), 3),
|
||||
'instances': sorted({e[2] for e in events if e[1]}),
|
||||
}
|
||||
|
||||
def last_seen(self, instance, start, end):
|
||||
with self.lock:
|
||||
times = [e[0] for e in self.events if e[1] and e[2] == instance and start <= e[0] < end]
|
||||
return max(times) if times else None
|
||||
|
||||
def first_seen_after(self, instance, after):
|
||||
with self.lock:
|
||||
times = [e[0] for e in self.events if e[1] and e[2] == instance and e[0] >= after]
|
||||
return min(times) if times else None
|
||||
|
||||
|
||||
def verify_history(client, actor, chat, confirmed):
|
||||
path = '/api/v1/chats/' + chat['id'] + '/messages?limit=100'
|
||||
items = []
|
||||
while True:
|
||||
page = client.call('GET', path, actor=actor, schema='MessagePage')['json']
|
||||
items.extend(page['items'])
|
||||
if page['next_cursor'] is None:
|
||||
break
|
||||
path = '/api/v1/chats/' + chat['id'] + '/messages?limit=100&cursor=' + quote(page['next_cursor'], safe='')
|
||||
texts = [m['text'] for m in items]
|
||||
stored = {m['id']: m for m in items}
|
||||
return {
|
||||
'confirmed': len(confirmed),
|
||||
'stored': len(items),
|
||||
'lost_confirmed': sum(1 for m in confirmed if stored.get(m['id']) != m),
|
||||
'duplicates': len(texts) - len(set(texts)),
|
||||
}
|
||||
|
||||
|
||||
def resources():
|
||||
ids = docker('compose', 'ps', '-q').split()
|
||||
return docker('stats', '--no-stream', '--format', '{{.Name}} cpu={{.CPUPerc}} mem={{.MemUsage}}', *ids).splitlines()
|
||||
|
||||
|
||||
def messages_in_db():
|
||||
return int(docker('compose', 'exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-tAc', 'SELECT count(*) FROM messages'))
|
||||
|
||||
|
||||
def failover(load, args):
|
||||
results = []
|
||||
with load:
|
||||
time.sleep(args.warmup)
|
||||
usage = resources()
|
||||
for cid in api_containers():
|
||||
t0 = time.monotonic()
|
||||
docker('kill' if args.kill else 'stop', cid)
|
||||
stopped = time.monotonic()
|
||||
time.sleep(args.outage)
|
||||
outage = load.window(t0, time.monotonic())
|
||||
restore = time.monotonic()
|
||||
docker('start', cid)
|
||||
wait_healthy(cid)
|
||||
healthy = time.monotonic()
|
||||
time.sleep(args.warmup)
|
||||
rejoined = load.first_seen_after(cid, restore)
|
||||
last = load.last_seen(cid, t0, restore)
|
||||
results.append({
|
||||
'container': describe(cid),
|
||||
'action': 'docker kill (SIGKILL)' if args.kill else 'docker stop (SIGTERM, graceful)',
|
||||
'before': load.window(t0 - args.warmup, t0),
|
||||
'stop_command_seconds': round(stopped - t0, 3),
|
||||
'target_last_success_after_stop_seconds': round(last - t0, 3) if last else None,
|
||||
'outage_window': outage,
|
||||
'restore_until_healthy_seconds': round(healthy - restore, 3),
|
||||
'restore_until_serving_seconds': round(rejoined - restore, 3) if rejoined else None,
|
||||
'after_restore': load.window(healthy, time.monotonic()),
|
||||
})
|
||||
return {'scenario': 'sequential failover of each api replica', 'resources_under_load': usage, 'replicas': results}
|
||||
|
||||
|
||||
def rolling(load, args):
|
||||
old = api_containers()
|
||||
before = [describe(cid) for cid in old]
|
||||
steps = []
|
||||
with load:
|
||||
time.sleep(args.warmup)
|
||||
usage = resources()
|
||||
t_start = time.monotonic()
|
||||
docker('compose', 'run', '--rm', '--no-deps', 'migrate')
|
||||
for cid in old:
|
||||
t0 = time.monotonic()
|
||||
docker('compose', 'up', '-d', '--no-deps', '--no-recreate', '--scale', 'api=' + str(len(old) + 1), '--wait', 'api')
|
||||
added = time.monotonic()
|
||||
docker('stop', cid)
|
||||
docker('rm', cid)
|
||||
steps.append({'replaced': cid, 'new_replica_ready_seconds': round(added - t0, 3), 'step_seconds': round(time.monotonic() - t0, 3)})
|
||||
time.sleep(args.warmup)
|
||||
total = load.window(t_start, time.monotonic())
|
||||
return {
|
||||
'scenario': 'rolling replacement: migrate once, then add new replica, wait healthy, stop old one',
|
||||
'resources_under_load': usage,
|
||||
'before': before,
|
||||
'after': [describe(cid) for cid in api_containers()],
|
||||
'steps': steps,
|
||||
'during_update': total,
|
||||
}
|
||||
|
||||
|
||||
def idempotency(client, actor, chat, args):
|
||||
key = uuid.uuid4().hex
|
||||
text = 'parallel ' + key
|
||||
|
||||
def send(_):
|
||||
local = Client(BASE_URL, timeout=10)
|
||||
response = local.message(actor, chat, text, key=key)
|
||||
return response['json']['id'], response['headers']['X-Instance-Id']
|
||||
|
||||
with ThreadPoolExecutor(max_workers=args.parallel) as pool:
|
||||
results = list(pool.map(send, range(args.parallel)))
|
||||
path = '/api/v1/chats/' + chat['id'] + '/messages?limit=100'
|
||||
stored = [m for m in client.call('GET', path, actor=actor, schema='MessagePage')['json']['items'] if m['text'] == text]
|
||||
return {
|
||||
'scenario': 'parallel POST with one Idempotency-Key through LB',
|
||||
'requests': args.parallel,
|
||||
'all_201': True,
|
||||
'distinct_message_ids': len({r[0] for r in results}),
|
||||
'instances': sorted({r[1] for r in results}),
|
||||
'messages_in_history': len(stored),
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='Lab3 level-4 experiments under load through LB')
|
||||
parser.add_argument('scenario', choices=['failover', 'rolling', 'idempotency'])
|
||||
parser.add_argument('--workers', type=int, default=4)
|
||||
parser.add_argument('--warmup', type=float, default=5)
|
||||
parser.add_argument('--outage', type=float, default=10)
|
||||
parser.add_argument('--parallel', type=int, default=20)
|
||||
parser.add_argument('--kill', action='store_true')
|
||||
parser.add_argument('--output')
|
||||
args = parser.parse_args()
|
||||
|
||||
client = Client(BASE_URL)
|
||||
alice, bob, _, chat = client.bootstrap()
|
||||
scenarios = {'failover': failover, 'rolling': rolling}
|
||||
if args.scenario in scenarios:
|
||||
load = Load(client, alice, chat, args.workers)
|
||||
dataset = messages_in_db()
|
||||
report = scenarios[args.scenario](load, args)
|
||||
report['dataset'] = {'messages_in_db_before': dataset, 'messages_in_db_after': messages_in_db()}
|
||||
report['history'] = verify_history(client, bob, chat, load.confirmed)
|
||||
report['load'] = {'workers': args.workers, 'model': 'closed loop, POST message', 'warmup_seconds': args.warmup, 'client_timeout_seconds': 2, 'retry': 'same Idempotency-Key until success'}
|
||||
else:
|
||||
report = idempotency(client, alice, chat, args)
|
||||
report['date'] = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())
|
||||
text = json.dumps(report, ensure_ascii=False, indent=2)
|
||||
if args.output:
|
||||
Path(args.output).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(args.output).write_text(text + '\n')
|
||||
print(text)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,88 @@
|
||||
#!/usr/bin/env python3
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
BASE = os.environ.get('BASE_URL', 'http://localhost:8080')
|
||||
|
||||
|
||||
def call(method, path, body=None, headers=None, with_headers=False):
|
||||
data = json.dumps(body).encode() if body is not None else None
|
||||
content_type = {'Content-Type': 'application/json'} if data else {}
|
||||
request = urllib.request.Request(BASE + path, data=data, method=method, headers={**content_type, **(headers or {})})
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=15) as response:
|
||||
result = response.status, json.loads(response.read() or b'null'), response.headers
|
||||
except urllib.error.HTTPError as error:
|
||||
result = error.code, json.loads(error.read() or b'null'), error.headers
|
||||
except OSError as error:
|
||||
result = 0, str(error), {}
|
||||
return result if with_headers else result[:2]
|
||||
|
||||
|
||||
def login():
|
||||
username = 'probe_' + uuid.uuid4().hex[:8]
|
||||
password = 'Probe-check-' + uuid.uuid4().hex
|
||||
print('register ->', call('POST', '/api/v1/users', {'username': username, 'display_name': 'Probe', 'password': password})[0])
|
||||
credential = base64.b64encode((username + ':' + password).encode()).decode()
|
||||
code, session = call('POST', '/api/v1/auth/sessions', headers={'Authorization': 'Basic ' + credential})
|
||||
if code != 201:
|
||||
sys.exit('login failed: %s %s' % (code, session))
|
||||
print('login ->', code, 'expires_at:', session['expires_at'])
|
||||
return {'Authorization': 'Bearer ' + session['token']}
|
||||
|
||||
|
||||
def instances(count):
|
||||
auth = login()
|
||||
for _ in range(count):
|
||||
code, _, headers = call('GET', '/api/v1/users/me', headers=auth, with_headers=True)
|
||||
print('GET /api/v1/users/me ->', code, 'X-Instance-Id:', headers.get('X-Instance-Id'))
|
||||
|
||||
|
||||
def logout():
|
||||
auth = login()
|
||||
print('GET /api/v1/users/me ->', call('GET', '/api/v1/users/me', headers=auth)[0])
|
||||
code, body = call('DELETE', '/api/v1/auth/sessions/current', headers=auth)
|
||||
print('DELETE /api/v1/auth/sessions/current ->', code, json.dumps(body, ensure_ascii=False) if body else '')
|
||||
print('GET /api/v1/users/me ->', call('GET', '/api/v1/users/me', headers=auth)[0])
|
||||
|
||||
|
||||
def ready(timeout=90):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
if call('GET', '/health/ready')[0] == 200:
|
||||
print('ready')
|
||||
return
|
||||
time.sleep(0.5)
|
||||
sys.exit('not ready within %ds' % timeout)
|
||||
|
||||
|
||||
def status(method, path, authorization=None):
|
||||
code, body = call(method, path, headers={'Authorization': authorization} if authorization else None)
|
||||
print(method, path, '(%s)' % (authorization or 'anonymous'), '->', code, json.dumps(body, ensure_ascii=False))
|
||||
|
||||
|
||||
def expiry(ttl):
|
||||
auth = login()
|
||||
print('GET /api/v1/users/me (fresh) ->', call('GET', '/api/v1/users/me', headers=auth)[0])
|
||||
time.sleep(ttl + 1)
|
||||
print('GET /api/v1/users/me (after %ds) ->' % (ttl + 1), call('GET', '/api/v1/users/me', headers=auth)[0])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
command = sys.argv[1]
|
||||
if command == 'ready':
|
||||
ready()
|
||||
elif command == 'status':
|
||||
status(*sys.argv[2:5])
|
||||
elif command == 'expiry':
|
||||
expiry(int(sys.argv[2]))
|
||||
elif command == 'instances':
|
||||
instances(int(sys.argv[2]))
|
||||
elif command == 'logout':
|
||||
logout()
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
started() {
|
||||
docker inspect -f '{{.Name}} {{.State.Status}} started={{.State.StartedAt}}' $(docker compose ps -aq postgres redis api lb)
|
||||
}
|
||||
started
|
||||
docker compose restart postgres redis api lb
|
||||
started
|
||||
Executable
+11
@@ -0,0 +1,11 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
|
||||
project="${COMPOSE_PROJECT_NAME:-messenger-lab4}"
|
||||
labels=$(docker inspect -f '{{index .Config.Labels "com.docker.compose.project"}}/{{index .Config.Labels "com.docker.compose.service"}}' "$TARGET_INSTANCE_ID")
|
||||
if [ "$labels" != "$project/api" ]; then
|
||||
echo "refusing to stop $TARGET_INSTANCE_ID: not an api replica of $project ($labels)" >&2
|
||||
exit 1
|
||||
fi
|
||||
docker stop -t 8 "$TARGET_INSTANCE_ID" >/dev/null
|
||||
docker inspect -f '{{.Name}} {{.State.Status}} finished={{.State.FinishedAt}}' "$TARGET_INSTANCE_ID"
|
||||
Reference in New Issue
Block a user