Add protected Ansible recovery transaction and verified simulation evidence
startup-product-gitea-ci/pipeline/pr-main This commit looks good
startup-product-gitea-ci/pipeline/pr-main This commit looks good
This commit is contained in:
+248
@@ -0,0 +1,248 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def log(message):
|
||||
print(
|
||||
datetime.now(timezone.utc).isoformat(),
|
||||
message,
|
||||
flush=True
|
||||
)
|
||||
|
||||
|
||||
def docker(*args):
|
||||
return subprocess.check_output(
|
||||
["docker", *args],
|
||||
text=True,
|
||||
timeout=60
|
||||
).strip()
|
||||
|
||||
|
||||
def inspect(identifier):
|
||||
return json.loads(docker("inspect", identifier))[0]
|
||||
|
||||
|
||||
def fetch(url):
|
||||
with urllib.request.urlopen(url, timeout=5) as response:
|
||||
if response.status != 200:
|
||||
raise RuntimeError("Unexpected HTTP status")
|
||||
return json.load(response)
|
||||
|
||||
|
||||
def verify(release, container):
|
||||
expected_id = json.loads(
|
||||
docker("image", "inspect", release["image"])
|
||||
)[0]["Id"]
|
||||
|
||||
for attempt in range(15):
|
||||
try:
|
||||
active = inspect(container)
|
||||
health = fetch(release["health_url"])
|
||||
pricing = fetch(release["pricing_url"])
|
||||
|
||||
plans = {
|
||||
p["name"]: p["price"]
|
||||
for p in pricing["plans"]
|
||||
}
|
||||
|
||||
assert active["State"]["Running"]
|
||||
assert active["Config"]["Image"] == release["image"]
|
||||
assert active["Image"] == expected_id
|
||||
assert health["status"] == release["expected_health"]
|
||||
assert pricing["version"] == release["release"]
|
||||
assert plans == release["expected_pricing"]
|
||||
assert len(pricing["plans"]) == len(plans)
|
||||
assert sum(plans.values()) == release["expected_total"]
|
||||
|
||||
if release["release"] == "v2":
|
||||
assert health["version"] == "v2"
|
||||
|
||||
log("VERIFIED " + release["release"])
|
||||
log("Registry reference: " + release["image"])
|
||||
log("Image ID: " + active["Image"])
|
||||
log("Health: " + json.dumps(health))
|
||||
log("Pricing: " + json.dumps(pricing))
|
||||
return
|
||||
|
||||
except Exception as exc:
|
||||
log(f"Verification attempt {attempt + 1}: {exc}")
|
||||
time.sleep(2)
|
||||
|
||||
raise RuntimeError("Release verification failed")
|
||||
|
||||
|
||||
def interrupted(signum, frame):
|
||||
raise RuntimeError(f"Interrupted by signal {signum}")
|
||||
|
||||
|
||||
def main():
|
||||
if not __debug__:
|
||||
raise RuntimeError("Python assertions must remain enabled")
|
||||
|
||||
if os.geteuid() != 0:
|
||||
raise RuntimeError("Root execution required")
|
||||
|
||||
if len(sys.argv) != 3 or sys.argv[2] != "AUTHORIZED":
|
||||
raise RuntimeError("Explicit authorization required")
|
||||
|
||||
config = json.loads(Path(sys.argv[1]).read_text())
|
||||
v1 = config["v1"]
|
||||
v2 = config["v2"]
|
||||
|
||||
name = v2["container_name"]
|
||||
|
||||
assert name == "startup-pricing-production"
|
||||
assert v1["container_name"] == name
|
||||
assert v1["release"] == "v1"
|
||||
assert v2["release"] == "v2"
|
||||
assert v1["image"] != v2["image"]
|
||||
|
||||
stamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
|
||||
saved_v2 = name + "-recovery-" + stamp
|
||||
saved_v1 = name + "-drill-v1-" + stamp
|
||||
|
||||
lock = open("/run/lock/chapter6-production.lock", "a")
|
||||
|
||||
try:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError:
|
||||
raise RuntimeError("Production deployment lock is busy")
|
||||
|
||||
log("PRODUCTION_LOCK_ACQUIRED")
|
||||
log("Configuration commit: " + config["configuration_commit"])
|
||||
|
||||
signal.signal(signal.SIGTERM, interrupted)
|
||||
signal.signal(signal.SIGINT, interrupted)
|
||||
signal.signal(signal.SIGHUP, interrupted)
|
||||
|
||||
original = inspect(name)
|
||||
original_id = original["Id"]
|
||||
|
||||
docker("image", "inspect", v1["image"])
|
||||
docker("image", "inspect", v2["image"])
|
||||
|
||||
verify(v2, name)
|
||||
|
||||
existing = docker("ps", "-a", "--format", "{{.Names}}").splitlines()
|
||||
|
||||
if saved_v1 in existing or saved_v2 in existing:
|
||||
raise RuntimeError("Preservation name already exists")
|
||||
|
||||
log("ROLLBACK_DECISION")
|
||||
log("Original V2 container: " + original_id)
|
||||
|
||||
try:
|
||||
log("ROLLBACK_STARTED")
|
||||
|
||||
docker("stop", original_id)
|
||||
docker("rename", original_id, saved_v2)
|
||||
|
||||
docker(
|
||||
"run", "-d",
|
||||
"--pull=never",
|
||||
"--name", name,
|
||||
"--label", "chapter6.recovery=" + stamp,
|
||||
"--restart", v1["restart_policy"],
|
||||
"--network", v1["network"],
|
||||
"--memory", v1["memory"],
|
||||
"--memory-swap", v1["memory_swap"],
|
||||
"--cpus", str(v1["cpus"]),
|
||||
"--pids-limit", str(v1["pids_limit"]),
|
||||
"--read-only",
|
||||
"--tmpfs", v1["tmpfs"],
|
||||
"--security-opt", "no-new-privileges:true",
|
||||
"--cap-drop", "ALL",
|
||||
"-p", v1["host_binding"],
|
||||
v1["image"]
|
||||
)
|
||||
|
||||
verify(v1, name)
|
||||
log("ROLLBACK_RECOVERED")
|
||||
|
||||
time.sleep(10)
|
||||
|
||||
log("RESTORATION_STARTED")
|
||||
|
||||
replacement = inspect(name)
|
||||
|
||||
assert replacement["Config"]["Labels"].get(
|
||||
"chapter6.recovery"
|
||||
) == stamp
|
||||
|
||||
docker("stop", replacement["Id"])
|
||||
docker("rename", replacement["Id"], saved_v1)
|
||||
|
||||
docker("rename", original_id, name)
|
||||
docker("start", original_id)
|
||||
|
||||
verify(v2, name)
|
||||
|
||||
assert inspect(name)["Id"] == original_id
|
||||
|
||||
log("RESTORATION_RECOVERED")
|
||||
log("Preserved V1: " + saved_v1)
|
||||
log("Restored original V2: " + original_id)
|
||||
log("RECOVERY_TRANSACTION_SUCCESS")
|
||||
|
||||
except BaseException as exc:
|
||||
log("RECOVERY_TRANSACTION_FAILED: " + str(exc))
|
||||
log("Attempting original V2 restoration")
|
||||
|
||||
try:
|
||||
names = docker(
|
||||
"ps", "-a", "--format", "{{.Names}}"
|
||||
).splitlines()
|
||||
|
||||
if name in names:
|
||||
current = inspect(name)
|
||||
|
||||
if current["Id"] != original_id:
|
||||
labels = current["Config"].get("Labels") or {}
|
||||
|
||||
if labels.get("chapter6.recovery") != stamp:
|
||||
raise RuntimeError(
|
||||
"Unexpected container; refusing modification"
|
||||
)
|
||||
|
||||
if current["State"]["Running"]:
|
||||
docker("stop", current["Id"])
|
||||
|
||||
docker(
|
||||
"rename",
|
||||
current["Id"],
|
||||
name + "-failed-" + stamp
|
||||
)
|
||||
|
||||
original = inspect(original_id)
|
||||
|
||||
if original["Name"] != "/" + name:
|
||||
docker("rename", original_id, name)
|
||||
|
||||
if not inspect(original_id)["State"]["Running"]:
|
||||
docker("start", original_id)
|
||||
|
||||
verify(v2, name)
|
||||
log("EMERGENCY_V2_RESTORATION_VERIFIED")
|
||||
|
||||
except BaseException as rescue_error:
|
||||
log("MANUAL_RECOVERY_REQUIRED: " + str(rescue_error))
|
||||
|
||||
raise
|
||||
|
||||
finally:
|
||||
lock.close()
|
||||
log("PRODUCTION_LOCK_RELEASED")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user