Add progressive delivery failure lab

This commit is contained in:
juvenal.diaz 2026-11-10 10:43:35 -06:00
parent dd99af4f58
commit 688fe9f0f0
10 changed files with 486 additions and 0 deletions

View File

@ -0,0 +1,4 @@
apiVersion: v2
name: progressive-lab
version: 0.1.0
description: Disposable canary and rollback learning lab

View File

@ -0,0 +1,41 @@
# Progressive delivery and failure lab
This disposable lab demonstrates a manual canary orchestrated by Jeannie and
Argo CD. A small internal router sends traffic to a stable or canary backend and
exposes Prometheus counters. The Argo CD Application's Helm values are the
runtime control for this experiment; Jeannie updates those values and Argo CD
reconciles the workloads. This is a learning implementation, not Argo Rollouts
or a production traffic manager.
Push the commit first. On Debian, select the cluster profile and run:
```sh
cd ~/my-homelab-configs
git pull --ff-only gitea main
./jeannie progressive-lab plan
./jeannie progressive-lab apply
./jeannie progressive-lab run errors
./jeannie progressive-lab run readiness
```
Each run directs approximately 10% of 120 requests to the canary, compares the
router's `progressive_lab_requests_total` counter before and after, and rolls
back when the expected canary error rate exceeds 10%. The `errors` scenario
returns HTTP 500 from the canary; `readiness` uses an intentionally failing
readiness probe, removing the canary endpoint and producing a router error.
The stable service should continue returning success. Jeannie restores the
canary weight to zero in a `finally` block, including on most command failures.
If Jeannie is interrupted or the API is unavailable, explicitly run:
```sh
./jeannie progressive-lab rollback
./jeannie progressive-lab status
```
The ServiceMonitor exposes router counters to the existing Prometheus stack if
its ServiceMonitor selectors include the `monitoring` namespace and the
`release=prometheus-stack` label. The experiment measures the same counters
directly, so a successful run does not by itself prove Prometheus scraped them.
The router is available only through its ClusterIP and temporary local port
forward; existing public routes are unchanged. It is deliberately simple and
does not implement production-grade retries, traffic management, or analysis.

View File

@ -0,0 +1,20 @@
import os
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/health":
code, body = 200, b"ready\n"
elif self.path == "/unready":
code, body = 503, b"deliberately unready\n"
elif os.environ.get("DEMO_FAIL") == "true":
code, body = 500, b"deliberate canary failure\n"
else:
code, body = 200, (os.environ["VERSION"] + "\n").encode()
self.send_response(code)
self.end_headers()
self.wfile.write(body)
ThreadingHTTPServer(("0.0.0.0", 8080), Handler).serve_forever()

View File

@ -0,0 +1,46 @@
import os
import random
import threading
import urllib.error
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
weight = int(os.environ["CANARY_WEIGHT"])
counts = {(version, outcome): 0 for version in ("stable", "canary") for outcome in ("success", "error")}
lock = threading.Lock()
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/health":
self.send_response(200)
self.end_headers()
return
if self.path == "/metrics":
with lock:
body = "# TYPE progressive_lab_requests_total counter\n" + "".join(
f'progressive_lab_requests_total{{version="{v}",outcome="{o}"}} {count}\n'
for (v, o), count in counts.items()
)
self.send_response(200)
self.send_header("Content-Type", "text/plain; version=0.0.4")
self.end_headers()
self.wfile.write(body.encode())
return
version = "canary" if random.randrange(100) < weight else "stable"
try:
with urllib.request.urlopen(f"http://progressive-{version}:8080/", timeout=2) as response:
code, body = response.status, response.read()
except urllib.error.HTTPError as exc:
code, body = exc.code, b"upstream error\n"
except (OSError, ValueError):
code, body = 503, b"upstream unavailable\n"
with lock:
counts[version, "success" if code < 500 else "error"] += 1
self.send_response(code)
self.send_header("X-Demo-Version", version)
self.end_headers()
self.wfile.write(body)
ThreadingHTTPServer(("0.0.0.0", 8080), Handler).serve_forever()

View File

@ -0,0 +1,106 @@
apiVersion: v1
kind: ConfigMap
metadata:
name: progressive-lab-code
data:
backend.py: |
{{ .Files.Get "files/backend.py" | indent 4 }}
router.py: |
{{ .Files.Get "files/router.py" | indent 4 }}
---
{{- range $version := list "stable" "canary" }}
apiVersion: apps/v1
kind: Deployment
metadata:
name: progressive-{{ $version }}
spec:
replicas: 1
strategy: {type: Recreate}
selector:
matchLabels: {app: progressive-{{ $version }}}
template:
metadata:
labels: {app: progressive-{{ $version }}}
annotations:
code-hash: {{ $.Files.Get "files/backend.py" | sha256sum | quote }}
spec:
automountServiceAccountToken: false
securityContext: {runAsNonRoot: true, runAsUser: 65532, runAsGroup: 65532, seccompProfile: {type: RuntimeDefault}}
containers:
- name: app
image: python:3.12-alpine
command: ["python", "-B", "/app/backend.py"]
env:
- {name: VERSION, value: {{ $version | quote }}}
- {name: DEMO_FAIL, value: {{ and (eq $version "canary") $.Values.canaryFailure | quote }}}
ports: [{name: http, containerPort: 8080}]
readinessProbe:
httpGet:
path: {{ if and (eq $version "canary") $.Values.badReadiness }}/unready{{ else }}/health{{ end }}
port: http
periodSeconds: 3
resources:
requests: {cpu: 10m, memory: 32Mi}
limits: {memory: 128Mi}
securityContext: {allowPrivilegeEscalation: false, readOnlyRootFilesystem: true, capabilities: {drop: [ALL]}}
volumeMounts: [{name: code, mountPath: /app, readOnly: true}]
volumes: [{name: code, configMap: {name: progressive-lab-code}}]
---
apiVersion: v1
kind: Service
metadata:
name: progressive-{{ $version }}
spec:
selector: {app: progressive-{{ $version }}}
ports: [{name: http, port: 8080, targetPort: http}]
---
{{- end }}
apiVersion: apps/v1
kind: Deployment
metadata:
name: progressive-router
spec:
replicas: 1
selector:
matchLabels: {app: progressive-router}
template:
metadata:
labels: {app: progressive-router}
annotations:
code-hash: {{ .Files.Get "files/router.py" | sha256sum | quote }}
spec:
automountServiceAccountToken: false
securityContext: {runAsNonRoot: true, runAsUser: 65532, runAsGroup: 65532, seccompProfile: {type: RuntimeDefault}}
containers:
- name: router
image: python:3.12-alpine
command: ["python", "-B", "/app/router.py"]
env: [{name: CANARY_WEIGHT, value: {{ .Values.canaryWeight | quote }}}]
ports: [{name: http, containerPort: 8080}]
readinessProbe: {httpGet: {path: /health, port: http}}
resources:
requests: {cpu: 10m, memory: 32Mi}
limits: {memory: 128Mi}
securityContext: {allowPrivilegeEscalation: false, readOnlyRootFilesystem: true, capabilities: {drop: [ALL]}}
volumeMounts: [{name: code, mountPath: /app, readOnly: true}]
volumes: [{name: code, configMap: {name: progressive-lab-code}}]
---
apiVersion: v1
kind: Service
metadata:
name: progressive-router
labels: {app: progressive-router}
spec:
selector: {app: progressive-router}
ports: [{name: http, port: 8080, targetPort: http}]
---
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: progressive-lab
namespace: monitoring
labels: {release: prometheus-stack}
spec:
namespaceSelector: {matchNames: [progressive-lab]}
selector: {matchLabels: {app: progressive-router}}
endpoints: [{port: http, path: /metrics, interval: 15s}]

View File

@ -0,0 +1,3 @@
canaryWeight: 0
canaryFailure: false
badReadiness: false

15
jeannie
View File

@ -64,6 +64,7 @@ Base, Inventory, And Planning
Review pinned cluster identity and scoped state.
preflight Run non-mutating infrastructure preflight checks.
gateway-lab {plan|apply|status|test} Manage the isolated Gateway API and FastAPI lab.
progressive-lab {plan|apply|status|run|rollback} Practice canary rollout and rollback.
secrets-lab {plan|apply|status|test|rotate|recover|recover-cert} Practice secret and certificate lifecycle.
doctor-preapply Run deeper pre-apply safety checks.
plan [all|provisioning|cluster|platform|apps|edge]
@ -256,6 +257,7 @@ case "${1:-}" in
up|cluster|platform|apps|start-cluster) runtime_pipeline=true ;;
start) [[ "${2:-plan}" != apply ]] || runtime_pipeline=true ;;
gateway-lab) [[ "${2:-plan}" != apply ]] || runtime_pipeline=true ;;
progressive-lab) case "${2:-plan}" in apply|run|rollback) runtime_pipeline=true ;; esac ;;
secrets-lab) case "${2:-plan}" in apply|test|rotate|recover|recover-cert) runtime_pipeline=true ;; esac ;;
esac
if "${runtime_pipeline}"; then
@ -278,6 +280,9 @@ case "${1:-}" in
gateway-lab)
if [[ "${2:-plan}" == apply ]]; then cluster_runtime_require || exit 1; fi
;;
progressive-lab)
case "${2:-plan}" in apply|run|rollback) cluster_runtime_require || exit 1 ;; esac
;;
secrets-lab)
case "${2:-plan}" in apply|test|rotate|recover|recover-cert) cluster_runtime_require || exit 1 ;; esac
;;
@ -311,6 +316,16 @@ case "${1:-}" in
esac
case "${1:-}" in
progressive-lab)
[[ $# -le 3 && ( $# -le 2 || "${2:-}" == run ) ]] || { echo "Usage: ./jeannie progressive-lab {plan|apply|status|run [errors|readiness]|rollback}" >&2; exit 2; }
case "${2:-plan}" in
plan|apply|status|run|rollback) ;;
*) echo "Usage: ./jeannie progressive-lab {plan|apply|status|run [errors|readiness]|rollback}" >&2; exit 2 ;;
esac
if [[ "${2:-plan}" != plan ]]; then cluster_context_require || exit 1; fi
case "${2:-plan}" in apply|run|rollback) record_change_journal "progressive-lab" "$@" ;; esac
KUBECONFIG="${KUBECONFIG_PATH}" python3 "${REPO_ROOT}/scripts/progressive-lab.py" "${@:2}"
;;
secrets-lab)
[[ $# -le 2 ]] || { echo "Usage: ./jeannie secrets-lab {plan|apply|status|test|rotate|recover|recover-cert}" >&2; exit 2; }
case "${2:-plan}" in

202
scripts/progressive-lab.py Normal file
View File

@ -0,0 +1,202 @@
#!/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)

View File

@ -72,6 +72,16 @@ validate_yaml() {
echo "ruby not installed; skipping generic YAML parse"
}
validate_progressive_chart() {
if ! command -v helm >/dev/null 2>&1; then
echo "helm not installed; skipping progressive lab chart rendering"
return 0
fi
helm template progressive-lab "${REPO_ROOT}/apps/progressive-lab" >/dev/null
helm template progressive-lab "${REPO_ROOT}/apps/progressive-lab" --set canaryWeight=10 --set canaryFailure=true >/dev/null
helm template progressive-lab "${REPO_ROOT}/apps/progressive-lab" --set canaryWeight=10 --set badReadiness=true >/dev/null
}
validate_tofu_fmt() {
if ! command -v tofu >/dev/null 2>&1; then
echo "tofu not installed; skipping fmt check"
@ -109,6 +119,7 @@ validate_unit_tests() {
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_opentelemetry_lab.py'
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_gateway_lab.py'
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_secrets_lab.py'
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_progressive_lab.py'
}
main() {
@ -119,6 +130,7 @@ main() {
run_step "Bash syntax" validate_bash_syntax
run_step "Shellcheck" validate_shellcheck
run_step "YAML parse" validate_yaml
run_step "Progressive lab chart" validate_progressive_chart
run_step "Go checks" validate_go
run_step "OpenTofu formatting" validate_tofu_fmt
run_step "Security static checks" validate_security_static

View File

@ -0,0 +1,37 @@
import importlib.util
from pathlib import Path
import unittest
from unittest import mock
ROOT = Path(__file__).resolve().parents[2]
spec = importlib.util.spec_from_file_location("progressive_lab", ROOT / "scripts/progressive-lab.py")
lab = importlib.util.module_from_spec(spec)
spec.loader.exec_module(lab)
class ProgressiveLabTest(unittest.TestCase):
def test_refuses_to_adopt_unowned_app(self):
with mock.patch.object(lab, "get", return_value={"metadata": {}}):
with self.assertRaisesRegex(RuntimeError, "not owned"):
lab.check_owned("application", "progressive-lab", "argocd")
def test_metrics_parser_matches_expected_counter(self):
match = lab.METRIC.fullmatch('progressive_lab_requests_total{version="canary",outcome="error"} 42')
self.assertEqual(match.groups(), ("canary", "error", "42"))
self.assertIsNone(lab.METRIC.fullmatch('progressive_lab_requests_total{version="other",outcome="error"} 42'))
def test_run_rolls_back_after_failed_measurement(self):
with mock.patch.object(lab, "set_values") as values, mock.patch.object(lab, "wait_values", side_effect=[RuntimeError("failure"), None]):
with self.assertRaisesRegex(RuntimeError, "failure"):
lab.run("errors")
self.assertEqual(values.call_args_list, [mock.call(10, True, False), mock.call(0)])
def test_invalid_scenario_never_changes_weights(self):
with mock.patch.object(lab, "set_values") as values:
with self.assertRaisesRegex(RuntimeError, "Choose"):
lab.run("unknown")
values.assert_not_called()
if __name__ == "__main__":
unittest.main()