my-homelab-configs/scripts/progressive-lab.py

203 lines
9.2 KiB
Python

#!/usr/bin/env python3
"""Run a disposable canary experiment through an Argo CD application."""
import json
import os
import re
import socket
import subprocess
import sys
import time
import urllib.error
import urllib.request
from contextlib import contextmanager
NAMESPACE = "progressive-lab"
OWNER = "homelab.dev/progressive-lab"
METRIC = re.compile(r'^progressive_lab_requests_total\{version="(stable|canary)",outcome="(success|error)"\} (\d+)$')
def kubectl(*args, data=None):
result = subprocess.run(["kubectl", *args], input=data, text=True, capture_output=True)
if result.returncode:
raise RuntimeError(result.stderr.strip() or "kubectl failed")
return result.stdout
def get(kind, name, namespace=None):
args = ["get", kind, name, "--ignore-not-found", "-o", "json"]
if namespace:
args += ["-n", namespace]
value = kubectl(*args).strip()
return json.loads(value) if value else None
def owned(obj):
return obj and obj.get("metadata", {}).get("labels", {}).get(OWNER) == "true"
def check_owned(kind, name, namespace=None):
obj = get(kind, name, namespace)
if obj and not owned(obj):
raise RuntimeError(f"{kind}/{name} already exists and is not owned by this lab")
return obj
def install():
namespace = check_owned("namespace", NAMESPACE)
app = check_owned("application", "progressive-lab", "argocd")
# A pre-existing ServiceMonitor could belong to another deployment.
monitor = get("servicemonitor", "progressive-lab", "monitoring")
if monitor and not app:
raise RuntimeError("monitoring/ServiceMonitor progressive-lab already exists")
if not get("crd", "servicemonitors.monitoring.coreos.com"):
raise RuntimeError("Prometheus Operator ServiceMonitor CRD is missing; deploy monitoring first")
if not namespace:
kubectl("create", "-f", "-", data=json.dumps({"apiVersion": "v1", "kind": "Namespace", "metadata": {"name": NAMESPACE, "labels": {OWNER: "true"}}}))
if not app:
repo = os.environ.get("TF_VAR_gitops_repo_url") or os.environ.get("LAB_GITOPS_REPO_URL") or "ssh://git@192.168.100.73:32222/jv/my-homelab-configs.git"
app = {"apiVersion": "argoproj.io/v1alpha1", "kind": "Application", "metadata": {"name": "progressive-lab", "namespace": "argocd", "labels": {OWNER: "true"}}, "spec": {"project": "default", "source": {"repoURL": repo, "targetRevision": "main", "path": "apps/progressive-lab", "helm": {"valuesObject": {"canaryWeight": 0, "canaryFailure": False, "badReadiness": False}}}, "destination": {"server": "https://kubernetes.default.svc", "namespace": NAMESPACE}, "syncPolicy": {"automated": {"prune": True, "selfHeal": True}}}}
kubectl("create", "-f", "-", data=json.dumps(app))
print("Argo CD application requested. Run ./jeannie progressive-lab run to start the experiment.")
def set_values(weight, failure=False, readiness=False):
if not owned(get("application", "progressive-lab", "argocd")):
raise RuntimeError("Lab application is missing or not owned by Jeannie; run apply first")
patch = {"spec": {"source": {"helm": {"valuesObject": {"canaryWeight": weight, "canaryFailure": failure, "badReadiness": readiness}}}}}
kubectl("-n", "argocd", "patch", "application", "progressive-lab", "--type=merge", "-p", json.dumps(patch))
def wait_values(weight, failure, readiness):
for _ in range(150):
router = get("deployment", "progressive-router", NAMESPACE)
canary = get("deployment", "progressive-canary", NAMESPACE)
if router and canary:
router_env = router["spec"]["template"]["spec"]["containers"][0].get("env", [])
container = canary["spec"]["template"]["spec"]["containers"][0]
env = {entry["name"]: entry["value"] for entry in container.get("env", [])}
path = container["readinessProbe"]["httpGet"]["path"]
if {e["name"]: e["value"] for e in router_env}.get("CANARY_WEIGHT") == str(weight) and env.get("DEMO_FAIL") == str(failure).lower() and path == ("/unready" if readiness else "/health"):
break
time.sleep(2)
else:
raise RuntimeError("Argo CD did not reconcile the requested lab parameters")
for name in ("progressive-stable", "progressive-router"):
kubectl("-n", NAMESPACE, "rollout", "status", f"deployment/{name}", "--timeout=180s")
if not readiness:
kubectl("-n", NAMESPACE, "rollout", "status", "deployment/progressive-canary", "--timeout=180s")
else:
for _ in range(90):
dep = get("deployment", "progressive-canary", NAMESPACE)
endpoints = get("endpoints", "progressive-canary", NAMESPACE)
addresses = [a for subset in (endpoints or {}).get("subsets", []) for a in subset.get("addresses", [])]
if dep and dep.get("status", {}).get("observedGeneration", 0) >= dep["metadata"]["generation"] and not addresses:
break
time.sleep(2)
else:
raise RuntimeError("Canary still has ready endpoints; readiness failure was not observed")
@contextmanager
def forward():
with socket.socket() as sock:
sock.bind(("127.0.0.1", 0))
port = sock.getsockname()[1]
proc = subprocess.Popen(["kubectl", "-n", NAMESPACE, "port-forward", "--address", "127.0.0.1", "service/progressive-router", f"{port}:8080"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
for _ in range(50):
if proc.poll() is not None:
raise RuntimeError("Router port-forward failed")
try:
with socket.create_connection(("127.0.0.1", port), timeout=0.2):
break
except OSError:
time.sleep(0.2)
else:
raise RuntimeError("Router port-forward timed out")
yield port
finally:
proc.terminate()
proc.wait(timeout=10)
def read_metrics(port):
with urllib.request.urlopen(f"http://127.0.0.1:{port}/metrics", timeout=5) as response:
lines = response.read().decode().splitlines()
values = {}
for line in lines:
match = METRIC.fullmatch(line)
if match:
values[(match.group(1), match.group(2))] = int(match.group(3))
if len(values) != 4:
raise RuntimeError("Router metrics are incomplete")
return values
def exercise(port, requests=120):
before = read_metrics(port)
for _ in range(requests):
try:
with urllib.request.urlopen(f"http://127.0.0.1:{port}/", timeout=5) as response:
response.read()
except urllib.error.HTTPError as exc:
exc.close()
after = read_metrics(port)
delta = {key: after[key] - before[key] for key in before}
if any(value < 0 for value in delta.values()):
raise RuntimeError("Router restarted during the measurement")
return delta
def run(scenario):
if scenario not in ("errors", "readiness"):
raise RuntimeError("Choose errors or readiness")
failure, readiness = scenario == "errors", scenario == "readiness"
try:
set_values(10, failure, readiness)
wait_values(10, failure, readiness)
with forward() as port:
counts = exercise(port)
total = counts[("canary", "success")] + counts[("canary", "error")]
rate = counts[("canary", "error")] / total if total else 0
print(json.dumps({"scenario": scenario, "canary_requests": total, "canary_errors": counts[("canary", "error")], "canary_error_rate": round(rate, 3), "stable_successes": counts[("stable", "success")], "threshold": 0.1}, indent=2))
if total < 5:
raise RuntimeError("Too few canary samples to evaluate the error rate")
if not counts[("stable", "success")]:
raise RuntimeError("No successful stable requests were observed")
if rate <= 0.1:
raise RuntimeError("Expected failing canary did not exceed the error threshold")
print("Canary error threshold exceeded; rolling back.")
finally:
set_values(0)
wait_values(0, False, False)
print("Rollback reconciled: canary traffic is 0%.")
def main():
action = sys.argv[1] if len(sys.argv) > 1 else "plan"
if action == "plan":
print(json.dumps({"profile": os.environ.get("LAB_CLUSTER_PROFILE"), "route": "internal ClusterIP", "experiment": "10% canary, sampled errors, rollback to 0%", "metrics": "router Prometheus counter and ServiceMonitor"}, indent=2))
elif action == "apply":
install()
elif action == "run":
run(sys.argv[2] if len(sys.argv) > 2 else "errors")
elif action == "rollback":
set_values(0)
wait_values(0, False, False)
print("Rollback reconciled: canary traffic is 0%.")
elif action == "status":
print(kubectl("-n", NAMESPACE, "get", "deployments,services", "--ignore-not-found"))
app = get("application", "progressive-lab", "argocd")
if app:
print(json.dumps(app.get("spec", {}).get("source", {}).get("helm", {}).get("valuesObject", {}), indent=2))
else:
raise RuntimeError("Usage: ./jeannie progressive-lab {plan|apply|status|run [errors|readiness]|rollback}")
if __name__ == "__main__":
try:
main()
except (RuntimeError, ValueError, OSError, KeyError) as exc:
print(f"Progressive lab: {exc}", file=sys.stderr)
sys.exit(1)