forked from mtusi2026/mtusi2026lab3
two api-replicas with LB-nginx
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""Команды управления учебным стендом."""
|
||||
@@ -0,0 +1,348 @@
|
||||
"""Проверяет инфраструктуру, SIGTERM и обновление реального стенда."""
|
||||
|
||||
import asyncio
|
||||
from collections import Counter
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
from threading import Event
|
||||
import time
|
||||
from uuid import uuid4
|
||||
|
||||
import asyncpg
|
||||
|
||||
from scripts.deployment import ComposeProject, ROOT, deployment_lock
|
||||
from scripts.failover_all import exercise, failure_kind, history
|
||||
from scripts.rolling_update import update
|
||||
from tests.client import Client, Failure, arguments, check, run
|
||||
|
||||
PROBE = """import json, sys, urllib.request, urllib.error
|
||||
payload = json.load(sys.stdin)
|
||||
results = []
|
||||
for item in payload:
|
||||
data = json.dumps(item['body']).encode() if 'body' in item else None
|
||||
request = urllib.request.Request(item['url'], data=data, headers=item.get('headers', {}), method=item.get('method', 'GET'))
|
||||
try:
|
||||
response = urllib.request.urlopen(request, timeout=7)
|
||||
except urllib.error.HTTPError as error:
|
||||
response = error
|
||||
with response:
|
||||
results.append({'status': response.status, 'body': json.loads(response.read())})
|
||||
print(json.dumps(results))
|
||||
"""
|
||||
|
||||
|
||||
def probe(project, runner, requests):
|
||||
"""Обращается к внутреннему API, передавая токен только через stdin."""
|
||||
result = subprocess.run(
|
||||
["docker", "exec", "-i", runner, "python", "-c", PROBE],
|
||||
input=json.dumps(requests),
|
||||
text=True,
|
||||
capture_output=True,
|
||||
timeout=10,
|
||||
)
|
||||
check(result.returncode == 0, "internal HTTP probe failed")
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
def audit(project):
|
||||
"""Проверяет фактические лимиты, порты и область доступа к секретам."""
|
||||
allowed = {
|
||||
"postgres": {"db_password"},
|
||||
"redis": {"redis_password"},
|
||||
"migrate": {"db_password"},
|
||||
"api": {"db_password", "redis_password"},
|
||||
"nginx": set(),
|
||||
}
|
||||
ids = project.run("ps", "--all", "--quiet").splitlines()
|
||||
containers = json.loads(project.docker("inspect", *ids))
|
||||
for item in containers:
|
||||
service = item["Config"]["Labels"]["com.docker.compose.service"]
|
||||
check(service in allowed, "unexpected service")
|
||||
host = item["HostConfig"]
|
||||
check(
|
||||
host["Memory"] > 0 and host["NanoCpus"] > 0,
|
||||
service + ": missing CPU/RAM limit",
|
||||
)
|
||||
env_names = {entry.split("=", 1)[0] for entry in item["Config"]["Env"]}
|
||||
check(
|
||||
not env_names
|
||||
& {
|
||||
"DB_PASSWORD",
|
||||
"REDIS_PASSWORD",
|
||||
"POSTGRES_PASSWORD",
|
||||
"REDISCLI_AUTH",
|
||||
"DATABASE_URL",
|
||||
},
|
||||
service + ": password in environment",
|
||||
)
|
||||
secrets = {
|
||||
Path(mount["Destination"]).name
|
||||
for mount in item["Mounts"]
|
||||
if mount["Destination"].startswith("/run/secrets/")
|
||||
}
|
||||
check(secrets == allowed[service], service + ": incorrect secret scope")
|
||||
if service == "api":
|
||||
check(not host["PortBindings"], "API publishes ports")
|
||||
for mount in item["Mounts"]:
|
||||
if mount["Destination"].startswith("/run/secrets/"):
|
||||
check(not mount["RW"], "writable secret mount")
|
||||
check(
|
||||
"container_name" not in project.config["services"][service],
|
||||
"fixed container name",
|
||||
)
|
||||
check(
|
||||
len(containers) == 6,
|
||||
"expected PostgreSQL, Redis, migrate, Nginx and two API replicas",
|
||||
)
|
||||
print(
|
||||
"PASS infrastructure: CPU/RAM, private API ports, scoped read-only file secrets, no environment passwords",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
|
||||
async def graceful(project, base_url):
|
||||
"""Удерживает реальный POST в БД и завершает его после SIGTERM."""
|
||||
replicas = project.replicas()
|
||||
target, runner = replicas[:2]
|
||||
client = Client(base_url)
|
||||
actor, _, _, chat = await asyncio.to_thread(client.bootstrap)
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
key = uuid4().hex
|
||||
raw = json.dumps([actor["id"], "POST", path, key]).encode()
|
||||
lock_id = int.from_bytes(hashlib.sha256(raw).digest()[:8], signed=True)
|
||||
database = project.config["services"]["postgres"]
|
||||
env = database["environment"]
|
||||
conn = await asyncpg.connect(
|
||||
host="127.0.0.1",
|
||||
port=int(database["ports"][0]["published"]),
|
||||
database=env["POSTGRES_DB"],
|
||||
user=env["POSTGRES_USER"],
|
||||
password=(ROOT / "secrets/db_password").read_text().strip(),
|
||||
timeout=3,
|
||||
)
|
||||
address = project.docker(
|
||||
"inspect",
|
||||
"--format",
|
||||
"{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}",
|
||||
target.id,
|
||||
)
|
||||
port = project.config["services"]["api"]["environment"]["APP_PORT"]
|
||||
direct = f"http://{address}:{port}"
|
||||
started = time.monotonic()
|
||||
task = None
|
||||
try:
|
||||
async with conn.transaction():
|
||||
await conn.execute("SELECT pg_advisory_xact_lock($1)", lock_id)
|
||||
task = asyncio.create_task(
|
||||
asyncio.to_thread(
|
||||
probe,
|
||||
project,
|
||||
runner.id,
|
||||
[
|
||||
{
|
||||
"url": direct + path,
|
||||
"method": "POST",
|
||||
"body": {"text": "graceful-" + key},
|
||||
"headers": {
|
||||
"Authorization": "Bearer " + actor["token"],
|
||||
"Idempotency-Key": key,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}
|
||||
],
|
||||
)
|
||||
)
|
||||
deadline = time.monotonic() + 3
|
||||
while not await conn.fetchval(
|
||||
"SELECT EXISTS(SELECT 1 FROM pg_stat_activity WHERE wait_event = 'advisory' AND datname = current_database())"
|
||||
):
|
||||
check(time.monotonic() < deadline, "POST did not reach database lock")
|
||||
await asyncio.sleep(0.02)
|
||||
started = time.monotonic()
|
||||
await asyncio.to_thread(
|
||||
project.docker, "kill", "--signal", "SIGTERM", target.id
|
||||
)
|
||||
results = await asyncio.to_thread(
|
||||
probe,
|
||||
project,
|
||||
runner.id,
|
||||
[
|
||||
{"url": direct + "/health/ready"},
|
||||
{"url": direct + "/health/live"},
|
||||
{"url": direct + "/api/v1/users/me"},
|
||||
],
|
||||
)
|
||||
check(
|
||||
[item["status"] for item in results] == [503, 200, 503],
|
||||
"incorrect drain readiness/liveness/new work",
|
||||
)
|
||||
await asyncio.sleep(max(0, 1.2 - (time.monotonic() - started)))
|
||||
result = (await task)[0]
|
||||
check(result["status"] == 201, "in-flight POST failed during SIGTERM")
|
||||
await asyncio.to_thread(project.docker, "wait", target.id, timeout=10)
|
||||
state = json.loads(
|
||||
project.docker("inspect", "--format", "{{json .State}}", target.id)
|
||||
)
|
||||
check(
|
||||
not state["OOMKilled"] and state["ExitCode"] != 137,
|
||||
"forced shutdown instead of graceful completion",
|
||||
)
|
||||
check(time.monotonic() - started < 8, "shutdown exceeded Docker grace budget")
|
||||
items = await asyncio.to_thread(history, client, actor, chat)
|
||||
check(
|
||||
result["body"]["id"] in {item["id"] for item in items},
|
||||
"acknowledged in-flight message lost",
|
||||
)
|
||||
print(
|
||||
f"PASS SIGTERM: readiness 503, live 200, new work 503, in-flight POST 201; exit in {time.monotonic() - started:.3f}s",
|
||||
flush=True,
|
||||
)
|
||||
finally:
|
||||
await conn.close()
|
||||
if task:
|
||||
await asyncio.gather(task, return_exceptions=True)
|
||||
if any(item.id == target.id and item.running for item in project.replicas()):
|
||||
await asyncio.to_thread(project.docker, "stop", target.id)
|
||||
await asyncio.to_thread(project.docker, "start", target.id)
|
||||
await asyncio.to_thread(project.wait_healthy, {item.id for item in replicas})
|
||||
await asyncio.to_thread(project.wait_routed, target.instance_id, base_url)
|
||||
|
||||
|
||||
class ObservedProject(ComposeProject):
|
||||
"""Подсчитывает миграции и проверяет готовность перед заменой."""
|
||||
|
||||
def __init__(self):
|
||||
self.migrations = 0
|
||||
self.replacements = 0
|
||||
self.replacement_started = []
|
||||
super().__init__()
|
||||
|
||||
def run(self, *args, **kwargs):
|
||||
if args[:6] == ("run", "--rm", "--no-deps", "--pull", "never", "migrate"):
|
||||
self.migrations += 1
|
||||
return super().run(*args, **kwargs)
|
||||
|
||||
def docker(self, *args, **kwargs):
|
||||
if args[0] == "stop":
|
||||
healthy = [
|
||||
item
|
||||
for item in self.replicas()
|
||||
if item.id != args[1] and item.running and item.health == "healthy"
|
||||
]
|
||||
check(len(healthy) >= 2, "rolling update reduces healthy capacity")
|
||||
self.replacements += 1
|
||||
self.replacement_started.append(time.monotonic())
|
||||
return super().docker(*args, **kwargs)
|
||||
|
||||
|
||||
def rolling(base_url):
|
||||
"""Заменяет образ под постоянной записью с проверкой сохранности."""
|
||||
project = ObservedProject()
|
||||
before = project.replicas()
|
||||
client = Client(base_url)
|
||||
actor, _, _, chat = client.bootstrap()
|
||||
stop = Event()
|
||||
results, errors = [], []
|
||||
|
||||
def worker():
|
||||
local = Client(base_url, timeout=2)
|
||||
key = uuid4().hex
|
||||
while not stop.is_set():
|
||||
started = time.monotonic()
|
||||
try:
|
||||
result = local.message(actor, chat, "rolling-" + key, key=key)
|
||||
results.append(
|
||||
(started, time.monotonic(), result["json"]["id"], result["elapsed"])
|
||||
)
|
||||
key = uuid4().hex
|
||||
except Failure as error:
|
||||
errors.append(failure_kind(error))
|
||||
stop.wait(0.08)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||
jobs = [pool.submit(worker) for _ in range(2)]
|
||||
try:
|
||||
time.sleep(1)
|
||||
started = time.monotonic()
|
||||
update(project, base_url, revision="verification-" + uuid4().hex[:12])
|
||||
finished = time.monotonic()
|
||||
time.sleep(1)
|
||||
finally:
|
||||
stop.set()
|
||||
for job in jobs:
|
||||
job.result(timeout=5)
|
||||
after = project.replicas()
|
||||
check(
|
||||
project.migrations == 1 and project.replacements == len(before),
|
||||
"migration/replacement count incorrect",
|
||||
)
|
||||
check(
|
||||
{item.image for item in before}.isdisjoint({item.image for item in after}),
|
||||
"new image was not deployed",
|
||||
)
|
||||
check(
|
||||
{item.id for item in before}.isdisjoint({item.id for item in after}),
|
||||
"old containers remain",
|
||||
)
|
||||
writes = [row for row in results if started <= row[0] <= finished]
|
||||
check(bool(writes), "no writes during update")
|
||||
check(
|
||||
any(project.replacement_started[0] <= row[0] <= finished for row in writes),
|
||||
"no writes during container replacement",
|
||||
)
|
||||
items = history(client, actor, chat)
|
||||
check(
|
||||
{row[2] for row in results} <= {item["id"] for item in items},
|
||||
"rolling update lost confirmed messages",
|
||||
)
|
||||
check(
|
||||
len(items) == len({item["text"] for item in items}),
|
||||
"rolling update created duplicate messages",
|
||||
)
|
||||
latencies = sorted(row[3] for row in writes)
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"scenario": "rolling update",
|
||||
"replacements": project.replacements,
|
||||
"migration_runs": project.migrations,
|
||||
"successful_writes": len(writes),
|
||||
"failed_attempts": len(errors),
|
||||
"errors_by_kind": dict(Counter(errors)),
|
||||
"elapsed_seconds": round(finished - started, 3),
|
||||
"successful_rps": round(len(writes) / (finished - started), 3),
|
||||
"p95_seconds": round(
|
||||
latencies[min(len(latencies) - 1, int(len(latencies) * 0.95))], 3
|
||||
),
|
||||
}
|
||||
),
|
||||
flush=True,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
"""Выполняет проверки только на отдельном тестовом проекте."""
|
||||
|
||||
def configure(parser):
|
||||
parser.add_argument(
|
||||
"--phase", choices=("all", "update-and-failover"), default="all"
|
||||
)
|
||||
|
||||
args = arguments("Grade 4 integration checks", configure)
|
||||
project = ComposeProject()
|
||||
check(project.name.endswith("-test"), "use isolated test Compose project")
|
||||
with deployment_lock(project):
|
||||
audit(project)
|
||||
if args.phase == "all":
|
||||
asyncio.run(graceful(project, args.base_url))
|
||||
rolling(args.base_url)
|
||||
args.duration, args.concurrency = 10, 2
|
||||
exercise(project, args)
|
||||
audit(project)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Проверяет конкурентные повторы через балансировщик."""
|
||||
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from uuid import uuid4
|
||||
|
||||
from tests.client import Client, arguments, check, run
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""Отправляет один ключ параллельно через разные реплики."""
|
||||
args = arguments("Concurrent idempotency through load balancer")
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
key = uuid4().hex
|
||||
body = "parallel-" + key
|
||||
|
||||
def send(_):
|
||||
return Client(args.base_url, args.ca_file).message(alice, chat, body, key=key)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=8) as pool:
|
||||
results = list(pool.map(send, range(24)))
|
||||
ids = {result["json"]["id"] for result in results}
|
||||
replicas = {result["headers"]["X-Instance-Id"] for result in results}
|
||||
check(len(ids) == 1, "parallel retries created duplicate messages")
|
||||
check(len(replicas) >= 2, "parallel retries did not reach two API replicas")
|
||||
history = client.call(
|
||||
"GET",
|
||||
f"/api/v1/chats/{chat['id']}/messages?limit=100",
|
||||
actor=alice,
|
||||
schema="MessagePage",
|
||||
)["json"]["items"]
|
||||
check(
|
||||
len(history) == 1 and history[0] == results[0]["json"], "history has duplicates"
|
||||
)
|
||||
print(f"PASS: 24 concurrent replays, {len(replicas)} replicas, one message")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,261 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Проверки реального nginx в отдельном Compose-проекте без БД и приложения."""
|
||||
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import gzip
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.request import Request, urlopen
|
||||
from uuid import uuid4
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
IMAGE = "nginx:1.28.0-alpine"
|
||||
PAYLOAD = json.dumps({"text": "message " * 256}).encode()
|
||||
|
||||
|
||||
def check(condition: bool, message: str) -> None:
|
||||
if not condition:
|
||||
raise AssertionError(message)
|
||||
|
||||
|
||||
class Stand:
|
||||
def __init__(self, directory: str) -> None:
|
||||
self.directory = Path(directory)
|
||||
self.project = "mtusi-lab3-nginx-check-" + uuid4().hex[:12]
|
||||
self.base_url = ""
|
||||
backend = self.directory / "backend.conf"
|
||||
backend.write_text(
|
||||
"worker_processes 1;\n"
|
||||
"events { worker_connections 1024; }\n"
|
||||
"http {\n"
|
||||
" log_format backend 'BACKEND $request_method $uri';\n"
|
||||
" access_log /dev/stdout backend;\n"
|
||||
" server {\n"
|
||||
" listen 8080;\n"
|
||||
" default_type application/json;\n"
|
||||
" add_header X-Instance-Id $hostname always;\n"
|
||||
" add_header X-Request-Id $request_id always;\n"
|
||||
" add_header Retry-After 7 always;\n"
|
||||
' location /health/ { return 200 \'{"status":"ok"}\'; }\n'
|
||||
" location = /api/limited {\n"
|
||||
' return 429 \'{"error":{"code":"rate_limited",'
|
||||
'"message":"upstream limit","request_id":"$request_id"}}\';\n'
|
||||
" }\n"
|
||||
" location = /api/post-failure {\n"
|
||||
' return 503 \'{"error":{"code":"unavailable",'
|
||||
'"message":"upstream failure","request_id":"$request_id"}}\';\n'
|
||||
" }\n"
|
||||
" location / { return 200 '" + PAYLOAD.decode() + "'; }\n"
|
||||
" }\n"
|
||||
"}\n"
|
||||
)
|
||||
self.compose_file = self.directory / "compose.json"
|
||||
self.compose_file.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"services": {
|
||||
"api": {
|
||||
"image": IMAGE,
|
||||
"volumes": [f"{backend}:/etc/nginx/nginx.conf:ro"],
|
||||
},
|
||||
"nginx": {
|
||||
"image": IMAGE,
|
||||
"volumes": [
|
||||
f"{ROOT / 'infra/nginx/nginx.conf'}:/etc/nginx/nginx.conf:ro"
|
||||
],
|
||||
"ports": ["127.0.0.1::8080"],
|
||||
},
|
||||
}
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
def compose(self, *args: str) -> str:
|
||||
# Явный файл, уникальный проект и пустой env-file исключают основной стенд.
|
||||
result = subprocess.run(
|
||||
[
|
||||
"docker",
|
||||
"compose",
|
||||
"--env-file",
|
||||
"/dev/null",
|
||||
"-f",
|
||||
str(self.compose_file),
|
||||
"-p",
|
||||
self.project,
|
||||
*args,
|
||||
],
|
||||
cwd=self.directory,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=45,
|
||||
)
|
||||
if result.returncode:
|
||||
raise RuntimeError(result.stdout + result.stderr)
|
||||
return result.stdout + result.stderr
|
||||
|
||||
def call(self, path: str, *, method: str = "GET", encoding: str = "identity"):
|
||||
request = Request(
|
||||
self.base_url + path,
|
||||
method=method,
|
||||
headers={"Accept-Encoding": encoding},
|
||||
data=b"{}" if method == "POST" else None,
|
||||
)
|
||||
try:
|
||||
response = urlopen(request, timeout=3)
|
||||
except HTTPError as error:
|
||||
response = error
|
||||
except (URLError, TimeoutError):
|
||||
return 0, {}, b""
|
||||
with response:
|
||||
return (
|
||||
response.status,
|
||||
{key.lower(): value for key, value in response.headers.items()},
|
||||
response.read(),
|
||||
)
|
||||
|
||||
def wait_instances(self, count: int) -> set[str]:
|
||||
seen: set[str] = set()
|
||||
deadline = time.monotonic() + 15
|
||||
while time.monotonic() < deadline:
|
||||
status, headers, _ = self.call("/health/live")
|
||||
if status == 200:
|
||||
seen.add(headers["x-instance-id"])
|
||||
if len(seen) == count:
|
||||
return seen
|
||||
time.sleep(0.05)
|
||||
raise AssertionError(f"Ожидалось {count} реплик, наблюдалось {len(seen)}")
|
||||
|
||||
|
||||
def check_error(response, status: int, code: str) -> None:
|
||||
actual_status, headers, body = response
|
||||
check(actual_status == status, f"Ожидался HTTP {status}, получен {actual_status}")
|
||||
check(
|
||||
headers.get("content-type", "").startswith("application/json"), "Ошибка не JSON"
|
||||
)
|
||||
error = json.loads(body)["error"]
|
||||
check(error["code"] == code, "Неверный код ошибки")
|
||||
check(error["request_id"] == headers.get("x-request-id"), "request_id не совпадает")
|
||||
|
||||
|
||||
def run_checks(stand: Stand) -> None:
|
||||
stand.compose("up", "-d", "--pull", "never", "--scale", "api=2", "api", "nginx")
|
||||
address = stand.compose("port", "nginx", "8080").strip()
|
||||
stand.base_url = "http://" + address
|
||||
stand.wait_instances(2)
|
||||
print(stand.compose("exec", "-T", "nginx", "nginx", "-v").strip())
|
||||
stand.compose("exec", "-T", "nginx", "nginx", "-t")
|
||||
print("PASS: nginx -t и балансировка двух реплик")
|
||||
|
||||
status, headers, body = stand.call("/api/large", encoding="gzip")
|
||||
check(
|
||||
status == 200 and headers.get("content-encoding") == "gzip", "Нет gzip для JSON"
|
||||
)
|
||||
check(gzip.decompress(body) == PAYLOAD, "gzip изменил содержимое")
|
||||
check(len(body) < len(PAYLOAD), "gzip не уменьшил тестовый ответ")
|
||||
check(
|
||||
"accept-encoding" in headers.get("vary", "").lower(),
|
||||
"Нет Vary: Accept-Encoding",
|
||||
)
|
||||
check(stand.call("/api/large")[2] == PAYLOAD, "Ответ без gzip изменён")
|
||||
small = stand.call("/health/live", encoding="gzip")
|
||||
check(
|
||||
small[0] == 200 and "content-encoding" not in small[1], "Маленький ответ сжат"
|
||||
)
|
||||
print(f"PASS: gzip {len(PAYLOAD)} → {len(body)} байт, содержимое сохранено")
|
||||
|
||||
limited = stand.call("/api/limited")
|
||||
check_error(limited, 429, "rate_limited")
|
||||
check(limited[1].get("retry-after") == "7", "Подменён Retry-After приложения")
|
||||
check("x-instance-id" in limited[1], "Потерян id backend на ошибке API")
|
||||
print("PASS: JSON и заголовки ошибки API передаются без подмены")
|
||||
|
||||
failure = stand.call("/api/post-failure", method="POST")
|
||||
check_error(failure, 503, "unavailable")
|
||||
backend_logs = stand.compose("logs", "--no-color", "--no-log-prefix", "api")
|
||||
check(backend_logs.count("BACKEND POST /api/post-failure") == 1, "POST повторился")
|
||||
print("PASS: отправленный POST не повторяется на другой реплике")
|
||||
|
||||
with ThreadPoolExecutor(max_workers=32) as pool:
|
||||
responses = list(pool.map(lambda _: stand.call("/api/large"), range(500)))
|
||||
rejected = [response for response in responses if response[0] == 429]
|
||||
check(bool(rejected), "Не удалось вызвать ограничение частоты")
|
||||
check(
|
||||
all(response[0] in (200, 429) for response in responses), "Ошибка при нагрузке"
|
||||
)
|
||||
for response in rejected:
|
||||
check_error(response, 429, "rate_limited")
|
||||
check(response[1].get("retry-after") == "1", "Нет Retry-After балансировщика")
|
||||
check("x-instance-id" not in response[1], "LB выдал себя за API-реплику")
|
||||
with ThreadPoolExecutor(max_workers=16) as pool:
|
||||
health = list(pool.map(lambda _: stand.call("/health/ready"), range(100)))
|
||||
check(all(response[0] == 200 for response in health), "Лимит затронул health")
|
||||
check(stand.call("/lb-health")[0] == 200, "Проверка LB недоступна")
|
||||
print(f"PASS: лимит вернул {len(rejected)} ответов 429; health доступен")
|
||||
|
||||
stand.compose(
|
||||
"up", "-d", "--pull", "never", "--scale", "api=3", "--no-recreate", "api"
|
||||
)
|
||||
instances = stand.wait_instances(3)
|
||||
print("PASS: третья реплика обнаружена через DNS без reload nginx")
|
||||
|
||||
target = sorted(instances)[0]
|
||||
containers = stand.compose("ps", "-q", "api").splitlines()
|
||||
matching = [container for container in containers if container.startswith(target)]
|
||||
check(len(matching) == 1, "Не найдена тестовая реплика для остановки")
|
||||
# Все id взяты только из уникального временного Compose-проекта.
|
||||
started = time.monotonic()
|
||||
subprocess.run(
|
||||
["docker", "stop", "--time", "1", matching[0]], check=True, capture_output=True
|
||||
)
|
||||
recovery = None
|
||||
for _ in range(20):
|
||||
status, headers, _ = stand.call("/health/live")
|
||||
if status == 200:
|
||||
check(headers["x-instance-id"] != target, "Остановленная реплика отвечает")
|
||||
if recovery is None:
|
||||
recovery = time.monotonic() - started
|
||||
check(recovery is not None and recovery < 10, "Чтение не восстановилось за 10 с")
|
||||
print(f"PASS: отказ реплики, первое успешное чтение через {recovery:.3f} с")
|
||||
|
||||
stand.compose("stop", "--timeout", "1", "api")
|
||||
unavailable = stand.call("/health/ready")
|
||||
check_error(unavailable, 503, "unavailable")
|
||||
check(
|
||||
unavailable[1].get("retry-after") == "1", "Нет Retry-After при отказе всех API"
|
||||
)
|
||||
check("x-instance-id" not in unavailable[1], "У ошибки LB есть id реплики")
|
||||
check(stand.call("/lb-health")[0] == 200, "Отказ API сломал проверку самого LB")
|
||||
print("PASS: недоступность всех backend возвращает JSON 503")
|
||||
|
||||
logs = stand.compose("logs", "--no-color", "--no-log-prefix", "nginx")
|
||||
entries = [json.loads(line) for line in logs.splitlines() if line.startswith("{")]
|
||||
check(bool(entries), "Нет JSON access log")
|
||||
check(
|
||||
all("request_id" in entry and "upstream_time" in entry for entry in entries),
|
||||
"Неполный лог",
|
||||
)
|
||||
check(
|
||||
any(entry["limit_status"] == "REJECTED" for entry in entries),
|
||||
"Лимит не отражён в логе",
|
||||
)
|
||||
print("PASS: JSON access log содержит время backend и результат лимита")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
with tempfile.TemporaryDirectory(prefix="mtusi-lab3-nginx-check-") as directory:
|
||||
stand = Stand(directory)
|
||||
try:
|
||||
run_checks(stand)
|
||||
except Exception:
|
||||
print(stand.compose("logs", "--no-color", "--tail", "20"), flush=True)
|
||||
raise
|
||||
finally:
|
||||
stand.compose("down", "--remove-orphans", "--timeout", "1")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,107 @@
|
||||
"""Общие операции с репликами текущего Compose-проекта."""
|
||||
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import ssl
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.request import urlopen
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Replica:
|
||||
"""Состояние контейнера API."""
|
||||
|
||||
id: str
|
||||
image: str
|
||||
instance_id: str
|
||||
running: bool
|
||||
health: str | None
|
||||
|
||||
|
||||
class ComposeProject:
|
||||
"""Работает только с выбранным Compose-проектом."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.command = ["docker", "compose", "--env-file", ".env"]
|
||||
self.config = json.loads(self.run("config", "--format", "json"))
|
||||
self.name = self.config["name"]
|
||||
|
||||
def docker(self, *args: str, timeout: int = 90, env=None) -> str:
|
||||
"""Выполняет Docker-команду с ограничением времени."""
|
||||
result = subprocess.run(
|
||||
["docker", *args], cwd=ROOT, text=True, capture_output=True,
|
||||
timeout=timeout, env={**os.environ, **(env or {})},
|
||||
)
|
||||
if result.returncode:
|
||||
raise RuntimeError(result.stderr.strip() or result.stdout.strip())
|
||||
return result.stdout.strip()
|
||||
|
||||
def run(self, *args: str, timeout: int = 90, env=None) -> str:
|
||||
"""Выполняет команду Compose с текущими overrides."""
|
||||
return self.docker(*self.command[1:], *args, timeout=timeout, env=env)
|
||||
|
||||
def replicas(self) -> list[Replica]:
|
||||
"""Читает состояние API без окружения контейнеров."""
|
||||
ids = self.run("ps", "--all", "--quiet", "api").splitlines()
|
||||
if not ids:
|
||||
return []
|
||||
template = (
|
||||
'{"id":{{json .Id}},"image":{{json .Image}},'
|
||||
'"hostname":{{json .Config.Hostname}},"running":{{json .State.Running}},'
|
||||
'"health":{{if .State.Health}}{{json .State.Health.Status}}{{else}}null{{end}}}'
|
||||
)
|
||||
rows = self.docker("inspect", "--format", template, *ids).splitlines()
|
||||
configured = str(self.config["services"]["api"].get("environment", {}).get("INSTANCE_ID") or "").strip()
|
||||
return [
|
||||
Replica(row["id"], row["image"], configured or row["hostname"], row["running"], row["health"])
|
||||
for row in map(json.loads, rows)
|
||||
]
|
||||
|
||||
def wait_healthy(self, ids: set[str], timeout: float = 40) -> None:
|
||||
"""Ожидает готовность конкретных реплик."""
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
current = {replica.id: replica for replica in self.replicas()}
|
||||
if not ids <= current.keys():
|
||||
raise RuntimeError("Контейнер API исчез во время развёртывания")
|
||||
if all(current[id].running and current[id].health == "healthy" for id in ids):
|
||||
return
|
||||
if any(not current[id].running for id in ids):
|
||||
raise RuntimeError("Контейнер API завершился до готовности")
|
||||
time.sleep(0.25)
|
||||
raise TimeoutError("API не стал healthy за отведённое время")
|
||||
|
||||
def wait_routed(self, instance_id: str, base_url: str, ca_file=None) -> None:
|
||||
"""Ожидает ответа реплики через балансировщик."""
|
||||
context = ssl.create_default_context(cafile=ca_file)
|
||||
deadline = time.monotonic() + 40
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
with urlopen(base_url.rstrip("/") + "/health/live", timeout=3, context=context) as response:
|
||||
if response.status == 200 and response.headers.get("X-Instance-Id") == instance_id:
|
||||
return
|
||||
except (HTTPError, URLError, TimeoutError, OSError):
|
||||
pass
|
||||
time.sleep(0.1)
|
||||
raise TimeoutError("Реплика не появилась в ответах балансировщика")
|
||||
|
||||
|
||||
@contextmanager
|
||||
def deployment_lock(project: ComposeProject):
|
||||
"""Исключает параллельные изменения одного стенда."""
|
||||
path = Path(tempfile.gettempdir()) / f"{project.name}-deployment.lock"
|
||||
with path.open("a") as lock:
|
||||
try:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError:
|
||||
raise RuntimeError("Другой процесс уже изменяет этот Compose-проект") from None
|
||||
yield
|
||||
@@ -0,0 +1,148 @@
|
||||
"""Сценарий поочерёдного отказа всех API-реплик под записью."""
|
||||
|
||||
from collections import Counter
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
from threading import Event, Lock
|
||||
import time
|
||||
from urllib.parse import quote
|
||||
from uuid import uuid4
|
||||
|
||||
from scripts.deployment import ComposeProject, ROOT, deployment_lock
|
||||
from tests.client import Client, Failure, arguments, check, run
|
||||
|
||||
|
||||
def failure_kind(error: Failure) -> str:
|
||||
"""Различает HTTP-отказы, ошибки соединения и проверки контракта."""
|
||||
match = re.search(r"received (\d{3})$", str(error))
|
||||
if match:
|
||||
return "http_" + match.group(1)
|
||||
return "connection" if "connection/TLS failure" in str(error) else "contract"
|
||||
|
||||
|
||||
def snapshot(project: ComposeProject, phase: str, target: str) -> list:
|
||||
"""Печатает состояние API без окружения и секретов."""
|
||||
replicas = project.replicas()
|
||||
print(json.dumps({
|
||||
"scenario": "replica_failure", "phase": phase, "target": target,
|
||||
"replicas": [{"instance": item.instance_id, "running": item.running, "health": item.health} for item in replicas],
|
||||
}), flush=True)
|
||||
return replicas
|
||||
|
||||
|
||||
def history(client: Client, actor: dict, chat: dict) -> list[dict]:
|
||||
"""Читает всю историю без повторов курсора."""
|
||||
path = f"/api/v1/chats/{chat['id']}/messages?limit=100"
|
||||
items = []
|
||||
cursors = set()
|
||||
for _ in range(1000):
|
||||
page = client.call("GET", path, actor=actor, schema="MessagePage")["json"]
|
||||
items.extend(page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
return items
|
||||
check(cursor not in cursors, "cursor cycle")
|
||||
cursors.add(cursor)
|
||||
path = f"/api/v1/chats/{chat['id']}/messages?limit=100&cursor={quote(cursor, safe='')}"
|
||||
raise Failure("history exceeded safety bound")
|
||||
|
||||
|
||||
def exercise(project: ComposeProject, args) -> None:
|
||||
"""Останавливает каждую реплику и восстанавливает её перед следующей."""
|
||||
replicas = project.replicas()
|
||||
check(len(replicas) >= 2, "at least two API replicas are required")
|
||||
project.wait_healthy({item.id for item in replicas})
|
||||
client = Client(args.base_url, args.ca_file, timeout=2)
|
||||
for item in replicas:
|
||||
project.wait_routed(item.instance_id, client.base, args.ca_file)
|
||||
actor, _, _, chat = client.bootstrap()
|
||||
confirmed = set()
|
||||
|
||||
for target in replicas:
|
||||
snapshot(project, "before", target.instance_id)
|
||||
stop = Event()
|
||||
lock = Lock()
|
||||
successes = []
|
||||
errors = []
|
||||
|
||||
def worker():
|
||||
local = Client(client.base, args.ca_file, timeout=2)
|
||||
key = uuid4().hex
|
||||
while not stop.is_set():
|
||||
started = time.monotonic()
|
||||
try:
|
||||
result = local.message(actor, chat, "failover-" + key, key=key)
|
||||
with lock:
|
||||
successes.append((started, time.monotonic(), result["json"]["id"]))
|
||||
key = uuid4().hex
|
||||
except Failure as error:
|
||||
with lock:
|
||||
errors.append(failure_kind(error))
|
||||
time.sleep(0.1)
|
||||
|
||||
started = time.monotonic()
|
||||
with ThreadPoolExecutor(max_workers=args.concurrency) as pool:
|
||||
jobs = [pool.submit(worker) for _ in range(args.concurrency)]
|
||||
try:
|
||||
time.sleep(2)
|
||||
stop_started = time.monotonic()
|
||||
subprocess.run(
|
||||
[str(ROOT / "scripts/stop-one.sh")], cwd=ROOT,
|
||||
env={**os.environ, "TARGET_INSTANCE_ID": target.instance_id},
|
||||
check=True, timeout=10, capture_output=True,
|
||||
)
|
||||
stop_finished = time.monotonic()
|
||||
stopped = snapshot(project, "stopped", target.instance_id)
|
||||
check(any(item.id == target.id and not item.running for item in stopped), "target API was not stopped")
|
||||
check(any(item.id != target.id and item.running and item.health == "healthy" for item in stopped), "no healthy surviving API")
|
||||
time.sleep(args.duration)
|
||||
finally:
|
||||
stop.set()
|
||||
try:
|
||||
for job in jobs:
|
||||
job.result(timeout=5)
|
||||
finally:
|
||||
project.docker("start", target.id)
|
||||
project.wait_healthy({item.id for item in replicas})
|
||||
project.wait_routed(target.instance_id, client.base, args.ca_file)
|
||||
snapshot(project, "restored", target.instance_id)
|
||||
|
||||
elapsed = max(end for _, end, _ in successes) - started if successes else 0
|
||||
recovered = [end for begin, end, _ in successes if begin >= stop_finished]
|
||||
check(bool(recovered), "no confirmed writes after failure")
|
||||
recovery = min(recovered) - stop_started
|
||||
check(recovery <= 10, "writes did not recover within 10 seconds")
|
||||
confirmed.update(id for _, _, id in successes)
|
||||
items = history(client, actor, chat)
|
||||
check(confirmed <= {item["id"] for item in items}, "confirmed messages were lost")
|
||||
texts = [item["text"] for item in items]
|
||||
check(len(texts) == len(set(texts)), "uncertain retry created duplicates")
|
||||
print(json.dumps({
|
||||
"instance": target.instance_id,
|
||||
"successful_writes": len(successes),
|
||||
"failed_attempts": len(errors),
|
||||
"errors_by_kind": dict(Counter(errors)),
|
||||
"elapsed_seconds": round(elapsed, 3),
|
||||
"successful_rps": round(len(successes) / elapsed, 3) if elapsed else 0,
|
||||
"first_recovery_seconds": round(recovery, 3),
|
||||
}), flush=True)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""Готовит параметры эксперимента отказа реплик."""
|
||||
def configure(parser):
|
||||
parser.add_argument("--duration", type=float, default=15)
|
||||
parser.add_argument("--concurrency", type=int, default=2)
|
||||
|
||||
args = arguments("Fail each API replica under write load", configure)
|
||||
check(1 <= args.duration <= 120 and 1 <= args.concurrency <= 8, "invalid workload")
|
||||
project = ComposeProject()
|
||||
with deployment_lock(project):
|
||||
exercise(project, args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Подготавливает локальные файлы Docker secrets."""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
|
||||
from pydantic import SecretStr
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
class ExistingSecrets(BaseSettings):
|
||||
"""Читает прежние пароли без вывода значений."""
|
||||
|
||||
db_password: SecretStr | None = None
|
||||
redis_password: SecretStr | None = None
|
||||
model_config = SettingsConfigDict(env_file=ROOT / ".env", extra="ignore")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""Создаёт отсутствующие файлы, сохраняя существующие значения."""
|
||||
directory = ROOT / "secrets"
|
||||
directory.mkdir(mode=0o700, exist_ok=True)
|
||||
directory.chmod(0o700)
|
||||
existing = ExistingSecrets()
|
||||
for name in ("db_password", "redis_password"):
|
||||
path = directory / name
|
||||
if path.is_symlink():
|
||||
raise RuntimeError(f"Секрет {name} не должен быть символьной ссылкой")
|
||||
if path.exists() and not path.is_file():
|
||||
raise RuntimeError(f"Секрет {name} должен быть обычным файлом")
|
||||
if not path.exists():
|
||||
previous = getattr(existing, name)
|
||||
value = previous.get_secret_value() if previous else secrets.token_urlsafe(32)
|
||||
if not value or value.strip() != value or "\n" in value or "\r" in value:
|
||||
raise ValueError(f"Секрет {name} должен занимать одну строку без крайних пробелов")
|
||||
descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||||
with os.fdopen(descriptor, "w") as file:
|
||||
file.write(value + "\n")
|
||||
path.chmod(0o444)
|
||||
print(f"Готов файл secrets/{name}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,6 +1,4 @@
|
||||
#!/bin/sh
|
||||
# Перезапуск API и всех хранилищ с сохранением volumes (make test-persistence).
|
||||
# У api несколько реплик, перед ними nginx.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
@@ -8,7 +6,6 @@ compose() {
|
||||
docker compose --env-file .env "$@"
|
||||
}
|
||||
|
||||
# Ждёт, пока ВСЕ контейнеры service станут healthy (у api их несколько).
|
||||
wait_healthy() {
|
||||
for service in "$@"; do
|
||||
attempts=0
|
||||
@@ -29,7 +26,5 @@ compose restart postgres redis
|
||||
wait_healthy postgres redis
|
||||
compose restart api
|
||||
wait_healthy api
|
||||
# TODO(3.3): если nginx перерезолвит DNS сам, рестарт LB не обязателен —
|
||||
# но перезапуск «всего стенда» в защите всё равно его включает.
|
||||
compose restart nginx
|
||||
wait_healthy nginx
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
"""Поочерёдно заменяет API с одной дополнительной репликой."""
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
|
||||
from scripts.deployment import ComposeProject, deployment_lock
|
||||
|
||||
|
||||
def update(project: ComposeProject, base_url: str, ca_file=None, revision: str | None = None) -> None:
|
||||
"""Собирает образ, применяет миграции и заменяет реплики."""
|
||||
original = project.replicas()
|
||||
if len(original) < 2 or any(not item.running or item.health != "healthy" for item in original):
|
||||
raise RuntimeError("До обновления нужны минимум две здоровые API-реплики")
|
||||
old_images = {item.image for item in original}
|
||||
if len(old_images) != 1:
|
||||
raise RuntimeError("Сначала восстановите единый образ работающих реплик")
|
||||
old_image = old_images.pop()
|
||||
profile = project.docker(
|
||||
"image", "inspect", old_image,
|
||||
"--format", '{{index .Config.Labels "io.mtusi.messenger.secrets"}}',
|
||||
)
|
||||
if profile != "file-v1":
|
||||
raise RuntimeError("Сначала выполните первоначальный переход на файловые секреты через make up")
|
||||
count = len(original)
|
||||
print("Сборка нового образа API", flush=True)
|
||||
build_args = ("--build-arg", f"API_BUILD_REVISION={revision}") if revision else ()
|
||||
project.run("build", *build_args, "api", timeout=300)
|
||||
tag = project.config["services"]["api"]["image"]
|
||||
new_image = project.docker("image", "inspect", tag, "--format", "{{.Id}}")
|
||||
print("Однократное применение совместимых миграций", flush=True)
|
||||
project.run("run", "--rm", "--no-deps", "--pull", "never", "migrate")
|
||||
if old_image == new_image:
|
||||
print("Образ не изменился; замена контейнеров не требуется")
|
||||
return
|
||||
|
||||
try:
|
||||
for old in original:
|
||||
project.run(
|
||||
"up", "-d", "--no-deps", "--no-build", "--pull", "never",
|
||||
"--no-recreate", "--scale", f"api={count + 1}", "api",
|
||||
)
|
||||
current = project.replicas()
|
||||
additions = [item for item in current if item.id not in {replica.id for replica in original} and item.image == new_image]
|
||||
if not additions:
|
||||
raise RuntimeError("Новая реплика не создана")
|
||||
project.wait_healthy({item.id for item in additions})
|
||||
for added in additions:
|
||||
project.wait_routed(added.instance_id, base_url, ca_file)
|
||||
survivors = {item.id for item in project.replicas() if item.id != old.id}
|
||||
project.wait_healthy(survivors)
|
||||
project.docker("stop", old.id)
|
||||
project.docker("rm", old.id)
|
||||
print(f"Заменена реплика {old.instance_id}", flush=True)
|
||||
final = project.replicas()
|
||||
if len(final) != count or any(item.image != new_image for item in final):
|
||||
raise RuntimeError("Состав реплик после обновления не соответствует плану")
|
||||
project.wait_healthy({item.id for item in final})
|
||||
except Exception:
|
||||
print("Обновление прервано; восстанавливается прежний образ без отката БД", file=sys.stderr)
|
||||
project.run(
|
||||
"up", "-d", "--no-deps", "--no-build", "--pull", "never",
|
||||
"--force-recreate", "--scale", f"api={count}", "api",
|
||||
env={"API_IMAGE": old_image},
|
||||
)
|
||||
project.wait_healthy({item.id for item in project.replicas()})
|
||||
raise
|
||||
|
||||
dangling = project.docker("image", "ls", "--quiet", "--no-trunc", "--filter", "dangling=true").splitlines()
|
||||
if old_image in dangling:
|
||||
references = project.docker("ps", "--all", "--quiet", "--filter", f"ancestor={old_image}")
|
||||
if not references:
|
||||
try:
|
||||
project.docker("image", "rm", old_image)
|
||||
except RuntimeError:
|
||||
print("Прежний образ не удалён: состояние Docker изменилось", file=sys.stderr)
|
||||
print(f"Готово: {count} здоровых реплик нового образа")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""Запускает обновление с блокировкой проекта."""
|
||||
parser = argparse.ArgumentParser(description="Rolling update of API replicas")
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
parser.add_argument("--ca-file", default=None)
|
||||
parser.add_argument("--revision", default=None)
|
||||
args = parser.parse_args()
|
||||
project = ComposeProject()
|
||||
with deployment_lock(project):
|
||||
update(project, args.base_url or "http://localhost:8080", args.ca_file, args.revision)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+24
-15
@@ -1,21 +1,30 @@
|
||||
#!/bin/sh
|
||||
# Останавливает одну API-реплику по TARGET_INSTANCE_ID (сценарий отказа, make test-failover).
|
||||
# TODO(3.5): реализовать — см. docs/LAB3_TASKS.md, задача 3.5.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
|
||||
|
||||
# Что нужно сделать:
|
||||
# 1. Сопоставить TARGET_INSTANCE_ID (значение X-Instance-Id) с контейнером.
|
||||
# Проще всего, если X-Instance-Id = короткий id контейнера (HOSTNAME):
|
||||
# docker compose --env-file .env ps -q api -> полные id реплик api
|
||||
# и найти тот, что начинается с TARGET_INSTANCE_ID.
|
||||
# 2. Убедиться, что это контейнер service `api` ЭТОГО compose-проекта,
|
||||
# а не postgres/nginx/чужой контейнер. Не нашли -> exit 1.
|
||||
# 3. Остановить его (docker stop [-t N]) и оставить остановленным.
|
||||
# Не трогать БД/LB/volumes. Уложиться в 10 секунд.
|
||||
# 4. Напечатать (в stderr), что именно остановлено — пригодится для отчёта.
|
||||
# Восстановление — отдельно: make restore.
|
||||
case "$TARGET_INSTANCE_ID" in
|
||||
*[!a-zA-Z0-9_.:-]*|'') exit 1 ;;
|
||||
esac
|
||||
|
||||
echo 'TODO: implement stop-one.sh' >&2
|
||||
exit 2
|
||||
target=""
|
||||
for container in $(docker compose --env-file .env ps -q api); do
|
||||
hostname=$(docker inspect --format '{{.Config.Hostname}}' "$container")
|
||||
configured=$(docker inspect --format '{{range .Config.Env}}{{if eq (index (split . "=") 0) "INSTANCE_ID"}}{{println .}}{{end}}{{end}}' "$container" \
|
||||
| sed -n 's/^INSTANCE_ID=//p' | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
|
||||
if [ "$TARGET_INSTANCE_ID" = "$hostname" ] || [ "$TARGET_INSTANCE_ID" = "$configured" ]; then
|
||||
if [ -n "$target" ]; then
|
||||
echo 'Instance id matches multiple API containers' >&2
|
||||
exit 1
|
||||
fi
|
||||
target="$container"
|
||||
fi
|
||||
done
|
||||
|
||||
if [ -z "$target" ]; then
|
||||
echo 'Target API instance not found in this Compose project' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Stopping API container $target" >&2
|
||||
docker stop --timeout 8 "$target" >/dev/null
|
||||
|
||||
Reference in New Issue
Block a user