Implement durable image processing pipeline with outbox and recovery
This commit is contained in:
Executable
+10
@@ -0,0 +1,10 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
exec docker compose \
|
||||
--project-name mtusi2026lab5 \
|
||||
--env-file .env \
|
||||
-f compose.yaml \
|
||||
-f compose.s3.yaml \
|
||||
-f compose.queue.yaml \
|
||||
"$@"
|
||||
Executable
+124
@@ -0,0 +1,124 @@
|
||||
#!/usr/bin/env python3
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
DC = str(ROOT / "scripts/dc")
|
||||
|
||||
STORES = ["postgres", "redis", "s3", "broker"]
|
||||
PROCESSES = ["api", "lb", "publisher", "worker", "cleanup"]
|
||||
SERVICES = STORES + PROCESSES
|
||||
|
||||
|
||||
def compose(*args, timeout=60):
|
||||
result = subprocess.run(
|
||||
[DC, *args],
|
||||
cwd=ROOT,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=timeout,
|
||||
)
|
||||
if result.returncode:
|
||||
raise RuntimeError("Compose failed: " + " ".join(args))
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def snapshot():
|
||||
ids = compose("ps", "-a", "-q", *SERVICES).split()
|
||||
if not ids:
|
||||
raise RuntimeError("No lab5 containers found")
|
||||
|
||||
result = subprocess.run(
|
||||
["docker", "inspect", *ids],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=15,
|
||||
)
|
||||
|
||||
records = []
|
||||
for item in json.loads(result.stdout):
|
||||
records.append({
|
||||
"service": item["Config"]["Labels"]["com.docker.compose.service"],
|
||||
"container_id": item["Id"],
|
||||
"started_at": item["State"]["StartedAt"],
|
||||
"status": item["State"]["Status"],
|
||||
"volumes": sorted(
|
||||
mount["Name"]
|
||||
for mount in item["Mounts"]
|
||||
if mount["Type"] == "volume"
|
||||
),
|
||||
})
|
||||
return sorted(records, key=lambda item: (item["service"], item["container_id"]))
|
||||
|
||||
|
||||
def main():
|
||||
report = {"before": snapshot(), "result": "INCOMPLETE"}
|
||||
try:
|
||||
print("Stopping API, LB and background processes...", flush=True)
|
||||
compose("stop", "--timeout", "5", *PROCESSES)
|
||||
|
||||
print("Restarting PostgreSQL, Redis, S3 and RabbitMQ...", flush=True)
|
||||
compose("restart", "--no-deps", "--timeout", "10", *STORES)
|
||||
|
||||
deadline = time.monotonic() + 20
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
compose(
|
||||
"exec", "-T", "postgres",
|
||||
"pg_isready", "-U", "messenger", "-d", "messenger",
|
||||
timeout=4,
|
||||
)
|
||||
break
|
||||
except (RuntimeError, subprocess.TimeoutExpired):
|
||||
time.sleep(1)
|
||||
else:
|
||||
raise RuntimeError("PostgreSQL readiness timeout")
|
||||
|
||||
print("Starting API, LB and background processes...", flush=True)
|
||||
compose("up", "-d", "--no-deps", "--no-build", *PROCESSES)
|
||||
|
||||
after = snapshot()
|
||||
report["after"] = after
|
||||
|
||||
for service in SERVICES:
|
||||
old = [item for item in report["before"] if item["service"] == service]
|
||||
new = [item for item in after if item["service"] == service]
|
||||
|
||||
if not old or len(old) != len(new):
|
||||
raise RuntimeError(f"Unexpected container count: {service}")
|
||||
|
||||
old_starts = {item["started_at"] for item in old}
|
||||
if any(item["started_at"] in old_starts for item in new):
|
||||
raise RuntimeError(f"Restart not observed: {service}")
|
||||
|
||||
for service in STORES:
|
||||
old_volumes = {
|
||||
volume
|
||||
for item in report["before"] if item["service"] == service
|
||||
for volume in item["volumes"]
|
||||
}
|
||||
new_volumes = {
|
||||
volume
|
||||
for item in after if item["service"] == service
|
||||
for volume in item["volumes"]
|
||||
}
|
||||
if not old_volumes or old_volumes != new_volumes:
|
||||
raise RuntimeError(f"Persistent volumes changed: {service}")
|
||||
|
||||
report["result"] = "HOOK_COMPLETED"
|
||||
print("Restart hook completed; persistent volume names preserved.", flush=True)
|
||||
|
||||
finally:
|
||||
path = ROOT / "evidence" / "restart_containers.json"
|
||||
path.parent.mkdir(exist_ok=True)
|
||||
path.write_text(json.dumps(report, indent=2) + "\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,67 @@
|
||||
from pathlib import Path
|
||||
import json
|
||||
import secrets
|
||||
|
||||
|
||||
root = Path(__file__).resolve().parent.parent
|
||||
directory = root / "secrets"
|
||||
|
||||
targets = [
|
||||
root / ".env",
|
||||
directory / "s3_config.json",
|
||||
directory / "s3_access_key_id",
|
||||
directory / "s3_secret_access_key",
|
||||
directory / "broker_url",
|
||||
]
|
||||
|
||||
existing = [path for path in targets if path.exists()]
|
||||
if existing:
|
||||
raise SystemExit(
|
||||
"STOP: local configuration already exists; "
|
||||
"nothing changed. Do not delete or rotate it blindly."
|
||||
)
|
||||
|
||||
directory.mkdir(mode=0o700, exist_ok=True)
|
||||
directory.chmod(0o700)
|
||||
|
||||
postgres_password = secrets.token_hex(24)
|
||||
rabbit_password = secrets.token_hex(24)
|
||||
access_key = "lab5" + secrets.token_hex(12)
|
||||
secret_key = secrets.token_hex(32)
|
||||
|
||||
config = {
|
||||
"identities": [
|
||||
{
|
||||
"name": "lab5",
|
||||
"credentials": [
|
||||
{
|
||||
"accessKey": access_key,
|
||||
"secretKey": secret_key,
|
||||
}
|
||||
],
|
||||
"actions": ["Admin", "Read", "Write", "List", "Tagging"],
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
contents = {
|
||||
root / ".env": (
|
||||
f"POSTGRES_PASSWORD={postgres_password}\n"
|
||||
f"RABBITMQ_PASSWORD={rabbit_password}\n"
|
||||
"SESSION_TTL_SECONDS=3600\n"
|
||||
"USER_CACHE_TTL_SECONDS=60\n"
|
||||
),
|
||||
directory / "s3_config.json": json.dumps(config, indent=2) + "\n",
|
||||
directory / "s3_access_key_id": access_key + "\n",
|
||||
directory / "s3_secret_access_key": secret_key + "\n",
|
||||
directory / "broker_url": (
|
||||
f"amqp://messenger:{rabbit_password}@broker:5672/%2F\n"
|
||||
),
|
||||
}
|
||||
|
||||
for path, content in contents.items():
|
||||
with path.open("x") as stream:
|
||||
path.chmod(0o600 if path.name == ".env" else 0o644)
|
||||
stream.write(content)
|
||||
|
||||
print("Created local lab5 configuration; secret values were not printed.")
|
||||
@@ -0,0 +1,126 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
DIRECTORY = ROOT / "secrets"
|
||||
BUCKET = "messenger-attachments"
|
||||
|
||||
KEY_FILES = (
|
||||
"s3_admin_access_key",
|
||||
"s3_admin_secret_key",
|
||||
"s3_access_key_id",
|
||||
"s3_secret_access_key",
|
||||
)
|
||||
|
||||
|
||||
def configuration(values):
|
||||
return {
|
||||
"identities": [
|
||||
{
|
||||
"name": "bootstrap-admin",
|
||||
"credentials": [{
|
||||
"accessKey": values["s3_admin_access_key"],
|
||||
"secretKey": values["s3_admin_secret_key"],
|
||||
}],
|
||||
"actions": ["Admin", "Read", "Write", "List", "Tagging"],
|
||||
},
|
||||
{
|
||||
"name": "messenger-api",
|
||||
"credentials": [{
|
||||
"accessKey": values["s3_access_key_id"],
|
||||
"secretKey": values["s3_secret_access_key"],
|
||||
}],
|
||||
"actions": [
|
||||
f"Read:{BUCKET}",
|
||||
f"Write:{BUCKET}",
|
||||
f"List:{BUCKET}",
|
||||
],
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
def ensure_ignores():
|
||||
patterns = (
|
||||
".env",
|
||||
"/secrets/",
|
||||
"*.bak",
|
||||
"__pycache__/",
|
||||
"*.py[cod]",
|
||||
)
|
||||
for filename in (".gitignore", ".dockerignore"):
|
||||
path = ROOT / filename
|
||||
text = path.read_text() if path.exists() else ""
|
||||
existing = set(text.splitlines())
|
||||
missing = [item for item in patterns if item not in existing]
|
||||
if missing:
|
||||
path.write_text(
|
||||
text.rstrip("\n") + "\n" + "\n".join(missing) + "\n"
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
if DIRECTORY.is_symlink():
|
||||
raise SystemExit("Refusing a symlink at secrets/")
|
||||
|
||||
paths = [DIRECTORY / name for name in KEY_FILES]
|
||||
paths.append(DIRECTORY / "s3_config.json")
|
||||
present = [path.exists() for path in paths]
|
||||
|
||||
if any(present):
|
||||
if not all(path.is_file() and not path.is_symlink() for path in paths):
|
||||
raise SystemExit(
|
||||
"Incomplete or unsafe secret files; nothing regenerated"
|
||||
)
|
||||
|
||||
values = {
|
||||
name: (DIRECTORY / name).read_text().rstrip("\r\n")
|
||||
for name in KEY_FILES
|
||||
}
|
||||
if not all(values.values()):
|
||||
raise SystemExit("Empty credential file; nothing regenerated")
|
||||
|
||||
actual = json.loads(
|
||||
(DIRECTORY / "s3_config.json").read_text()
|
||||
)
|
||||
if actual != configuration(values):
|
||||
raise SystemExit(
|
||||
"Credentials and S3 configuration differ; nothing regenerated"
|
||||
)
|
||||
message = "Existing credentials verified; keys unchanged."
|
||||
else:
|
||||
DIRECTORY.mkdir(mode=0o700, exist_ok=True)
|
||||
DIRECTORY.chmod(0o700)
|
||||
|
||||
values = {
|
||||
"s3_admin_access_key": "admin-" + secrets.token_hex(12),
|
||||
"s3_admin_secret_key": secrets.token_hex(32),
|
||||
"s3_access_key_id": "api-" + secrets.token_hex(12),
|
||||
"s3_secret_access_key": secrets.token_hex(32),
|
||||
}
|
||||
|
||||
for name, value in values.items():
|
||||
with (DIRECTORY / name).open("x") as stream:
|
||||
stream.write(value + "\n")
|
||||
|
||||
with (DIRECTORY / "s3_config.json").open("x") as stream:
|
||||
json.dump(configuration(values), stream, indent=2)
|
||||
stream.write("\n")
|
||||
|
||||
message = "New credentials created; values are not printed."
|
||||
|
||||
DIRECTORY.chmod(0o700)
|
||||
for path in paths:
|
||||
path.chmod(0o644)
|
||||
|
||||
ensure_ignores()
|
||||
print(message)
|
||||
print("Secrets, .env, Python cache and .bak files are excluded.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+66
@@ -0,0 +1,66 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
exec python3 - <<'PY'
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
target = os.environ.get("TARGET_INSTANCE_ID")
|
||||
if not target:
|
||||
raise SystemExit("TARGET_INSTANCE_ID is required")
|
||||
|
||||
compose = ["./scripts/dc"]
|
||||
|
||||
containers = subprocess.check_output(
|
||||
compose + ["ps", "-q", "api"],
|
||||
text=True,
|
||||
timeout=10,
|
||||
).split()
|
||||
|
||||
if len(containers) < 2:
|
||||
raise SystemExit("At least two running API containers are required")
|
||||
|
||||
probe = (
|
||||
"import urllib.request; "
|
||||
"r=urllib.request.urlopen("
|
||||
"'http://127.0.0.1:8080/health/ready', timeout=2); "
|
||||
"print(r.headers['X-Instance-Id'])"
|
||||
)
|
||||
|
||||
matches = []
|
||||
for container in containers:
|
||||
instance = subprocess.check_output(
|
||||
["docker", "exec", container, "python", "-c", probe],
|
||||
text=True,
|
||||
timeout=4,
|
||||
).strip()
|
||||
|
||||
if instance == target:
|
||||
matches.append(container)
|
||||
|
||||
if len(matches) != 1:
|
||||
raise SystemExit("Target instance was not resolved uniquely")
|
||||
|
||||
container = matches[0]
|
||||
print("Stopping target API container:", container[:12], flush=True)
|
||||
|
||||
subprocess.run(
|
||||
["docker", "stop", "--time", "5", container],
|
||||
check=True,
|
||||
stdout=subprocess.DEVNULL,
|
||||
timeout=15,
|
||||
)
|
||||
|
||||
running = subprocess.check_output(
|
||||
["docker", "inspect", "-f", "{{.State.Running}}", container],
|
||||
text=True,
|
||||
timeout=5,
|
||||
).strip()
|
||||
|
||||
if running != "false":
|
||||
raise SystemExit("Target API container is still running")
|
||||
|
||||
print("Target API container is stopped", flush=True)
|
||||
PY
|
||||
Reference in New Issue
Block a user