Add isolated Gateway API FastAPI lab
This commit is contained in:
parent
f12bcc34c0
commit
ef60a6ec4e
|
|
@ -0,0 +1,45 @@
|
|||
# Gateway API and FastAPI lab
|
||||
|
||||
This optional lab demonstrates a GatewayClass, Gateway and HTTPRoute using a
|
||||
dedicated Traefik controller and a FastAPI backend. The proxy is a ClusterIP
|
||||
service; the existing Traefik deployment, Ingress resources and public routes
|
||||
are untouched. The controller watches only the lab namespace and the labeled
|
||||
lab GatewayClass. Gateway API CRDs are cluster-wide: Jeannie installs the
|
||||
missing standard v1.5.1 CRDs and refuses unknown or different existing versions.
|
||||
It does not install the release's optional admission policy or remove CRDs.
|
||||
|
||||
The FastAPI service exports real spans to the OpenTelemetry lab collector.
|
||||
The API's `/api/info` response contains the trace ID. Jeannie verifies it reaches
|
||||
Tempo, so the test needs the existing `opentelemetry-lab` application. The demo
|
||||
installs its pinned direct Python dependencies from PyPI in an init container;
|
||||
the node needs internet access each time a new API pod starts. This is a small
|
||||
learning lab, not an offline or production image build.
|
||||
|
||||
From the Debian server after pushing this code to the GitOps main branch:
|
||||
|
||||
```sh
|
||||
cd ~/my-homelab-configs
|
||||
git pull --ff-only gitea main
|
||||
./jeannie gateway-lab plan
|
||||
./jeannie gateway-lab apply
|
||||
./jeannie gateway-lab status
|
||||
./jeannie gateway-lab test
|
||||
```
|
||||
|
||||
Argo CD synchronization and the first dependency download may take a few
|
||||
minutes. `test` waits for both deployments, makes a request through the Gateway,
|
||||
and checks the resulting trace in Tempo. The selected Jeannie cluster profile and
|
||||
its pinned identity apply to all commands. The deployment uses the configured
|
||||
GitOps repository's `main` branch, so push first.
|
||||
|
||||
To explore the automatic FastAPI documentation from Debian:
|
||||
|
||||
```sh
|
||||
kubectl --kubeconfig="$HOME/.kube/opi5-k3s-config" -n gateway-lab \
|
||||
port-forward --address 127.0.0.1 service/gateway-lab-proxy 18080:8000
|
||||
```
|
||||
|
||||
Open `http://gateway-lab.localhost:18080/docs` on that host; use an SSH local
|
||||
port forward from another machine. Use the kubeconfig for the selected profile
|
||||
if running a mixed or all-Pimox cluster. The port forward remains local and does
|
||||
not publish a new external endpoint.
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
import os
|
||||
|
||||
from fastapi import FastAPI
|
||||
from opentelemetry import trace
|
||||
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
|
||||
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
|
||||
from opentelemetry.sdk.resources import Resource
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
||||
|
||||
provider = TracerProvider(resource=Resource.create({"service.name": "gateway-fastapi-demo"}))
|
||||
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter(
|
||||
endpoint=os.getenv("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "http://otel-lab-collector.monitoring.svc:4318/v1/traces")
|
||||
)))
|
||||
trace.set_tracer_provider(provider)
|
||||
app = FastAPI(title="Jeannie Gateway API Lab")
|
||||
FastAPIInstrumentor.instrument_app(app, excluded_urls="health")
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
def health():
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.get("/api/info")
|
||||
def info():
|
||||
with trace.get_tracer(__name__).start_as_current_span("demo.compute") as span:
|
||||
return {
|
||||
"message": "Hello from FastAPI behind Gateway API",
|
||||
"trace_id": format(span.get_span_context().trace_id, "032x"),
|
||||
}
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
apiVersion: kustomize.config.k8s.io/v1beta1
|
||||
kind: Kustomization
|
||||
namespace: gateway-lab
|
||||
resources:
|
||||
- resources.yaml
|
||||
configMapGenerator:
|
||||
- name: gateway-lab-api
|
||||
files:
|
||||
- api.py
|
||||
- requirements.txt
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
fastapi==0.115.6
|
||||
uvicorn==0.34.0
|
||||
opentelemetry-api==1.29.0
|
||||
opentelemetry-sdk==1.29.0
|
||||
opentelemetry-exporter-otlp-proto-http==1.29.0
|
||||
opentelemetry-instrumentation-fastapi==0.50b0
|
||||
|
|
@ -0,0 +1,244 @@
|
|||
apiVersion: v1
|
||||
kind: ServiceAccount
|
||||
metadata:
|
||||
name: gateway-lab-controller
|
||||
---
|
||||
apiVersion: rbac.authorization.k8s.io/v1
|
||||
kind: ClusterRole
|
||||
metadata:
|
||||
name: jeannie-gateway-lab
|
||||
labels:
|
||||
homelab.dev/gateway-lab: "true"
|
||||
rules:
|
||||
- apiGroups: [""]
|
||||
resources: ["namespaces"]
|
||||
verbs: ["get", "list", "watch"]
|
||||
- apiGroups: ["gateway.networking.k8s.io"]
|
||||
resources: ["gatewayclasses"]
|
||||
verbs: ["get", "list", "watch"]
|
||||
- apiGroups: ["gateway.networking.k8s.io"]
|
||||
resources: ["gatewayclasses/status"]
|
||||
verbs: ["update", "patch"]
|
||||
---
|
||||
apiVersion: rbac.authorization.k8s.io/v1
|
||||
kind: ClusterRoleBinding
|
||||
metadata:
|
||||
name: jeannie-gateway-lab
|
||||
labels:
|
||||
homelab.dev/gateway-lab: "true"
|
||||
roleRef:
|
||||
apiGroup: rbac.authorization.k8s.io
|
||||
kind: ClusterRole
|
||||
name: jeannie-gateway-lab
|
||||
subjects:
|
||||
- kind: ServiceAccount
|
||||
name: gateway-lab-controller
|
||||
namespace: gateway-lab
|
||||
---
|
||||
apiVersion: rbac.authorization.k8s.io/v1
|
||||
kind: Role
|
||||
metadata:
|
||||
name: gateway-lab-controller
|
||||
rules:
|
||||
- apiGroups: [""]
|
||||
resources: ["services", "endpoints", "secrets", "configmaps"]
|
||||
verbs: ["get", "list", "watch"]
|
||||
- apiGroups: ["discovery.k8s.io"]
|
||||
resources: ["endpointslices"]
|
||||
verbs: ["get", "list", "watch"]
|
||||
- apiGroups: ["gateway.networking.k8s.io"]
|
||||
resources: ["gateways", "httproutes", "grpcroutes", "referencegrants", "backendtlspolicies", "tlsroutes", "listenersets"]
|
||||
verbs: ["get", "list", "watch"]
|
||||
- apiGroups: ["gateway.networking.k8s.io"]
|
||||
resources: ["gateways/status", "httproutes/status", "grpcroutes/status", "tlsroutes/status", "backendtlspolicies/status", "listenersets/status"]
|
||||
verbs: ["update", "patch"]
|
||||
---
|
||||
apiVersion: rbac.authorization.k8s.io/v1
|
||||
kind: RoleBinding
|
||||
metadata:
|
||||
name: gateway-lab-controller
|
||||
roleRef:
|
||||
apiGroup: rbac.authorization.k8s.io
|
||||
kind: Role
|
||||
name: gateway-lab-controller
|
||||
subjects:
|
||||
- kind: ServiceAccount
|
||||
name: gateway-lab-controller
|
||||
namespace: gateway-lab
|
||||
---
|
||||
apiVersion: gateway.networking.k8s.io/v1
|
||||
kind: GatewayClass
|
||||
metadata:
|
||||
name: jeannie-gateway-lab
|
||||
labels:
|
||||
homelab.dev/gateway-lab: "true"
|
||||
spec:
|
||||
controllerName: traefik.io/gateway-controller
|
||||
---
|
||||
apiVersion: gateway.networking.k8s.io/v1
|
||||
kind: Gateway
|
||||
metadata:
|
||||
name: gateway-lab
|
||||
labels:
|
||||
homelab.dev/gateway-lab: "true"
|
||||
spec:
|
||||
gatewayClassName: jeannie-gateway-lab
|
||||
listeners:
|
||||
- name: web
|
||||
port: 8000
|
||||
protocol: HTTP
|
||||
hostname: gateway-lab.localhost
|
||||
allowedRoutes:
|
||||
namespaces:
|
||||
from: Same
|
||||
---
|
||||
apiVersion: gateway.networking.k8s.io/v1
|
||||
kind: HTTPRoute
|
||||
metadata:
|
||||
name: gateway-lab
|
||||
labels:
|
||||
homelab.dev/gateway-lab: "true"
|
||||
spec:
|
||||
parentRefs:
|
||||
- name: gateway-lab
|
||||
hostnames: [gateway-lab.localhost]
|
||||
rules:
|
||||
- matches:
|
||||
- path:
|
||||
type: PathPrefix
|
||||
value: /
|
||||
backendRefs:
|
||||
- name: gateway-lab-api
|
||||
port: 8080
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: gateway-lab-proxy
|
||||
spec:
|
||||
selector:
|
||||
app: gateway-lab-proxy
|
||||
ports:
|
||||
- name: web
|
||||
port: 8000
|
||||
targetPort: web
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: gateway-lab-proxy
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: gateway-lab-proxy
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: gateway-lab-proxy
|
||||
spec:
|
||||
serviceAccountName: gateway-lab-controller
|
||||
containers:
|
||||
- name: traefik
|
||||
image: traefik:v3.7.1
|
||||
args:
|
||||
- --providers.kubernetesgateway=true
|
||||
- --providers.kubernetesgateway.namespaces=gateway-lab
|
||||
- --providers.kubernetesgateway.labelselector=homelab.dev/gateway-lab=true
|
||||
- --entrypoints.web.address=:8000
|
||||
- --entrypoints.traefik.address=:9000
|
||||
- --ping=true
|
||||
ports:
|
||||
- name: web
|
||||
containerPort: 8000
|
||||
- name: health
|
||||
containerPort: 9000
|
||||
readinessProbe:
|
||||
httpGet:
|
||||
path: /ping
|
||||
port: health
|
||||
resources:
|
||||
requests: {cpu: 30m, memory: 64Mi}
|
||||
limits: {memory: 256Mi}
|
||||
securityContext:
|
||||
allowPrivilegeEscalation: false
|
||||
capabilities: {drop: [ALL]}
|
||||
runAsNonRoot: true
|
||||
runAsUser: 65532
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: gateway-lab-api
|
||||
spec:
|
||||
selector:
|
||||
app: gateway-lab-api
|
||||
ports:
|
||||
- port: 8080
|
||||
targetPort: http
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: gateway-lab-api
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: gateway-lab-api
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: gateway-lab-api
|
||||
spec:
|
||||
automountServiceAccountToken: false
|
||||
securityContext:
|
||||
runAsNonRoot: true
|
||||
runAsUser: 65532
|
||||
runAsGroup: 65532
|
||||
fsGroup: 65532
|
||||
initContainers:
|
||||
- name: dependencies
|
||||
image: python:3.12-alpine
|
||||
command: ["python", "-m", "pip", "install", "--no-cache-dir", "--target", "/deps", "-r", "/app/requirements.txt"]
|
||||
env:
|
||||
- {name: HOME, value: /tmp}
|
||||
volumeMounts:
|
||||
- {name: app, mountPath: /app, readOnly: true}
|
||||
- {name: deps, mountPath: /deps}
|
||||
resources:
|
||||
requests: {cpu: 50m, memory: 64Mi}
|
||||
limits: {memory: 256Mi}
|
||||
securityContext:
|
||||
allowPrivilegeEscalation: false
|
||||
capabilities: {drop: [ALL]}
|
||||
containers:
|
||||
- name: api
|
||||
image: python:3.12-alpine
|
||||
command: ["python", "-m", "uvicorn", "api:app", "--host", "0.0.0.0", "--port", "8080"]
|
||||
env:
|
||||
- {name: PYTHONPATH, value: "/deps:/app"}
|
||||
- {name: PYTHONDONTWRITEBYTECODE, value: "1"}
|
||||
ports:
|
||||
- {name: http, containerPort: 8080}
|
||||
readinessProbe:
|
||||
httpGet: {path: /health, port: http}
|
||||
livenessProbe:
|
||||
httpGet: {path: /health, port: http}
|
||||
initialDelaySeconds: 10
|
||||
volumeMounts:
|
||||
- {name: app, mountPath: /app, readOnly: true}
|
||||
- {name: deps, mountPath: /deps, readOnly: true}
|
||||
resources:
|
||||
requests: {cpu: 30m, memory: 64Mi}
|
||||
limits: {memory: 256Mi}
|
||||
securityContext:
|
||||
readOnlyRootFilesystem: true
|
||||
allowPrivilegeEscalation: false
|
||||
capabilities: {drop: [ALL]}
|
||||
volumes:
|
||||
- name: app
|
||||
configMap:
|
||||
name: gateway-lab-api
|
||||
- name: deps
|
||||
emptyDir: {}
|
||||
15
jeannie
15
jeannie
|
|
@ -63,6 +63,7 @@ Base, Inventory, And Planning
|
|||
cluster-context {status|check|enroll|migrate} [--yes] [--stack NAME]
|
||||
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.
|
||||
doctor-preapply Run deeper pre-apply safety checks.
|
||||
plan [all|provisioning|cluster|platform|apps|edge]
|
||||
Run OpenTofu plans without applying changes.
|
||||
|
|
@ -253,6 +254,7 @@ runtime_pipeline=false
|
|||
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 ;;
|
||||
esac
|
||||
if "${runtime_pipeline}"; then
|
||||
if [[ "${JEANNIE_RUNTIME_PIPELINE_LOCK:-}" != "${LAB_CLUSTER_PROFILE}" ||
|
||||
|
|
@ -271,6 +273,9 @@ case "${1:-}" in
|
|||
start)
|
||||
if [[ "${2:-plan}" == apply ]]; then cluster_runtime_require || exit 1; fi
|
||||
;;
|
||||
gateway-lab)
|
||||
if [[ "${2:-plan}" == apply ]]; then cluster_runtime_require || exit 1; fi
|
||||
;;
|
||||
__up-task)
|
||||
cluster_runtime_require || exit 1
|
||||
;;
|
||||
|
|
@ -301,6 +306,16 @@ case "${1:-}" in
|
|||
esac
|
||||
|
||||
case "${1:-}" in
|
||||
gateway-lab)
|
||||
[[ $# -le 2 ]] || { echo "Usage: ./jeannie gateway-lab {plan|apply|status|test}" >&2; exit 2; }
|
||||
case "${2:-plan}" in
|
||||
plan|apply|status|test) ;;
|
||||
*) echo "Usage: ./jeannie gateway-lab {plan|apply|status|test}" >&2; exit 2 ;;
|
||||
esac
|
||||
if [[ "${2:-plan}" != plan ]]; then cluster_context_require || exit 1; fi
|
||||
if [[ "${2:-plan}" == apply ]]; then record_change_journal "gateway-lab" "$@"; fi
|
||||
KUBECONFIG="${KUBECONFIG_PATH}" python3 "${REPO_ROOT}/scripts/gateway-lab.py" "${2:-plan}"
|
||||
;;
|
||||
goose-graph)
|
||||
python3 "${REPO_ROOT}/scripts/goose-graph.py" "${@:2}"
|
||||
;;
|
||||
|
|
|
|||
|
|
@ -0,0 +1,179 @@
|
|||
#!/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)
|
||||
|
|
@ -107,6 +107,7 @@ validate_unit_tests() {
|
|||
"${REPO_ROOT}/tests/jeannie-unit"
|
||||
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_doctor_dex_drift.py'
|
||||
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'
|
||||
}
|
||||
|
||||
main() {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,38 @@
|
|||
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("gateway_lab", ROOT / "scripts/gateway-lab.py")
|
||||
lab = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(lab)
|
||||
|
||||
|
||||
class GatewayLabTest(unittest.TestCase):
|
||||
def test_empty_cluster_needs_all_standard_crds(self):
|
||||
self.assertEqual(lab.crd_actions({}), lab.CRDS)
|
||||
|
||||
def test_resume_lab_owned_install(self):
|
||||
name = next(iter(lab.CRDS))
|
||||
self.assertNotIn(name, lab.crd_actions({name: {"metadata": {"labels": {lab.OWNER: lab.VERSION}}}}))
|
||||
|
||||
def test_unknown_existing_crd_is_not_replaced(self):
|
||||
name = next(iter(lab.CRDS))
|
||||
with self.assertRaisesRegex(RuntimeError, "unknown"):
|
||||
lab.crd_actions({name: {"metadata": {}}})
|
||||
|
||||
def test_official_matching_crd_is_reused(self):
|
||||
name = next(iter(lab.CRDS))
|
||||
obj = {"metadata": {"annotations": {"gateway.networking.k8s.io/bundle-version": lab.VERSION}}}
|
||||
self.assertNotIn(name, lab.crd_actions({name: obj}))
|
||||
|
||||
def test_missing_telemetry_stops_before_changes(self):
|
||||
with mock.patch.object(lab, "get", return_value=None), mock.patch.object(lab, "kubectl") as command:
|
||||
with self.assertRaisesRegex(RuntimeError, "OpenTelemetry"):
|
||||
lab.install()
|
||||
command.assert_not_called()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Loading…
Reference in New Issue