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

180 lines
8.7 KiB
Python

#!/usr/bin/env python3
"""Opt-in Gateway API learning lab; never modifies the existing ingress."""
import json
import os
import re
import socket
import subprocess
import sys
import time
import urllib.request
from contextlib import contextmanager
import yaml
VERSION = "v1.5.1"
URL = f"https://github.com/kubernetes-sigs/gateway-api/releases/download/{VERSION}/standard-install.yaml"
CRDS = {f"{name}.gateway.networking.k8s.io" for name in (
"gatewayclasses", "gateways", "grpcroutes", "httproutes", "referencegrants",
"backendtlspolicies", "listenersets", "tlsroutes",
)}
OWNER = "homelab.dev/gateway-lab"
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]
result = kubectl(*args).strip()
return json.loads(result) if result else None
def crd_actions(existing):
"""Refuse to change a pre-existing CRD of unknown provenance or version."""
for name, obj in existing.items():
meta = obj.get("metadata", {})
if meta.get("labels", {}).get(OWNER) == VERSION:
continue
if meta.get("annotations", {}).get("gateway.networking.k8s.io/bundle-version") == VERSION:
continue
raise RuntimeError(f"{name} already exists with a different or unknown Gateway API version; review it before installing this lab")
return CRDS - existing.keys()
def bundle():
with urllib.request.urlopen(URL, timeout=30) as response:
contents = response.read(10_000_001)
if len(contents) > 10_000_000:
raise RuntimeError("Gateway API bundle exceeds the size limit")
docs = [d for d in yaml.safe_load_all(contents) if isinstance(d, dict) and d.get("kind") == "CustomResourceDefinition"]
by_name = {d["metadata"]["name"]: d for d in docs}
if set(by_name) != CRDS:
raise RuntimeError("Gateway API bundle does not contain the expected standard CRDs")
for name, obj in by_name.items():
spec = obj.get("spec", {})
if obj.get("apiVersion") != "apiextensions.k8s.io/v1" or spec.get("group") != "gateway.networking.k8s.io" or spec.get("names", {}).get("plural") != name.split(".")[0]:
raise RuntimeError(f"Unexpected Gateway API CRD: {name}")
obj["metadata"].setdefault("labels", {})[OWNER] = VERSION
return by_name
def install():
for service in ("otel-lab-collector", "otel-lab-tempo"):
if not get("service", service, "monitoring"):
raise RuntimeError(f"monitoring/{service} is missing; deploy the OpenTelemetry lab first")
ns = get("namespace", "gateway-lab")
if ns and ns.get("metadata", {}).get("labels", {}).get(OWNER) != "true":
raise RuntimeError("Namespace gateway-lab already exists without the lab ownership label")
for kind, name, namespace in (("application", "gateway-lab", "argocd"), ("clusterrole", "jeannie-gateway-lab", None), ("clusterrolebinding", "jeannie-gateway-lab", None)):
obj = get(kind, name, namespace)
if obj and obj.get("metadata", {}).get("labels", {}).get(OWNER) != "true":
raise RuntimeError(f"{kind}/{name} already exists without the lab ownership label")
existing = {name: obj for name in CRDS if (obj := get("crd", name))}
missing = crd_actions(existing)
# GatewayClass is only queryable once its CRD exists.
if "gatewayclasses.gateway.networking.k8s.io" in existing:
obj = get("gatewayclass", "jeannie-gateway-lab")
if obj and obj.get("metadata", {}).get("labels", {}).get(OWNER) != "true":
raise RuntimeError("GatewayClass jeannie-gateway-lab already exists without the lab ownership label")
if missing:
docs = bundle()
payload = "\n---\n".join(yaml.safe_dump(docs[name]) for name in sorted(missing))
kubectl("apply", "--server-side", "--dry-run=server", "-f", "-", data=payload)
kubectl("apply", "--server-side", "-f", "-", data=payload)
for name in sorted(CRDS):
kubectl("wait", "--for=condition=Established", "--timeout=120s", f"crd/{name}")
if not ns:
kubectl("apply", "-f", "-", data=yaml.safe_dump({"apiVersion": "v1", "kind": "Namespace", "metadata": {"name": "gateway-lab", "labels": {OWNER: "true"}}}))
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": "gateway-lab", "namespace": "argocd", "labels": {OWNER: "true"}}, "spec": {"project": "default", "source": {"repoURL": repo, "targetRevision": "main", "path": "apps/gateway-lab"}, "destination": {"server": "https://kubernetes.default.svc", "namespace": "gateway-lab"}, "syncPolicy": {"automated": {"prune": True, "selfHeal": True}}}}
kubectl("apply", "-f", "-", data=yaml.safe_dump(app))
print("Gateway lab requested through Argo CD. Run ./jeannie gateway-lab test after synchronization.")
@contextmanager
def forward(namespace, service, port):
with socket.socket() as sock:
sock.bind(("127.0.0.1", 0))
local = sock.getsockname()[1]
process = subprocess.Popen(["kubectl", "-n", namespace, "port-forward", "--address", "127.0.0.1", f"service/{service}", f"{local}:{port}"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
for _ in range(50):
if process.poll() is not None:
raise RuntimeError(f"Port forwarding {service} failed")
try:
with socket.create_connection(("127.0.0.1", local), timeout=0.2):
break
except OSError:
time.sleep(0.2)
else:
raise RuntimeError(f"Port forwarding {service} timed out")
yield local
finally:
process.terminate()
process.wait(timeout=10)
def test():
for name in ("gateway-lab-proxy", "gateway-lab-api"):
for _ in range(150):
if get("deployment", name, "gateway-lab"):
break
time.sleep(2)
else:
raise RuntimeError(f"Deployment {name} was not created; inspect the gateway-lab Argo CD application")
print(kubectl("-n", "gateway-lab", "rollout", "status", f"deployment/{name}", "--timeout=300s").strip())
with forward("gateway-lab", "gateway-lab-proxy", 8000) as port:
request = urllib.request.Request(f"http://127.0.0.1:{port}/api/info", headers={"Host": "gateway-lab.localhost"})
for attempt in range(30):
try:
with urllib.request.urlopen(request, timeout=5) as response:
body = json.load(response)
break
except OSError:
if attempt == 29:
raise RuntimeError("Gateway did not route the FastAPI request; check the Gateway and HTTPRoute status")
time.sleep(2)
trace_id = body.get("trace_id", "")
if not re.fullmatch(r"[0-9a-f]{32}", trace_id) or trace_id == "0" * 32:
raise RuntimeError("FastAPI did not return a valid trace ID")
print(f"Gateway routed FastAPI request. Trace ID: {trace_id}")
with forward("monitoring", "otel-lab-tempo", 3200) as port:
for _ in range(30):
try:
with urllib.request.urlopen(f"http://127.0.0.1:{port}/api/traces/{trace_id}", timeout=3) as response:
if response.status == 200:
print("Trace found in Tempo.")
return
except (OSError, urllib.error.HTTPError):
time.sleep(2)
raise RuntimeError("Gateway request succeeded, but its trace was not found in Tempo within 60 seconds")
def main():
action = sys.argv[1] if len(sys.argv) > 1 else "plan"
if action == "apply":
install()
elif action == "test":
test()
elif action == "status":
print(kubectl("-n", "gateway-lab", "get", "deployments,services,gateways,httproutes", "--ignore-not-found"))
elif action == "plan":
print(json.dumps({"profile": os.environ.get("LAB_CLUSTER_PROFILE"), "gateway_api_version": VERSION, "scope": "internal ClusterIP only", "actions": ["install missing compatible standard CRDs", "create isolated Traefik and FastAPI via Argo CD", "send application traces to existing Tempo lab"], "existing_ingress": "unchanged"}, indent=2))
else:
raise RuntimeError("Usage: ./jeannie gateway-lab {plan|apply|status|test}")
if __name__ == "__main__":
try:
main()
except (RuntimeError, OSError, ValueError, yaml.YAMLError) as exc:
print(f"Gateway lab: {exc}", file=sys.stderr)
sys.exit(1)