forked from mtusi2026/mtusi2026lab4
Добавить приватные вложения и безопасную сверку PostgreSQL и S3
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Create local synthetic credentials once, without printing their values."""
|
||||
|
||||
import os
|
||||
import secrets
|
||||
from pathlib import Path
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
directory = root / "secrets"
|
||||
directory.mkdir(mode=0o700, exist_ok=True)
|
||||
password_file = directory / "postgres_password"
|
||||
if not password_file.exists():
|
||||
password_file.write_text(secrets.token_urlsafe(32) + "\n")
|
||||
password = password_file.read_text().strip()
|
||||
for name, value in {
|
||||
"database_url": f"postgresql://messenger:{password}@postgres:5432/messenger",
|
||||
"cache_url": "redis://valkey:6379/0",
|
||||
}.items():
|
||||
path = directory / name
|
||||
if not path.exists():
|
||||
path.write_text(value + "\n")
|
||||
# Compose bind-mount secrets must be readable by the non-root container process.
|
||||
# The parent directory remains 0700 on the host.
|
||||
for role in ("root", "api", "reconciler", "test"):
|
||||
names = (
|
||||
("s3_root_user", "s3_root_password")
|
||||
if role == "root"
|
||||
else ("s3_" + role + "_access_key_id", "s3_" + role + "_secret_access_key")
|
||||
)
|
||||
for index, name in enumerate(names):
|
||||
path = directory / name
|
||||
if not path.exists():
|
||||
path.write_text(
|
||||
(secrets.token_hex(10) if index == 0 else secrets.token_urlsafe(32)) + "\n"
|
||||
)
|
||||
for name in (
|
||||
"postgres_password",
|
||||
"database_url",
|
||||
"cache_url",
|
||||
*[p.name for p in directory.glob("s3_*")],
|
||||
):
|
||||
os.chmod(directory / name, 0o644)
|
||||
env = root / ".env"
|
||||
if not env.exists():
|
||||
env.write_text((root / ".env.example").read_text())
|
||||
print("Local secret files and environment are ready; existing values preserved.")
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Read-only discovery and scoped Compose operations for the local lab4 stack."""
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def compose(*args, env=None):
|
||||
return subprocess.run(
|
||||
["docker", "compose", "--env-file", ".env", *args],
|
||||
cwd=ROOT,
|
||||
env=env,
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=90,
|
||||
).stdout
|
||||
|
||||
|
||||
def inspect(container):
|
||||
template = (
|
||||
'{"id":{{json .Id}},"started_at":{{json .State.StartedAt}},'
|
||||
'"pid":{{.State.Pid}},"running":{{json .State.Running}},'
|
||||
'"image":{{json .Image}},"memory":{{.HostConfig.Memory}},'
|
||||
'"nano_cpus":{{.HostConfig.NanoCpus}},'
|
||||
'"published_ports":{{json .HostConfig.PortBindings}}}'
|
||||
)
|
||||
r = subprocess.run(
|
||||
["docker", "inspect", "--format", template, container],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True,
|
||||
timeout=5,
|
||||
)
|
||||
return json.loads(r.stdout)
|
||||
|
||||
|
||||
def instance(container):
|
||||
code = (
|
||||
"import urllib.request; r=urllib.request.urlopen("
|
||||
"'http://127.0.0.1:8080/health/live',timeout=1); print(r.headers['X-Instance-Id'])"
|
||||
)
|
||||
r = subprocess.run(
|
||||
["docker", "exec", container, "python", "-c", code],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True,
|
||||
timeout=3,
|
||||
)
|
||||
value = inspect(container)
|
||||
value["instance"] = r.stdout.strip()
|
||||
return value
|
||||
|
||||
|
||||
def instances():
|
||||
ids = compose("ps", "-q", "api").split()
|
||||
with ThreadPoolExecutor(max_workers=8) as pool:
|
||||
return list(pool.map(instance, ids))
|
||||
|
||||
|
||||
def wait_lb(base="http://127.0.0.1:8084", count=2, timeout=45):
|
||||
deadline, seen = time.monotonic() + timeout, set()
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
current = {value["instance"] for value in instances()}
|
||||
if len(current) != count:
|
||||
time.sleep(0.2)
|
||||
continue
|
||||
with urllib.request.urlopen(base + "/health/ready", timeout=2) as response:
|
||||
seen.add(response.headers["X-Instance-Id"])
|
||||
if current <= seen:
|
||||
return sorted(current)
|
||||
except (OSError, urllib.error.URLError, subprocess.SubprocessError):
|
||||
pass
|
||||
time.sleep(0.1)
|
||||
raise RuntimeError("Expected healthy API replicas were not observed through LB")
|
||||
Executable
+5
@@ -0,0 +1,5 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
# All running application/state services; no migration, down -v, flush or seed.
|
||||
docker compose --env-file .env restart --timeout 7 api postgres valkey s3 lb
|
||||
@@ -0,0 +1,49 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Sequential process replacement; at least one existing API stays running."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import subprocess
|
||||
|
||||
from cluster import compose, instances, wait_lb
|
||||
|
||||
|
||||
def replace_all(base="http://127.0.0.1:8084"):
|
||||
original = instances()
|
||||
if len(original) < 2:
|
||||
raise RuntimeError("Rolling replacement requires at least two healthy replicas")
|
||||
wait_lb(base, len(original))
|
||||
replacements = []
|
||||
for current in original:
|
||||
subprocess.run(
|
||||
["docker", "stop", "--time", "5", current["id"]],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
timeout=8,
|
||||
)
|
||||
subprocess.run(["docker", "rm", current["id"]], check=True, capture_output=True)
|
||||
compose(
|
||||
"up", "-d", "--no-deps", "--no-recreate", "--scale", "api=" + str(len(original)), "api"
|
||||
)
|
||||
aliases = wait_lb(base, len(original))
|
||||
if current["instance"] in aliases:
|
||||
raise RuntimeError("Old API process is still serving after replacement")
|
||||
replacements.append(
|
||||
{
|
||||
"old_container": current["id"],
|
||||
"old_instance": current["instance"],
|
||||
"live_instances": aliases,
|
||||
}
|
||||
)
|
||||
return replacements
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--base-url", default="http://127.0.0.1:8084")
|
||||
args = parser.parse_args()
|
||||
print(json.dumps(replace_all(args.base_url)))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,48 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Map a process alias to ONE container belonging to this Compose service."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def alias(container):
|
||||
code = (
|
||||
"import urllib.request; r=urllib.request.urlopen("
|
||||
"'http://127.0.0.1:8080/health/live',timeout=1); print(r.headers['X-Instance-Id'])"
|
||||
)
|
||||
r = subprocess.run(
|
||||
["docker", "exec", container, "python", "-c", code],
|
||||
cwd=ROOT,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=3,
|
||||
check=True,
|
||||
)
|
||||
return container, r.stdout.strip()
|
||||
|
||||
|
||||
def main():
|
||||
target = os.environ.get("TARGET_INSTANCE_ID", "")
|
||||
if not re.fullmatch(r"[a-f0-9]{32}", target):
|
||||
raise SystemExit("TARGET_INSTANCE_ID must name a live API process")
|
||||
ids = subprocess.check_output(
|
||||
["docker", "compose", "ps", "-q", "api"], cwd=ROOT, text=True
|
||||
).split()
|
||||
with ThreadPoolExecutor(max_workers=8) as pool:
|
||||
matches = [cid for cid, identity in pool.map(alias, ids) if identity == target]
|
||||
if len(matches) != 1:
|
||||
raise SystemExit("Expected exactly one matching API in this project")
|
||||
subprocess.run(
|
||||
["docker", "stop", "--time", "5", matches[0]], check=True, capture_output=True, timeout=7
|
||||
)
|
||||
print(json.dumps({"stopped_container": matches[0], "instance": target}))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
exec python3 scripts/stop-one.py
|
||||
@@ -0,0 +1,45 @@
|
||||
"""Local-only operator helpers; secret values never leave this process."""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import psycopg
|
||||
from psycopg.conninfo import make_conninfo
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
from messenger.settings import Settings
|
||||
from messenger.storage import ObjectStore
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def settings(role="reconciler"):
|
||||
password = (ROOT / "secrets/postgres_password").read_text().strip()
|
||||
dsn = make_conninfo(
|
||||
host="127.0.0.1",
|
||||
port=55435,
|
||||
dbname="messenger",
|
||||
user="messenger",
|
||||
password=password,
|
||||
connect_timeout=2,
|
||||
options="-c timezone=UTC",
|
||||
)
|
||||
key, secret = (
|
||||
("s3_root_user", "s3_root_password")
|
||||
if role == "root"
|
||||
else ("s3_" + role + "_access_key_id", "s3_" + role + "_secret_access_key")
|
||||
)
|
||||
return Settings(
|
||||
dsn,
|
||||
"redis://127.0.0.1:56382/0",
|
||||
s3_access_key=(ROOT / "secrets" / key).read_text().strip(),
|
||||
s3_secret_key=(ROOT / "secrets" / secret).read_text().strip(),
|
||||
)
|
||||
|
||||
|
||||
def connection(config=None):
|
||||
config = config or settings()
|
||||
return psycopg.connect(config.database_url, autocommit=True, row_factory=dict_row)
|
||||
|
||||
|
||||
def store(role="reconciler"):
|
||||
return ObjectStore(settings(role))
|
||||
@@ -0,0 +1,253 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Real LB requests during each replica failure and sequential replacement."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
from cluster import ROOT, compose, inspect, instance, instances, wait_lb
|
||||
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure, check # noqa: E402
|
||||
from resilience import history # noqa: E402
|
||||
|
||||
|
||||
def percentile(values, fraction):
|
||||
values = sorted(values)
|
||||
return values[min(int((len(values) - 1) * fraction), len(values) - 1)] if values else None
|
||||
|
||||
|
||||
class Traffic:
|
||||
def __init__(self, base, actor, room, workers=6):
|
||||
self.base, self.actor, self.room = base, actor, room
|
||||
self.prefix = uuid4().hex
|
||||
self.stop = threading.Event()
|
||||
self.lock = threading.Lock()
|
||||
self.events = []
|
||||
self.executor = ThreadPoolExecutor(max_workers=workers)
|
||||
self.workers = workers
|
||||
|
||||
def worker(self, worker):
|
||||
client, iteration = Client(self.base, timeout=3), 0
|
||||
while not self.stop.is_set():
|
||||
started = time.monotonic()
|
||||
write = iteration % 10 == 9
|
||||
try:
|
||||
if write:
|
||||
key = f"{self.prefix}:{worker}:{iteration}"
|
||||
response = client.message(self.actor, self.room, key, key=key)
|
||||
else:
|
||||
response = client.call(
|
||||
"GET", "/api/v1/users/me", actor=self.actor, schema="User"
|
||||
)
|
||||
event = {
|
||||
"at": time.monotonic(),
|
||||
"ok": True,
|
||||
"instance": response["headers"]["X-Instance-Id"],
|
||||
"latency_ms": (time.monotonic() - started) * 1000,
|
||||
"message": response["json"] if write else None,
|
||||
}
|
||||
iteration += 1
|
||||
except Failure:
|
||||
event = {
|
||||
"at": time.monotonic(),
|
||||
"ok": False,
|
||||
"latency_ms": (time.monotonic() - started) * 1000,
|
||||
}
|
||||
with self.lock:
|
||||
self.events.append(event)
|
||||
|
||||
def __enter__(self):
|
||||
self.started = time.monotonic()
|
||||
self.futures = [self.executor.submit(self.worker, i) for i in range(self.workers)]
|
||||
return self
|
||||
|
||||
def __exit__(self, *args):
|
||||
self.stop.set()
|
||||
self.executor.shutdown(wait=True)
|
||||
for future in self.futures:
|
||||
future.result()
|
||||
self.finished = time.monotonic()
|
||||
|
||||
def report(self, action_start, action_end):
|
||||
events = sorted(self.events, key=lambda row: row["at"])
|
||||
ok = [row for row in events if row["ok"]]
|
||||
after = [row for row in ok if row["at"] >= action_end]
|
||||
check(bool(after), "No successful request after action")
|
||||
elapsed = self.finished - self.started
|
||||
latency = [row["latency_ms"] for row in ok]
|
||||
return {
|
||||
"duration_seconds": elapsed,
|
||||
"workers": self.workers,
|
||||
"requests": len(events),
|
||||
"successes": len(ok),
|
||||
"errors": len(events) - len(ok),
|
||||
"successful_rps": len(ok) / elapsed,
|
||||
"error_fraction": (len(events) - len(ok)) / len(events),
|
||||
"first_success_after_action_seconds": after[0]["at"] - action_start,
|
||||
"action_seconds": action_end - action_start,
|
||||
"p50_ms": percentile(latency, 0.5),
|
||||
"p95_ms": percentile(latency, 0.95),
|
||||
"p99_ms": percentile(latency, 0.99),
|
||||
"instances": sorted({row["instance"] for row in ok}),
|
||||
"tail_instances": sorted({row["instance"] for row in after[-10:]}),
|
||||
"confirmed_writes": sum(row["message"] is not None for row in ok),
|
||||
}
|
||||
|
||||
def verify_messages(self, client, actor, room):
|
||||
actual = history(client, actor, room)
|
||||
by_id = {value["id"]: value for value in actual}
|
||||
check(len(by_id) == len(actual), "History has duplicate IDs")
|
||||
texts = [row["text"] for row in actual if row["text"].startswith(self.prefix)]
|
||||
check(len(texts) == len(set(texts)), "An uncertain retry created a duplicate effect")
|
||||
for event in self.events:
|
||||
if event["ok"] and event["message"]:
|
||||
check(
|
||||
by_id.get(event["message"]["id"]) == event["message"],
|
||||
"A confirmed message was lost or changed",
|
||||
)
|
||||
|
||||
|
||||
def public_test(target, base):
|
||||
result = subprocess.run(
|
||||
[
|
||||
"make",
|
||||
target,
|
||||
"ACTION_SCRIPT=scripts/"
|
||||
+ ("restart.sh" if target == "test-persistence" else "stop-one.sh"),
|
||||
"BASE_URL=" + base,
|
||||
],
|
||||
cwd=ROOT,
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=150,
|
||||
)
|
||||
return "\n".join(line.rstrip() for line in result.stdout.splitlines()) + "\n"
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--base-url", default="http://127.0.0.1:8084")
|
||||
parser.add_argument(
|
||||
"--output", type=Path, default=ROOT / f"evidence/cluster-{time.time_ns()}.json"
|
||||
)
|
||||
args = parser.parse_args()
|
||||
if args.output.exists():
|
||||
raise SystemExit("Use a new evidence filename")
|
||||
os.environ["NO_PROXY"] = os.environ["no_proxy"] = "127.0.0.1,localhost"
|
||||
baseline = instances()
|
||||
check(len(baseline) == 2, "This verification expects the default two API replicas")
|
||||
check(not any(row["published_ports"] for row in baseline), "API must not publish host ports")
|
||||
wait_lb(args.base_url, 2)
|
||||
result = {"initial_instances": baseline, "failures": []}
|
||||
client = Client(args.base_url, timeout=4)
|
||||
alice, bob, eve, room = client.bootstrap()
|
||||
key = uuid4().hex
|
||||
|
||||
def same_request(_):
|
||||
response = Client(args.base_url).message(alice, room, "concurrent replay", key=key)
|
||||
return response["json"], response["headers"]["X-Instance-Id"]
|
||||
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
responses = list(pool.map(same_request, range(30)))
|
||||
check(
|
||||
len({row[0]["id"] for row in responses}) == 1, "Cross-replica replay duplicated a message"
|
||||
)
|
||||
check(len({row[1] for row in responses}) == 2, "Concurrent replay did not cross real replicas")
|
||||
result["concurrent_replays"] = 30
|
||||
result["concurrent_effects"] = 1
|
||||
try:
|
||||
for selected in baseline:
|
||||
selected = instance(selected["id"])
|
||||
with Traffic(args.base_url, alice, room) as traffic:
|
||||
time.sleep(1)
|
||||
action_start = time.monotonic()
|
||||
env = {**os.environ, "TARGET_INSTANCE_ID": selected["instance"]}
|
||||
subprocess.run(
|
||||
[str(ROOT / "scripts/stop-one.sh")],
|
||||
cwd=ROOT,
|
||||
env=env,
|
||||
check=True,
|
||||
capture_output=True,
|
||||
timeout=10,
|
||||
)
|
||||
action_end = time.monotonic()
|
||||
check(not inspect(selected["id"])["running"], "Chosen process was not stopped")
|
||||
time.sleep(3)
|
||||
report = traffic.report(action_start, action_end)
|
||||
check(report["first_success_after_action_seconds"] <= 10, "Failover took too long")
|
||||
check(selected["instance"] not in report["tail_instances"], "Stopped API still serves")
|
||||
report["stopped"] = selected
|
||||
traffic.verify_messages(client, bob, room)
|
||||
result["failures"].append(report)
|
||||
subprocess.run(["docker", "start", selected["id"]], check=True, capture_output=True)
|
||||
wait_lb(args.base_url, 2)
|
||||
print("Verified failure and restoration of one API", flush=True)
|
||||
with Traffic(args.base_url, alice, room) as traffic:
|
||||
time.sleep(1)
|
||||
action_start = time.monotonic()
|
||||
replaced = subprocess.run(
|
||||
[
|
||||
sys.executable,
|
||||
str(ROOT / "scripts/rolling-update.py"),
|
||||
"--base-url",
|
||||
args.base_url,
|
||||
],
|
||||
cwd=ROOT,
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=120,
|
||||
)
|
||||
action_end = time.monotonic()
|
||||
time.sleep(3)
|
||||
traffic.verify_messages(client, bob, room)
|
||||
result["rolling"] = traffic.report(action_start, action_end)
|
||||
result["rolling"]["replacements"] = json.loads(replaced.stdout)
|
||||
result["rolling"]["confirmed_messages_preserved"] = True
|
||||
print("Verified sequential replacement under traffic", flush=True)
|
||||
(ROOT / "evidence/failover.txt").write_text(public_test("test-failover", args.base_url))
|
||||
for value in compose("ps", "-aq", "api").split():
|
||||
if not inspect(value)["running"]:
|
||||
subprocess.run(["docker", "start", value], check=True, capture_output=True)
|
||||
wait_lb(args.base_url, 2)
|
||||
before = {
|
||||
service: inspect(compose("ps", "-q", service).strip())
|
||||
for service in ("postgres", "valkey", "s3", "lb")
|
||||
}
|
||||
(ROOT / "evidence/persistence.txt").write_text(
|
||||
public_test("test-persistence", args.base_url)
|
||||
)
|
||||
after = {service: inspect(compose("ps", "-q", service).strip()) for service in before}
|
||||
check(
|
||||
all(before[s]["started_at"] != after[s]["started_at"] for s in before),
|
||||
"Persistence hook did not restart all state/LB services",
|
||||
)
|
||||
result["persistence"] = {"before": before, "after": after, "same_token_public_test": True}
|
||||
result["final_instances"] = instances()
|
||||
logs = compose("logs", "--no-color", "api", "lb")
|
||||
check(
|
||||
not any(
|
||||
a["token"] in logs or a["registration"]["password"] in logs
|
||||
for a in (alice, bob, eve)
|
||||
),
|
||||
"Credential appeared in logs",
|
||||
)
|
||||
args.output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n")
|
||||
print("PASS: real replica failures, replay, rolling replacement and persistence")
|
||||
finally:
|
||||
for value in compose("ps", "-aq", "api").split():
|
||||
if not inspect(value)["running"]:
|
||||
subprocess.run(["docker", "start", value], check=True, capture_output=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,424 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Private S3, 10 concurrent proxy uploads, failure recovery and reconciliation cost."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
from botocore.exceptions import ClientError
|
||||
from cluster import compose, inspect, instances, wait_lb
|
||||
from PIL import Image
|
||||
from storage_lab import ROOT, connection, store
|
||||
|
||||
from messenger.reconcile import Reconciler
|
||||
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, check # noqa: E402
|
||||
|
||||
PNG = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
|
||||
|
||||
def put_orphan(admin):
|
||||
key = "originals/" + str(uuid4())
|
||||
admin.put(key, io.BytesIO(PNG), len(PNG), "image/png", hashlib.sha256(PNG).hexdigest())
|
||||
return key
|
||||
|
||||
|
||||
def seed(path):
|
||||
admin = store("root")
|
||||
try:
|
||||
key = put_orphan(admin)
|
||||
path.write_text(
|
||||
json.dumps({"orphan": key, "created_at": datetime.now(UTC).isoformat()}) + "\n"
|
||||
)
|
||||
print("Seeded one orphan; its real S3 LastModified must age 300 seconds.")
|
||||
finally:
|
||||
admin.close()
|
||||
|
||||
|
||||
def memory(cids):
|
||||
result = {}
|
||||
for cid in cids:
|
||||
raw = subprocess.check_output(
|
||||
[
|
||||
"docker",
|
||||
"exec",
|
||||
cid,
|
||||
"sh",
|
||||
"-c",
|
||||
"cat /sys/fs/cgroup/memory.current /sys/fs/cgroup/memory.peak "
|
||||
"/sys/fs/cgroup/cpu.stat",
|
||||
],
|
||||
text=True,
|
||||
)
|
||||
lines = raw.splitlines()
|
||||
current, peak = map(int, lines[:2])
|
||||
counters = {k: int(v) for k, v in (line.split() for line in lines[2:])}
|
||||
result[cid] = {"current_bytes": current, "peak_bytes": peak, "cpu": counters}
|
||||
return result
|
||||
|
||||
|
||||
def pressure(client, actor, chat):
|
||||
results = []
|
||||
for side in (600, 1700):
|
||||
image = Image.frombytes("RGB", (side, side), os.urandom(side * side * 3))
|
||||
output = io.BytesIO()
|
||||
image.save(output, format="PNG", compress_level=0)
|
||||
data = output.getvalue()
|
||||
check(len(data) <= 10485760, "Fixture accidentally oversized")
|
||||
# Recreate API only, so kernel memory.peak includes this trial and startup.
|
||||
compose("up", "-d", "--no-deps", "--force-recreate", "--scale", "api=2", "api")
|
||||
wait_lb(count=2, base=client.base)
|
||||
cids = [row["id"] for row in instances()]
|
||||
resource_started = time.monotonic()
|
||||
baseline = memory(cids)
|
||||
import threading
|
||||
|
||||
barrier = threading.Barrier(10)
|
||||
|
||||
def one(i, data=data, barrier=barrier):
|
||||
c = Client(client.base, timeout=30)
|
||||
barrier.wait(timeout=10)
|
||||
started = time.monotonic()
|
||||
value = c.call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/attachments?filename=load-{i}.png",
|
||||
expected=201,
|
||||
actor=actor,
|
||||
raw=data,
|
||||
headers={"Content-Type": "image/png"},
|
||||
schema="Attachment",
|
||||
)
|
||||
check(value["json"]["sha256"] == hashlib.sha256(data).hexdigest(), "Checksum mismatch")
|
||||
return {
|
||||
"duration_ms": (time.monotonic() - started) * 1000,
|
||||
"instance": value["headers"]["X-Instance-Id"],
|
||||
"id": value["json"]["id"],
|
||||
}
|
||||
|
||||
started = time.monotonic()
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
values = list(pool.map(one, range(10)))
|
||||
elapsed = time.monotonic() - started
|
||||
peak = memory(cids)
|
||||
resource_seconds = time.monotonic() - resource_started
|
||||
cpu_cores = (
|
||||
sum(peak[k]["cpu"]["usage_usec"] - baseline[k]["cpu"]["usage_usec"] for k in cids)
|
||||
/ 1e6
|
||||
/ resource_seconds
|
||||
)
|
||||
values_ms = sorted(row["duration_ms"] for row in values)
|
||||
results.append(
|
||||
{
|
||||
"clients": 10,
|
||||
"bytes_each": len(data),
|
||||
"pixels": side * side,
|
||||
"duration_seconds": elapsed,
|
||||
"successful_rps": 10 / elapsed,
|
||||
"resource_window_seconds": resource_seconds,
|
||||
"mean_api_cpu_cores_including_probes": cpu_cores,
|
||||
"errors": 0,
|
||||
"p50_ms": values_ms[4],
|
||||
"p95_ms": values_ms[9],
|
||||
"p99_ms": values_ms[9],
|
||||
"before": baseline,
|
||||
"after": peak,
|
||||
"responses": values,
|
||||
}
|
||||
)
|
||||
print(f"PASS: 10 simultaneous uploads, {len(data)} bytes each", flush=True)
|
||||
return results
|
||||
|
||||
|
||||
def private(admin, api, chat, actor, client):
|
||||
value, _ = client.attachment(actor, chat)
|
||||
with connection() as conn:
|
||||
row = conn.execute("SELECT * FROM attachments WHERE id=%s", (value["id"],)).fetchone()
|
||||
# HTTP from a different container, no Authorization, no signature, no API.
|
||||
code = (
|
||||
"import urllib.request,urllib.error; "
|
||||
f'u="http://s3:9000/{api.bucket}/{row["object_key"]}"; '
|
||||
"\ntry:\n r=urllib.request.urlopen(u); print(r.status)"
|
||||
"\nexcept urllib.error.HTTPError as e: print(e.code)"
|
||||
)
|
||||
cid = instances()[0]["id"]
|
||||
status = int(subprocess.check_output(["docker", "exec", cid, "python", "-c", code], text=True))
|
||||
check(status == 403, "Anonymous S3 GET succeeded")
|
||||
for method, kwargs in [
|
||||
("delete_object", {"Bucket": api.bucket, "Key": row["object_key"]}),
|
||||
("list_objects_v2", {"Bucket": "unrelated-bucket"}),
|
||||
]:
|
||||
try:
|
||||
getattr(api.client, method)(**kwargs)
|
||||
except ClientError as exc:
|
||||
check(exc.response["ResponseMetadata"]["HTTPStatusCode"] == 403, "Expected IAM 403")
|
||||
else:
|
||||
raise RuntimeError("API identity exceeded its policy")
|
||||
return {
|
||||
"anonymous_get_status": status,
|
||||
"api_delete_denied": True,
|
||||
"other_bucket_denied": True,
|
||||
"attachment": value["id"],
|
||||
}
|
||||
|
||||
|
||||
def cross_replica(client, actor, reader, chat):
|
||||
value = client.call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/attachments?filename=switch.png",
|
||||
expected=201,
|
||||
actor=actor,
|
||||
raw=PNG,
|
||||
headers={"Content-Type": "image/png"},
|
||||
schema="Attachment",
|
||||
)
|
||||
alias = value["headers"]["X-Instance-Id"]
|
||||
selected = next(row for row in instances() if row["instance"] == alias)
|
||||
try:
|
||||
subprocess.run(
|
||||
[str(ROOT / "scripts/stop-one.sh")],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
env={**os.environ, "TARGET_INSTANCE_ID": alias},
|
||||
timeout=10,
|
||||
)
|
||||
stopped = inspect(selected["id"])
|
||||
check(not stopped["running"], "Uploading process was not stopped")
|
||||
time.sleep(1)
|
||||
result = client.call(
|
||||
"GET", "/api/v1/attachments/" + value["json"]["id"] + "/content", actor=reader
|
||||
)
|
||||
check(
|
||||
result["bytes"] == PNG and result["headers"]["X-Instance-Id"] != alias,
|
||||
"Another API failed to serve original",
|
||||
)
|
||||
return {
|
||||
"uploader": selected,
|
||||
"after_stop": stopped,
|
||||
"downloader_instance": result["headers"]["X-Instance-Id"],
|
||||
"original_preserved": True,
|
||||
}
|
||||
finally:
|
||||
subprocess.run(["docker", "start", selected["id"]], check=True, capture_output=True)
|
||||
wait_lb(base=client.base, count=2)
|
||||
|
||||
|
||||
def interruption(client, actor, chat):
|
||||
with connection() as conn:
|
||||
before = conn.execute("SELECT count(*) AS n FROM attachments").fetchone()["n"]
|
||||
# Close in the middle of a correctly declared body; no durable intent must exist yet.
|
||||
s = socket.create_connection(("127.0.0.1", 8084), timeout=3)
|
||||
header = (
|
||||
f"POST /api/v1/chats/{chat['id']}/attachments?filename=interrupted.png HTTP/1.1\r\n"
|
||||
"Host: localhost\r\nContent-Type: image/png\r\nContent-Length: 1048576\r\n"
|
||||
f"Authorization: Bearer {actor['token']}\r\nConnection: close\r\n\r\n"
|
||||
)
|
||||
s.sendall(header.encode() + PNG[:32])
|
||||
s.close()
|
||||
time.sleep(0.5)
|
||||
with connection() as conn:
|
||||
after = conn.execute("SELECT count(*) AS n FROM attachments").fetchone()["n"]
|
||||
check(before == after, "Interrupted inbound body created an intent")
|
||||
return {"before_rows": before, "after_rows": after, "aborted_body_no_intent": True}
|
||||
|
||||
|
||||
def outage(client, actor, chat):
|
||||
att, _ = client.attachment(actor, chat)
|
||||
before = inspect(compose("ps", "-q", "s3").strip())
|
||||
compose("stop", "s3")
|
||||
started = time.monotonic()
|
||||
try:
|
||||
statuses = []
|
||||
for method, path, raw in [
|
||||
("GET", "/api/v1/attachments/" + att["id"] + "/content", None),
|
||||
("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=unavailable.png", PNG),
|
||||
]:
|
||||
request = urllib.request.Request(
|
||||
client.base + path,
|
||||
data=raw,
|
||||
method=method,
|
||||
headers={"Authorization": "Bearer " + actor["token"], "Content-Type": "image/png"},
|
||||
)
|
||||
try:
|
||||
response = urllib.request.urlopen(request, timeout=8)
|
||||
except urllib.error.HTTPError as exc:
|
||||
response = exc
|
||||
with response:
|
||||
statuses.append(response.code)
|
||||
check(response.code == 503, "S3 outage must produce 503")
|
||||
failed = len(statuses)
|
||||
finally:
|
||||
compose("start", "s3")
|
||||
wait_lb(base=client.base, count=2)
|
||||
after = inspect(compose("ps", "-q", "s3").strip())
|
||||
actual = client.call("GET", "/api/v1/attachments/" + att["id"] + "/content", actor=actor)[
|
||||
"bytes"
|
||||
]
|
||||
check(actual == PNG, "S3 restart lost original")
|
||||
return {
|
||||
"before": before,
|
||||
"after": after,
|
||||
"failed_operations": failed,
|
||||
"statuses": statuses,
|
||||
"stop_start_and_ready_seconds": time.monotonic() - started,
|
||||
"original_preserved": True,
|
||||
}
|
||||
|
||||
|
||||
def reconciliation(seed_path, admin, reconciler, client, actor, chat):
|
||||
saved = json.loads(seed_path.read_text())
|
||||
orphan = saved["orphan"]
|
||||
head = admin.head(orphan)
|
||||
check(head is not None, "Seed orphan is missing")
|
||||
age = time.time() - head["LastModified"].timestamp()
|
||||
check(age >= 300, "Seed must be at least 300s old; keep it while other checks run")
|
||||
fresh = put_orphan(admin)
|
||||
used, _ = client.attachment(actor, chat)
|
||||
client.message(actor, chat, "used attachment", attachments=[used["id"]])
|
||||
with connection() as conn:
|
||||
conn.execute(
|
||||
"UPDATE attachments SET updated_at=clock_timestamp()-interval '10 minutes' WHERE id=%s",
|
||||
(used["id"],),
|
||||
)
|
||||
dry = Reconciler(conn, reconciler).run()
|
||||
check(
|
||||
any(
|
||||
a["action"] == "delete_orphan" and a["id"] == orphan.split("/")[1]
|
||||
for a in dry["actions"]
|
||||
),
|
||||
"Dry run did not detect old orphan",
|
||||
)
|
||||
check(admin.head(orphan) is not None, "Dry-run mutated S3")
|
||||
applied = Reconciler(conn, reconciler, apply=True).run()
|
||||
repeated = Reconciler(conn, reconciler, apply=True).run()
|
||||
check(admin.head(orphan) is None and admin.head(fresh) is not None, "Grace safety failed")
|
||||
row = conn.execute("SELECT * FROM attachments WHERE id=%s", (used["id"],)).fetchone()
|
||||
check(
|
||||
row["storage_state"] == "ready" and admin.head(row["object_key"]) is not None,
|
||||
"Used attachment was removed",
|
||||
)
|
||||
check(repeated["actions"] == [], "Repeated apply failed to converge")
|
||||
# Remove a USED object's bytes, preserve its metadata/link, and repair after re-upload.
|
||||
admin.client.delete_object(Bucket=admin.bucket, Key=row["object_key"])
|
||||
missing_dry = Reconciler(conn, reconciler).run()
|
||||
check(
|
||||
conn.execute(
|
||||
"SELECT storage_state FROM attachments WHERE id=%s", (used["id"],)
|
||||
).fetchone()["storage_state"]
|
||||
== "ready",
|
||||
"Dry run mutated metadata",
|
||||
)
|
||||
missing_apply = Reconciler(conn, reconciler, apply=True).run()
|
||||
check(
|
||||
conn.execute(
|
||||
"SELECT storage_state FROM attachments WHERE id=%s", (used["id"],)
|
||||
).fetchone()["storage_state"]
|
||||
== "missing",
|
||||
"Missing original was not marked",
|
||||
)
|
||||
check(
|
||||
conn.execute(
|
||||
"SELECT count(*) AS n FROM message_attachments WHERE attachment_id=%s",
|
||||
(used["id"],),
|
||||
).fetchone()["n"]
|
||||
== 1,
|
||||
"A used relation was removed",
|
||||
)
|
||||
admin.put(
|
||||
row["object_key"],
|
||||
io.BytesIO(PNG),
|
||||
len(PNG),
|
||||
"image/png",
|
||||
hashlib.sha256(PNG).hexdigest(),
|
||||
)
|
||||
healing = Reconciler(conn, reconciler, apply=True).run()
|
||||
check(
|
||||
client.call("GET", "/api/v1/attachments/" + used["id"] + "/content", actor=actor)[
|
||||
"bytes"
|
||||
]
|
||||
== PNG,
|
||||
"Restored original is wrong",
|
||||
)
|
||||
return {
|
||||
"old_orphan_age_seconds": age,
|
||||
"dry_run": dry,
|
||||
"apply": applied,
|
||||
"repeat": repeated,
|
||||
"missing_dry_run": missing_dry,
|
||||
"missing_apply": missing_apply,
|
||||
"healing": healing,
|
||||
"fresh_preserved": True,
|
||||
"used_metadata_and_link_preserved": True,
|
||||
}
|
||||
|
||||
|
||||
def scan_cost(admin, reconciler):
|
||||
results = []
|
||||
created = []
|
||||
try:
|
||||
for target in (0, 100, 1100):
|
||||
while len(created) < target:
|
||||
created.append(put_orphan(admin))
|
||||
repeats = []
|
||||
for _ in range(3):
|
||||
with connection() as conn:
|
||||
repeats.append(Reconciler(conn, reconciler).run())
|
||||
results.append({"extra_fresh_objects": target, "repeats": repeats})
|
||||
return results
|
||||
finally:
|
||||
for key in created:
|
||||
admin.client.delete_object(Bucket=admin.bucket, Key=key)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--seed", type=Path)
|
||||
parser.add_argument("--resume-basics", type=Path)
|
||||
parser.add_argument("--seed-file", type=Path, default=ROOT / "evidence/storage-seed.json")
|
||||
parser.add_argument("--output", type=Path, default=ROOT / "evidence/storage.json")
|
||||
args = parser.parse_args()
|
||||
if args.seed:
|
||||
seed(args.seed)
|
||||
return
|
||||
if args.output.exists():
|
||||
raise SystemExit("Choose a new evidence filename")
|
||||
os.environ["NO_PROXY"] = os.environ["no_proxy"] = "localhost,127.0.0.1"
|
||||
admin, api, rec = store("root"), store("api"), store("reconciler")
|
||||
try:
|
||||
client = Client("http://127.0.0.1:8084", timeout=30)
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
result = {"started_at": datetime.now(UTC).isoformat()}
|
||||
if args.resume_basics:
|
||||
result.update(json.loads(args.resume_basics.read_text()))
|
||||
else:
|
||||
result["privacy"] = private(admin, api, chat, alice, client)
|
||||
result["cross_replica"] = cross_replica(client, alice, bob, chat)
|
||||
result["interruption"] = interruption(client, alice, chat)
|
||||
result["uploads"] = pressure(client, alice, chat)
|
||||
result["outage"] = outage(client, alice, chat)
|
||||
result["reconciliation"] = reconciliation(args.seed_file, admin, rec, client, alice, chat)
|
||||
result["scan_cost"] = scan_cost(admin, rec)
|
||||
result["finished_at"] = datetime.now(UTC).isoformat()
|
||||
args.output.write_text(json.dumps(result, indent=2) + "\n")
|
||||
print(
|
||||
"PASS: private S3, upload memory bound, interruption, outage and reconciler", flush=True
|
||||
)
|
||||
finally:
|
||||
for value in (admin, api, rec):
|
||||
value.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user