forked from mtusi2026/mtusi2026lab7
lab7
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
"""Process heartbeat for Compose; only the trusted LB probes HTTPS readiness."""
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
sys.exit(0 if Path("/tmp/instance-id").is_file() else 1)
|
||||
@@ -0,0 +1,167 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Explicit operator actions. The host-only unseal shares are never mounted."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import subprocess
|
||||
import time
|
||||
from urllib.error import HTTPError
|
||||
|
||||
from scripts.local_pki import ROLES, ROOT, RUNTIME, write
|
||||
from src.bao import client, request
|
||||
|
||||
ADDRESS = "https://localhost:8207"
|
||||
MATERIAL = ROOT / "operator-raft"
|
||||
SHARES = MATERIAL / "unseal.json"
|
||||
INITIAL = MATERIAL / "initial-root"
|
||||
IDENTITY = RUNTIME / "operator"
|
||||
OPENER = client(*(str(IDENTITY / f) for f in ("service.crt", "service.key", "ca.crt")))
|
||||
|
||||
|
||||
def call(path, body=None, token=None, method=None):
|
||||
return request(OPENER, ADDRESS, path, body, token, method, timeout=25)
|
||||
|
||||
|
||||
def unseal():
|
||||
status = seal_status()
|
||||
if status["sealed"]:
|
||||
for share in json.loads(SHARES.read_text()):
|
||||
status = call("sys/unseal", {"key": share}, method="PUT")
|
||||
if not status["sealed"]:
|
||||
break
|
||||
if status["sealed"]:
|
||||
raise RuntimeError("OpenBao is still sealed")
|
||||
for _ in range(25):
|
||||
try:
|
||||
call("sys/health")
|
||||
return
|
||||
except OSError:
|
||||
time.sleep(1)
|
||||
raise RuntimeError("OpenBao did not become active after unseal")
|
||||
|
||||
|
||||
def db_url(role, password):
|
||||
return f"postgresql://lab_{role}:{password}@db:5432/messenger?sslmode=verify-full&sslrootcert=/pki/ca.crt"
|
||||
|
||||
|
||||
def initial_values(role):
|
||||
values = {"DATABASE_URL": db_url(role, (ROOT / "bootstrap" / "db" / role).read_text())}
|
||||
if role != "dispatcher":
|
||||
values["S3_ACCESS_KEY_ID"] = "lab-" + role
|
||||
values["S3_SECRET_ACCESS_KEY"] = (ROOT / "bootstrap" / "s3" / role).read_text()
|
||||
if role in {"dispatcher", "worker"}:
|
||||
user = "producer" if role == "dispatcher" else "worker"
|
||||
password = (ROOT / "bootstrap" / "broker" / user).read_text()
|
||||
values["BROKER_URL"] = f"rediss://{user}:{password}@broker:6380/0"
|
||||
return values
|
||||
|
||||
|
||||
def login(role="operator"):
|
||||
return call("auth/cert/login", {"name": role})["auth"]
|
||||
|
||||
|
||||
def configure(token):
|
||||
if "messenger/" not in call("sys/mounts", token=token):
|
||||
call("sys/mounts/messenger", {"type": "kv", "options": {"version": "2"}}, token)
|
||||
if "cert/" not in call("sys/auth", token=token):
|
||||
call("sys/auth/cert", {"type": "cert"}, token)
|
||||
ttl = int(os.getenv("BAO_TOKEN_TTL", "30"))
|
||||
for role in (*ROLES, "operator"):
|
||||
call("sys/policies/acl/" + role, {
|
||||
"policy": (Path("infra/openbao") / (role + ".hcl")).read_text(),
|
||||
}, token)
|
||||
call("auth/cert/certs/" + role, {
|
||||
"certificate": (RUNTIME / role / "service.crt").read_text(),
|
||||
"allowed_dns_sans": [role],
|
||||
"token_policies": [role],
|
||||
"token_no_default_policy": True,
|
||||
"token_ttl": "5m" if role == "operator" else f"{ttl}s",
|
||||
"token_max_ttl": "5m" if role == "operator" else "5m",
|
||||
"token_explicit_max_ttl": "5m",
|
||||
}, token)
|
||||
if role == "operator":
|
||||
continue
|
||||
try:
|
||||
call("messenger/data/" + role, token=token)
|
||||
except HTTPError as exc:
|
||||
if exc.code != 404:
|
||||
raise
|
||||
call("messenger/data/" + role, {"data": initial_values(role)}, token)
|
||||
|
||||
|
||||
def seal_status():
|
||||
for _ in range(25):
|
||||
try:
|
||||
return call("sys/seal-status")
|
||||
except OSError:
|
||||
time.sleep(1)
|
||||
raise RuntimeError("OpenBao HTTPS listener is unavailable")
|
||||
|
||||
|
||||
def bootstrap():
|
||||
MATERIAL.mkdir(mode=0o700, exist_ok=True)
|
||||
status = seal_status()
|
||||
if not status["initialized"]:
|
||||
result = call("sys/init", {"secret_shares": 3, "secret_threshold": 2}, method="PUT")
|
||||
write(SHARES, json.dumps(result["keys_base64"]), 0o600)
|
||||
write(INITIAL, result["root_token"], 0o600)
|
||||
unseal()
|
||||
if INITIAL.exists():
|
||||
token = INITIAL.read_text()
|
||||
configure(token)
|
||||
login()
|
||||
call("auth/token/revoke-self", {}, token)
|
||||
INITIAL.unlink()
|
||||
else:
|
||||
login()
|
||||
|
||||
|
||||
def rotate_db():
|
||||
token = login()["client_token"]
|
||||
values = call("messenger/data/api", token=token)["data"]["data"]
|
||||
password = secrets.token_hex(32)
|
||||
# Send SQL over stdin. The local peer-auth socket belongs to the DB container.
|
||||
subprocess.run(
|
||||
["docker", "compose", "exec", "-T", "-u", "postgres", "db", "psql",
|
||||
"-q", "-v", "ON_ERROR_STOP=1", "-d", "messenger"],
|
||||
input=f"ALTER ROLE lab_api PASSWORD '{password}';\n",
|
||||
text=True, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
||||
)
|
||||
values["DATABASE_URL"] = db_url("api", password)
|
||||
call("messenger/data/api", {"data": values}, token)
|
||||
write(ROOT / "bootstrap" / "db" / "api", password)
|
||||
# Close existing sessions to prove a subsequent connection cannot use the old credential.
|
||||
subprocess.run(
|
||||
["docker", "compose", "exec", "-T", "-u", "postgres", "db", "psql", "-q", "-d", "messenger"],
|
||||
input="SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE usename='lab_api';\n",
|
||||
text=True, check=True, stdout=subprocess.DEVNULL,
|
||||
)
|
||||
|
||||
|
||||
def rotate_s3():
|
||||
token = login()["client_token"]
|
||||
values = call("messenger/data/api", token=token)["data"]["data"]
|
||||
password = secrets.token_hex(32)
|
||||
path = ROOT / "bootstrap" / "s3" / "api"
|
||||
write(path, password)
|
||||
subprocess.run(["docker", "compose", "run", "--rm", "--no-deps", "-T", "-e", "S3_ROLE=api",
|
||||
"s3-bootstrap"], stdin=subprocess.DEVNULL, check=True)
|
||||
values["S3_SECRET_ACCESS_KEY"] = password
|
||||
call("messenger/data/api", {"data": values}, token)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("action", choices=("bootstrap", "unseal", "seal", "rotate-db", "rotate-s3"))
|
||||
action = parser.parse_args().action
|
||||
if action == "seal":
|
||||
call("sys/seal", token=login()["client_token"], method="PUT")
|
||||
else:
|
||||
{"bootstrap": bootstrap, "unseal": unseal, "rotate-db": rotate_db, "rotate-s3": rotate_s3}[action]()
|
||||
print("OpenBao operator action completed:", action)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,25 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
export MC_CONFIG_DIR=/tmp/mc
|
||||
mkdir -p "$MC_CONFIG_DIR/certs/CAs"
|
||||
cp /pki/ca.crt "$MC_CONFIG_DIR/certs/CAs/ca.crt"
|
||||
for attempt in $(seq 1 45); do
|
||||
if mc alias set local https://s3:9000 operator "$(cat /credentials/root)" >/dev/null 2>&1; then
|
||||
break
|
||||
fi
|
||||
test "$attempt" -lt 45
|
||||
sleep 1
|
||||
done
|
||||
mc mb --ignore-existing local/messenger-attachments >/dev/null
|
||||
mc anonymous set none local/messenger-attachments >/dev/null
|
||||
case "${S3_ROLE:-all}" in
|
||||
all) roles="api worker reconciler" ;;
|
||||
api) roles=api ;;
|
||||
*) exit 2 ;;
|
||||
esac
|
||||
for role in $roles; do
|
||||
mc admin policy create local "messenger-$role" "/policies/$role.json" >/dev/null
|
||||
mc admin user add local "lab-$role" "$(cat "/credentials/$role")" >/dev/null
|
||||
mc admin policy attach local "messenger-$role" --user "lab-$role" >/dev/null
|
||||
done
|
||||
echo 'Private bucket and scoped accounts ready'
|
||||
@@ -0,0 +1,188 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate local identities and only the runtime material each service needs."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
ROOT = Path("secrets")
|
||||
CA = ROOT / "authority"
|
||||
RUNTIME = ROOT / "runtime"
|
||||
ROLES = ("api", "worker", "dispatcher", "reconciler")
|
||||
SERVERS = ("api", "openbao", "db", "s3", "broker", "collector",
|
||||
"prometheus", "loki", "tempo", "grafana")
|
||||
|
||||
|
||||
def openssl(*args, capture=False):
|
||||
result = subprocess.run(["openssl", *map(str, args)], check=True,
|
||||
stdout=subprocess.PIPE if capture else subprocess.DEVNULL,
|
||||
stderr=subprocess.PIPE)
|
||||
return result.stdout.decode() if capture else None
|
||||
|
||||
|
||||
def write(path, content, mode=0o444):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
if path.is_file() and path.read_text() == content:
|
||||
path.chmod(mode)
|
||||
return
|
||||
with tempfile.NamedTemporaryFile(mode="w", dir=path.parent, delete=False) as handle:
|
||||
handle.write(content)
|
||||
temporary = Path(handle.name)
|
||||
temporary.chmod(mode)
|
||||
temporary.replace(path)
|
||||
|
||||
|
||||
def random_file(path):
|
||||
if not path.exists():
|
||||
write(path, secrets.token_hex(32))
|
||||
|
||||
|
||||
def certificate(name, directory=None, issuer=CA):
|
||||
directory = directory or RUNTIME / name
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
key, cert = directory / "service.key", directory / "service.crt"
|
||||
if cert.exists():
|
||||
return
|
||||
dns = ["DNS:" + name]
|
||||
if name in ("public", "grafana", "openbao"):
|
||||
dns += ["DNS:localhost", "IP:127.0.0.1"]
|
||||
with tempfile.TemporaryDirectory(dir=ROOT) as scratch:
|
||||
folder = Path(scratch)
|
||||
private, csr, extensions = (folder / x for x in ("key", "csr", "extensions"))
|
||||
extensions.write_text(
|
||||
"basicConstraints=critical,CA:FALSE\n"
|
||||
"keyUsage=critical,digitalSignature,keyEncipherment\n"
|
||||
"extendedKeyUsage=serverAuth,clientAuth\n"
|
||||
"subjectAltName=" + ",".join(dns) + "\n"
|
||||
)
|
||||
openssl("req", "-new", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:P-256",
|
||||
"-nodes", "-subj", "/CN=" + name, "-keyout", private, "-out", csr)
|
||||
openssl("x509", "-req", "-days", "7", "-in", csr, "-CA", issuer / "ca.crt",
|
||||
"-CAkey", issuer / "ca.key", "-set_serial", "0x" + secrets.token_hex(16),
|
||||
"-extfile", extensions, "-out", cert)
|
||||
write(key, private.read_text())
|
||||
write(directory / "ca.crt", (CA / "ca.crt").read_text())
|
||||
write(directory / "service.pem", cert.read_text() + key.read_text())
|
||||
|
||||
|
||||
def authority(directory, name):
|
||||
directory.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
if not (directory / "ca.crt").exists():
|
||||
openssl("req", "-new", "-x509", "-days", "365", "-newkey", "ec", "-pkeyopt",
|
||||
"ec_paramgen_curve:P-256", "-nodes", "-subj", "/CN=" + name,
|
||||
"-addext", "basicConstraints=critical,CA:TRUE,pathlen:0",
|
||||
"-addext", "keyUsage=critical,keyCertSign,cRLSign",
|
||||
"-keyout", directory / "ca.key", "-out", directory / "ca.crt")
|
||||
|
||||
|
||||
def pin(directory):
|
||||
value = openssl("x509", "-in", directory / "service.crt", "-noout", "-serial", capture=True)
|
||||
return format(int(value.strip().split("=")[1], 16), "x")
|
||||
|
||||
|
||||
def activate_lb(directory):
|
||||
write(RUNTIME / "lb" / "client.pem", (directory / "service.pem").read_text())
|
||||
write(RUNTIME / "api" / "lb-serial", pin(directory))
|
||||
|
||||
|
||||
def activate_collector_client(source):
|
||||
runtime = RUNTIME / "collector" / "client"
|
||||
for name in ("service.crt", "service.key"):
|
||||
write(runtime / name, (source / name).read_text())
|
||||
fingerprint = openssl("x509", "-in", source / "service.crt", "-noout", "-fingerprint",
|
||||
"-sha256", capture=True).split("=", 1)[1].strip()
|
||||
for target in ("loki", "tempo"):
|
||||
write(RUNTIME / target / "collector-fingerprint", fingerprint.replace(":", "").lower() + "\n")
|
||||
|
||||
|
||||
def bootstrap():
|
||||
ROOT.mkdir(mode=0o700, exist_ok=True)
|
||||
ROOT.chmod(0o700)
|
||||
(ROOT / "rotation" / "probe").mkdir(parents=True, exist_ok=True)
|
||||
authority(CA, "Lab7 local authority")
|
||||
authority(ROOT / "foreign", "Lab7 untrusted test authority")
|
||||
for name in set(ROLES) | set(SERVERS) | {"operator", "public", "intruder", "scraper"}:
|
||||
certificate(name)
|
||||
certificate("lb", ROOT / "foreign" / "client", ROOT / "foreign")
|
||||
for name in ("public.crt", "private.key"):
|
||||
source = "service.crt" if name == "public.crt" else "service.key"
|
||||
write(RUNTIME / "s3" / name, (RUNTIME / "s3" / source).read_text())
|
||||
|
||||
write(RUNTIME / "lb" / "server.pem", (RUNTIME / "public" / "service.pem").read_text())
|
||||
if not (RUNTIME / "api" / "lb-serial").exists():
|
||||
initial_lb = ROOT / "rotation" / "initial-lb"
|
||||
certificate("lb", initial_lb)
|
||||
activate_lb(initial_lb)
|
||||
if not (RUNTIME / "collector" / "client" / "service.crt").exists():
|
||||
initial = ROOT / "rotation" / "initial-collector"
|
||||
certificate("collector-export", initial)
|
||||
activate_collector_client(initial)
|
||||
for name in ("db_owner", *ROLES):
|
||||
random_file(ROOT / "bootstrap" / "db" / name)
|
||||
for name in ("root", "api", "worker", "reconciler"):
|
||||
random_file(ROOT / "bootstrap" / "s3" / name)
|
||||
random_file(ROOT / "bootstrap" / "grafana" / "admin")
|
||||
for name in ("producer", "worker"):
|
||||
random_file(ROOT / "bootstrap" / "broker" / name)
|
||||
acl = ["user default off"]
|
||||
commands = {
|
||||
"producer": "+ping +xadd +xgroup|create",
|
||||
"worker": "+ping +xgroup|create +xautoclaim +xreadgroup +xack",
|
||||
}
|
||||
for name, permissions in commands.items():
|
||||
raw = (ROOT / "bootstrap" / "broker" / name).read_bytes()
|
||||
hashed = hashlib.sha256(raw).hexdigest()
|
||||
acl.append(f"user {name} on #{hashed} ~attachments.jobs {permissions}")
|
||||
write(RUNTIME / "broker" / "users.acl", "\n".join(acl) + "\n")
|
||||
for role in ROLES:
|
||||
write(Path("secrets") / "policies" / (role + ".hcl"),
|
||||
(Path("infra/openbao") / (role + ".hcl")).read_text())
|
||||
grafana = RUNTIME / "grafana"
|
||||
data = []
|
||||
for service, port in (("prometheus", 9090), ("loki", 3100), ("tempo", 3200)):
|
||||
item = dict(name=service.title(), uid=service, type=service, access="proxy",
|
||||
url=f"https://{service}:{port}", isDefault=service == "prometheus",
|
||||
jsonData={"tlsAuth": True, "tlsAuthWithCACert": True},
|
||||
secureJsonData={"tlsCACert": (grafana / "ca.crt").read_text(),
|
||||
"tlsClientCert": (grafana / "service.crt").read_text(),
|
||||
"tlsClientKey": (grafana / "service.key").read_text()})
|
||||
if service == "loki":
|
||||
item["jsonData"]["derivedFields"] = [{
|
||||
"name": "TraceID", "matcherRegex": '"trace_id":"([0-9a-f]{32})"',
|
||||
"datasourceUid": "tempo", "url": "$${__value.raw}",
|
||||
}]
|
||||
if service == "tempo":
|
||||
item["jsonData"]["tracesToLogsV2"] = {"datasourceUid": "loki", "filterByTraceID": True}
|
||||
data.append(item)
|
||||
write(grafana / "sources.yaml", json.dumps({"apiVersion": 1, "datasources": data}, indent=2))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("action", choices=("bootstrap", "rotate-lb", "rotate-collector"))
|
||||
args = parser.parse_args()
|
||||
os.umask(0o022)
|
||||
if args.action == "bootstrap":
|
||||
bootstrap()
|
||||
elif args.action == "rotate-lb":
|
||||
previous = ROOT / "rotation" / "probe" / "previous.pem"
|
||||
write(previous, (RUNTIME / "lb" / "client.pem").read_text(), 0o444)
|
||||
directory = ROOT / "rotation" / secrets.token_hex(8)
|
||||
certificate("lb", directory)
|
||||
activate_lb(directory)
|
||||
else:
|
||||
old = RUNTIME / "collector" / "client"
|
||||
previous = ROOT / "rotation" / "probe" / "collector-previous.pem"
|
||||
write(previous, (old / "service.crt").read_text() + (old / "service.key").read_text())
|
||||
directory = ROOT / "rotation" / secrets.token_hex(8)
|
||||
certificate("collector-export", directory)
|
||||
activate_collector_client(directory)
|
||||
print("Local PKI updated:", args.action)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+15
@@ -0,0 +1,15 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
services=(db s3 openbao streams otel metrics logs traces grafana api worker dispatcher reconciler)
|
||||
snapshot() {
|
||||
docker compose ps -a -q "${services[@]}" | xargs -r docker inspect --format \
|
||||
'{{index .Config.Labels "com.docker.compose.service"}} {{.Id}} {{.State.StartedAt}} {{range .Mounts}}{{if eq .Type "volume"}}{{.Name}} {{end}}{{end}}' | sort
|
||||
}
|
||||
snapshot > evidence/persistence-before.txt
|
||||
docker compose stop lb api worker dispatcher reconciler grafana otel metrics logs traces streams
|
||||
docker compose restart db s3 openbao broker collector prometheus loki tempo
|
||||
python3 -m scripts.bao_operator unseal
|
||||
docker compose start streams otel metrics logs traces grafana api worker dispatcher reconciler lb
|
||||
python3 scripts/wait_ready.py
|
||||
snapshot > evidence/persistence-after.txt
|
||||
Executable
+29
@@ -0,0 +1,29 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
cache="$PWD/secrets/scans"
|
||||
mkdir -p "$cache"
|
||||
scanner=aquasec/trivy:0.69.3
|
||||
docker run --rm -v "$cache:/scan" "$scanner" image --cache-dir /scan --download-db-only
|
||||
while read -r service image; do
|
||||
if (( $# )) && [[ " $* " != *" $service "* ]]; then continue; fi
|
||||
echo "Scanning $service $image"
|
||||
docker image save "$image" -o "$cache/image.tar"
|
||||
docker run --rm -v "$cache:/scan" "$scanner" image --cache-dir /scan \
|
||||
--input /scan/image.tar --skip-db-update --skip-java-db-update --scanners vuln \
|
||||
--severity HIGH,CRITICAL --format table --no-progress > "evidence/trivy-$service.txt"
|
||||
done <<'IMAGES'
|
||||
app mtusi2026lab7-app:1
|
||||
db postgres:16.9-bookworm
|
||||
redis redis:7.4.3-bookworm
|
||||
gateway haproxy:3.0.11-bookworm
|
||||
bao openbao/openbao:2.7.2
|
||||
minio cgr.dev/chainguard/minio@sha256:616286de6ef3a1892876b126e745e152d8e03add6357203f8a1f854bdd1dce76
|
||||
mc mtusi2026lab7-mc:2025-04-16
|
||||
collector otel/opentelemetry-collector-contrib:0.123.0
|
||||
prometheus prom/prometheus:v3.2.1
|
||||
loki grafana/loki:3.4.2
|
||||
tempo grafana/tempo:2.7.2
|
||||
grafana grafana/grafana:11.6.0-ubuntu
|
||||
IMAGES
|
||||
rm -- "$cache/image.tar"
|
||||
Executable
+13
@@ -0,0 +1,13 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
python3 scripts/local_pki.py bootstrap
|
||||
docker compose config --quiet
|
||||
docker compose build api s3-bootstrap
|
||||
docker compose run --rm --no-deps -T volume-permissions </dev/null
|
||||
docker compose up -d --wait db s3 openbao broker streams collector otel prometheus metrics loki logs tempo traces grafana
|
||||
python3 -m scripts.bao_operator bootstrap
|
||||
docker compose run --rm --no-deps -T migrate </dev/null
|
||||
docker compose run --rm --no-deps -T s3-bootstrap </dev/null
|
||||
docker compose up -d --no-deps api lb worker dispatcher reconciler
|
||||
python3 scripts/wait_ready.py
|
||||
Executable
+12
@@ -0,0 +1,12 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
: "${TARGET_INSTANCE_ID:?Missing tested replica alias}"
|
||||
for container in $(docker compose ps -q api); do
|
||||
if [[ "$(docker exec "$container" cat /tmp/instance-id)" == "$TARGET_INSTANCE_ID" ]]; then
|
||||
docker stop --time 1 "$container" >/dev/null
|
||||
printf 'Stopped API alias %s, container %.12s\n' "$TARGET_INSTANCE_ID" "$container" >> evidence/failover-hook.txt
|
||||
exit 0
|
||||
fi
|
||||
done
|
||||
exit 1
|
||||
Executable
+11
@@ -0,0 +1,11 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
restore() {
|
||||
SESSION_TTL_SECONDS=3600 docker compose up -d --force-recreate --no-deps api
|
||||
python3 scripts/wait_ready.py
|
||||
}
|
||||
trap restore EXIT
|
||||
SESSION_TTL_SECONDS=2 docker compose up -d --force-recreate --no-deps api
|
||||
python3 scripts/wait_ready.py
|
||||
python3 student-tests/http_security.py expiry
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Wait for two independently ready replica aliases through verified ingress."""
|
||||
import argparse
|
||||
import ssl
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
|
||||
def wait(count, timeout):
|
||||
context = ssl.create_default_context(cafile="secrets/authority/ca.crt")
|
||||
end = time.monotonic() + timeout
|
||||
aliases = set()
|
||||
while time.monotonic() < end:
|
||||
try:
|
||||
with urllib.request.urlopen("https://localhost:8443/health/ready", context=context, timeout=3) as res:
|
||||
aliases.add(res.headers["X-Instance-Id"])
|
||||
if len(aliases) >= count:
|
||||
print("Ready aliases:", ", ".join(sorted(aliases)))
|
||||
return
|
||||
except OSError:
|
||||
pass
|
||||
time.sleep(.4)
|
||||
raise SystemExit(f"Only {len(aliases)} ready API replicas within {timeout}s")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--count", type=int, default=2)
|
||||
parser.add_argument("--timeout", type=int, default=65)
|
||||
args = parser.parse_args()
|
||||
wait(args.count, args.timeout)
|
||||
Reference in New Issue
Block a user