ЛР5: устойчивый versioned pipeline изображений, outbox и доказательства отказов

This commit is contained in:
2026-11-06 18:27:29 +03:00
parent 276dbdad8a
commit 7f51c6ac3b
78 changed files with 7278 additions and 65 deletions
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/env python3
"""Create a private local secret directory once; never rotate existing volumes implicitly."""
import os
import json
import secrets
from pathlib import Path
root = Path(__file__).resolve().parents[1]
private = root / "secrets"
private.mkdir(mode=0o700, exist_ok=True)
os.chmod(private, 0o700)
password_file = private / "postgres_password"
if not password_file.exists():
password_file.write_text(secrets.token_urlsafe(32))
password = password_file.read_text().strip()
broker_password_file = private / "broker_password"
if not broker_password_file.exists():
broker_password_file.write_text(secrets.token_urlsafe(32))
broker_password = broker_password_file.read_text().strip()
values = {
"database_url": "postgresql://messenger:" + password + "@postgres:5432/messenger",
"cache_url": "redis://cache:6379/0",
"broker_url": "redis://:" + broker_password + "@broker:6379/0",
"broker_config": "bind 0.0.0.0\nprotected-mode yes\nrequirepass " + broker_password + "\nappendonly yes\nappendfsync always\nsave \"\"\ndir /data\nmaxmemory 128mb\nmaxmemory-policy noeviction\n",
"s3_access_key": "app-" + secrets.token_hex(10),
"s3_secret_key": secrets.token_urlsafe(32),
"s3_admin_access_key": "admin-" + secrets.token_hex(10),
"s3_admin_secret_key": secrets.token_urlsafe(32),
}
for name, value in values.items():
path = private / name
if not path.exists():
path.write_text(value)
config = private / "s3_config"
if not config.exists():
config.write_text(json.dumps({"identities": [
{"name": "bootstrap", "credentials": [{"accessKey": (private / "s3_admin_access_key").read_text(),
"secretKey": (private / "s3_admin_secret_key").read_text()}], "actions": ["Admin", "Read", "Write", "List"]},
{"name": "api", "credentials": [{"accessKey": (private / "s3_access_key").read_text(),
"secretKey": (private / "s3_secret_key").read_text()}], "actions": ["Read:messenger", "Write:messenger", "List:messenger"]}
]}))
# The parent directory is private on the host; files must be readable by non-root API
# through Compose's file-backed secret mount (uid/mode mapping is not portable).
for path in private.iterdir():
os.chmod(path, 0o644)
if not (root / ".env").exists():
(root / ".env").write_text("PUBLIC_PORT=8085\nSESSION_TTL_SECONDS=3600\n")
print("Local configuration ready; existing secret values preserved.")
+5
View File
@@ -0,0 +1,5 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
docker compose restart postgres cache broker storage s3 api lb dispatcher worker
docker compose up -d --wait --no-recreate
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
python3 scripts/stop_one.py
+22
View File
@@ -0,0 +1,22 @@
"""Map a process alias to its real container, then leave exactly it stopped."""
import json
import os
import subprocess
from pathlib import Path
wanted = os.environ["TARGET_INSTANCE_ID"]
ids = subprocess.check_output(["docker", "compose", "ps", "-q", "api"], text=True).split()
for cid in ids:
result = subprocess.run(
["docker", "exec", cid, "python", "-c",
"import urllib.request; r=urllib.request.urlopen('http://127.0.0.1:8080/health/live'); print(r.headers['X-Instance-Id'])"],
text=True, capture_output=True, check=False,
)
if result.returncode == 0 and result.stdout.strip() == wanted:
subprocess.run(["docker", "stop", "--time", "8", cid], check=True, stdout=subprocess.DEVNULL)
receipt = {"stopped_container": cid, "instance_id": wanted}
Path("evidence/last-stopped.json").write_text(json.dumps(receipt))
print(json.dumps(receipt))
break
else:
raise SystemExit("Target instance not found among this project's API containers")
+46
View File
@@ -0,0 +1,46 @@
"""Check the LB's own safe JSON error when every API is stopped, then recover."""
import json
import subprocess
import sys
import time
import urllib.error
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client
def main():
c = Client("http://127.0.0.1:8085")
actor = c.user("lbdown")
subprocess.run(["docker", "compose", "stop", "api"], cwd=ROOT, check=True)
try:
time.sleep(4)
request = urllib.request.Request(c.base + "/api/v1/users/me",
headers={"Authorization": "Bearer " + actor["token"]})
try:
response = urllib.request.urlopen(request, timeout=3)
except urllib.error.HTTPError as exc:
response = exc
with response:
body = json.loads(response.read())
result = {"status": response.code, "body": body,
"request_id": response.headers.get("X-Request-Id"),
"instance_id": response.headers.get("X-Instance-Id")}
assert result["status"] == 503
assert body["error"]["code"] == "unavailable"
assert result["request_id"] and body["error"]["request_id"] == result["request_id"]
assert result["instance_id"] is None
finally:
subprocess.run(["docker", "compose", "start", "api"], cwd=ROOT, check=True)
subprocess.run([sys.executable, "scripts/wait_replicas.py", "2"], cwd=ROOT, check=True)
c.call("GET", "/api/v1/users/me", actor=actor, schema="User")
result["recovered_existing_session"] = True
(ROOT / "evidence/lb-no-ready-api.json").write_text(json.dumps(result, indent=2) + "\n")
print(json.dumps(result, indent=2))
if __name__ == "__main__":
main()
+23
View File
@@ -0,0 +1,23 @@
"""Compare actual container source bytes to the repository and fault-study image."""
import hashlib
import json
import subprocess
from pathlib import Path
ids = subprocess.check_output(["docker", "compose", "ps", "-q", "api"], text=True).split()
assert ids
probe = "import hashlib,json,pathlib; p=pathlib.Path('/app/src/messenger'); print(json.dumps({x.name:hashlib.sha256(x.read_bytes()).hexdigest() for x in sorted(p.glob('*.py'))}))"
actual = json.loads(subprocess.check_output(["docker", "exec", ids[0], "python", "-c", probe], text=True))
expected = {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted(Path("src/messenger").glob("*.py"))}
assert actual == expected, "Runtime source differs from repository"
old = json.loads(Path("evidence/fault-runtime-source.json").read_text())
changed = sorted(name for name, digest in actual.items() if digest != old["source_sha256"].get(name))
assert set(changed) <= {"domain.py"}, changed
result = {"runtime_container_id": ids[0], "runtime_source_sha256": actual,
"fault_image_id": old["image_id"], "changed_after_fault_image": changed,
"pipeline_modules_identical": True,
"explanation": "Only shared cursor parsing was tightened after fault tests; complete final HTTP suite checks it. All pipeline/outbox/storage modules are byte-identical.",
"passed": True}
Path("evidence/runtime-source.json").write_text(json.dumps(result, indent=2))
print("PASS: runtime matches repository; fault-tested pipeline modules are identical")
+71
View File
@@ -0,0 +1,71 @@
"""Record real restart scope and exercise failover of both physical API containers."""
import json
import os
import subprocess
from pathlib import Path
def run(args):
result = subprocess.run(args, text=True, capture_output=True, timeout=180)
if result.returncode:
raise RuntimeError("Verification failed:\n" + result.stdout + result.stderr[-2000:])
return result
def snapshot():
ids = run(["docker", "compose", "ps", "-aq"]).stdout.split()
items = json.loads(run(["docker", "inspect", *ids]).stdout)
return [
{"id": item["Id"], "service": item["Config"]["Labels"]["com.docker.compose.service"],
"started_at": item["State"]["StartedAt"], "status": item["State"]["Status"],
"mounts": [{"type": mount["Type"], "name": mount.get("Name"), "destination": mount["Destination"]}
for mount in item["Mounts"] if mount["Type"] == "volume"]}
for item in items
]
def main():
base = os.getenv("BASE_URL", "http://127.0.0.1:8085")
before = snapshot()
result = run(["python3", "tests/resilience.py", "--mode", "persistence", "--action-script", "scripts/restart.sh", "--base-url", base])
Path("evidence/persistence-final.txt").write_text(result.stdout)
after = snapshot()
changed = []
by_id = {item["id"]: item for item in before}
for item in after:
old = by_id.get(item["id"])
if old and old["started_at"] != item["started_at"]:
changed.append(item["service"])
required = {"postgres", "cache", "broker", "storage", "s3", "api", "lb", "worker", "dispatcher"}
assert required <= set(changed), (required, changed)
assert {json.dumps(m, sort_keys=True) for i in before for m in i["mounts"]} == {json.dumps(m, sort_keys=True) for i in after for m in i["mounts"]}
Path("evidence/persistence-runtime.json").write_text(json.dumps({"before": before, "after": after, "restarted_services": changed, "volumes_unchanged": True, "passed": True}, indent=2))
actual_api = {item["id"] for item in after if item["service"] == "api"}
assert len(actual_api) >= 2
stopped = set()
attempts = []
try:
for _ in range(6):
result = run(["python3", "tests/resilience.py", "--mode", "failover", "--action-script", "scripts/stop-one.sh", "--base-url", base])
receipt = json.loads(Path("evidence/last-stopped.json").read_text())
assert receipt["stopped_container"] in actual_api
state = json.loads(run(["docker", "inspect", receipt["stopped_container"]]).stdout)[0]
assert not state["State"]["Running"]
summaries = [json.loads(line) for line in result.stdout.splitlines() if line.startswith("{")]
attempts.append({"stopped": receipt, "summary": summaries, "stdout": result.stdout})
stopped.add(receipt["stopped_container"])
run(["docker", "compose", "start", "api"])
run(["docker", "compose", "up", "-d", "--no-recreate", "--wait", "api", "lb"])
if stopped == actual_api:
break
assert stopped == actual_api, "Both physical replicas were not covered"
finally:
run(["docker", "compose", "start", "api"])
Path("evidence/failover-final.json").write_text(json.dumps({"actual_api_container_ids": sorted(actual_api), "covered_container_ids": sorted(stopped), "attempts": attempts, "passed": True}, indent=2))
print("PASS: full restart and failover of both physical API replicas")
if __name__ == "__main__":
main()
+21
View File
@@ -0,0 +1,21 @@
import os
import sys
import time
import urllib.error
import urllib.request
wanted = int(sys.argv[1])
url = "http://127.0.0.1:" + os.environ.get("PUBLIC_PORT", "8085") + "/health/ready"
deadline = time.monotonic() + 40
seen = set()
while time.monotonic() < deadline:
try:
with urllib.request.urlopen(url, timeout=2) as response:
seen.add(response.headers["X-Instance-Id"])
if len(seen) >= wanted:
break
except (urllib.error.URLError, TimeoutError):
seen.clear()
time.sleep(0.1)
else:
raise SystemExit("LB did not expose enough healthy replicas")