my-homelab-configs/docs/templates/architecture.md.tmpl

409 lines
20 KiB
Cheetah

# Homelab Architecture & Infrastructure
## Architecture
The lab is intentionally small but production-shaped:
- Debian remains the always-on operations host for Jeannie, Docker builds,
external Gitea, the GitOps mirror, the local registry endpoint, Ollama,
OmniRoute, and AI tool wrappers
- Kubernetes has three selectable profiles: a laptop kubeadm control plane with
Pimox workers, an entirely virtualized Pimox kubeadm cluster, and native K3s
on the Orange Pi 5 Plus. Only one profile may run at a time
- a Raspberry Pi arm64 host runs selected support services outside the
Kubernetes rebuild blast radius
- the Debian host also runs the always-on Gitea Docker service outside
Kubernetes
- the Debian host keeps a bare GitOps mirror under
`/home/jv/git-server/my-homelab-configs.git`
- a provisioning layer can PXE boot Debian 13 arm64 VMs for Pimox worker
templates
- OpenTofu owns the bootstrap layers for cluster, platform, apps, and edge
- Argo CD continuously reconciles Kubernetes manifests from this repo
- a local registry stores the website and demos images built for the worker
architecture
- a Debian-hosted OmniRoute gateway routes Holmes/goose/Hermes AI calls through
validated free/no-auth, OpenRouter, and NVIDIA-backed models while Ollama
remains available for small local tasks
- the website image keeps Apache as the public server, uses PHP-FPM with
OPcache for dynamic endpoints, and pre-renders read-heavy pages to static
HTML during the image build
- SOPS with age is the committed secret-management path for future encrypted
Kubernetes secrets
- local Jeannie/RAG eval cases exercise troubleshooting explanations and
retrieval grounding without touching live infrastructure
- an OCI jump box provides the public edge path back into the homelab over
Tailscale, with nginx caching, gzip, HTTP/2, TLS session reuse, and upstream
keepalive
## Inventory
The canonical non-secret inventory is [homelab.yml](../homelab.yml). Keep LAN IPs,
Tailscale IPs, public hostnames, ports, storage paths, and service ownership
there before copying values into scripts, OpenTofu variables, runbooks, or
service docs. Secrets and tokens do not belong in that file.
`./{{ main_script }}` reads `homelab.yml` at startup and exports matching OpenTofu
variables for the edge, provisioning, cluster, platform, and apps stacks. This
keeps values such as the Debian LAN IP, Debian Tailscale IP, RPi LAN IP, OCI IP,
Traefik MetalLB IP, and domain name from drifting across scripts and templates.
`scripts/render-docs` also renders [the service catalog](service-catalog.md)
and the static service catalog page at
`apps/demos-static/public/homelab-catalog/index.html` from the same inventory.
Run deployment commands from the Debian operations laptop at `.73`, or through
its allowlisted API. The development laptop is a separate client. Host checks
and pinned cluster identities prevent an unintended local deployment target.
## Flow
The [code map](code-map.md) traces these layers to the actual entrypoints.
`lib/jeannie/env.sh` is the shared inventory loader; `pipeline.sh` uses that
loader rather than maintaining a second copy of profile defaults.
1. `bootstrap/provisioning`
- prepares a Debian server as a PXE and preseed service for arm64 VMs
- serves Debian 13 arm64 netboot assets through TFTP and HTTP
- exposes a PXE rescue menu and HTTP rescue page for manual repair paths
- creates a golden image install path with Kubernetes, containerd,
qemu-guest-agent, cloud-init, and storage client packages ready
- is used by the kubeadm VM profiles; native K3s skips worker provisioning
and preserves Orange Pi host networking
2. `bootstrap/cluster`
- installs the selected runtime: kubeadm on the laptop or Pimox CP VM,
or K3s directly on the Orange Pi host
- joins Pimox workers for the kubeadm profiles; native K3s is single-node
- configures Calico-compatible pod CIDR
- configures containerd to pull from the in-cluster NodePort registry
- creates retained host directories under `/data/openebs/local`
Native K3s disables packaged Traefik, ServiceLB and metrics-server so the
platform can own ingress, MetalLB and metrics-server. Existing externally
managed metrics-server installations are discovered and reused.
3. `bootstrap/platform`
- installs a minimal Calico deployment through the Tigera operator
- installs NodeLocal DNSCache for node-local DNS query caching
- installs MetalLB for LAN `LoadBalancer` services
- installs Traefik as the single Kubernetes ingress entry point
- installs OpenEBS
- creates `openebs-hostpath-retain`
- installs Argo CD
- installs Kyverno with audit-first baseline Pod Security policies and
homelab image signature/SBOM admission controls
- registers the private GitOps repo without storing the SSH private key in
Terraform state
4. `bootstrap/apps`
- registers Argo CD Applications from the `applications` map
- passes the website image produced by the build step into Argo CD as a
Kustomize image override
- deploys the tuned website runtime: Apache listens on port 8080, PHP-FPM
listens on loopback inside the container, OPcache is enabled, and
pre-rendered HTML handles the read-heavy pages
- default apps are `container-registry`, `website-production`,
`demos-static`, the `heimdall` route bundle, `n8n`, and
`supply-chain-policy`
5. Debian host services
- keep Gitea, Heimdall, the ARR/media stack, Ollama, and OmniRoute outside
Kubernetes so a cluster rebuild does not remove the tools needed to repair
or redeploy it
- run `deploy-ai-stack` to create the OmniRoute gateway and validated model
routes, then `deploy-ai-tools` to wire goose, Holmes, and Hermes to that
gateway
- use `doctor-k8s` for read-only Kubernetes evidence collection and
Holmes-assisted triage before any deterministic heal/runbook action
6. `bootstrap/edge`
- connects to the OCI jump box
- uploads nginx, HAProxy, Varnish, and Squid configs
- obtains and renews Let's Encrypt certificates for the configured hostname
- runs the edge cache/proxy chain with Docker Compose
- enables gzip, HTTP/2, TLS session reuse, client keepalive, upstream
keepalive, and cache headers for the public website path
## Profile isolation and switching
| Profile | API | Runtime placement |
| --- | --- | --- |
| `debian` | `https://192.168.100.73:6443` | Laptop CP, worker VMs 9010/9011 |
| `pimox` | `https://192.168.100.65:6443` | CP VM 9001, worker VMs 9010/9011 |
| `k3s` | `https://192.168.100.80:6443` | Native Orange Pi host, node `opi5plus` |
`cluster-runtime-guard.py` probes both physical hosts, API listeners, K3s
workload processes and Pimox VM power state. Deployment/start pipelines hold a
shared lock and refuse conflicts. This does not prevent manual starts outside
Jeannie. Switching modes requires stopping the previous runtime first.
`cluster-context.py` binds each profile to its API endpoint, CA fingerprint and
`kube-system` UID. Its state root is
`~/.local/share/homelab/clusters/<profile>/`, with `identity.json` and separate
`stacks/{cluster,platform,apps}/terraform.tfstate` files. Stopped-cluster startup
checks endpoint/CA offline, then checks live UID after startup. Deployment,
import, cleanup and healing retain live identity checks.
Retained local PVs remain tied to their host and data path. A different profile
does not automatically inherit the old cluster's volume contents. The laptop
K3s transition verifies and copies registry data before host K3s starts, archives
the old identity/state and datastore, and enrolls a new identity on the Orange
Pi. Other laptop PVC data stays on the laptop pending a separate restore.
On November 2, 2026, the native `opi5plus` node reported Ready. Platform/apps
completion must be checked independently; source support is not proof of a
successful live deployment.
## Pimox Migration Lessons
The Pimox migration moved Kubernetes workloads away from the old Debian-hosted
cluster shape, but it also clarified what should not move into Kubernetes.
Debian keeps the Git source of truth, build tooling, registry endpoint, AI
gateway, and recovery commands. Pimox VMs provide disposable Kubernetes capacity.
Operational lessons now encoded in Jeannie:
- Two guest CPUs per Pimox VM remain the desired topology. Runtime scheduling
checks use actual capacity and reservations; an existing one-core worker is
not silently treated as a two-core VM or blocked solely by a two-core floor.
The VM path supports big-core pinning through a Proxmox hook script.
- Treat VM disks as rebuildable. Durable application data belongs on retained
OpenEBS paths, host-level `/data`, or backups, not inside an untracked VM root
disk.
- Use the Debian LAN IP as the registry endpoint, even when the registry pod
runs on a Pimox worker. Jeannie configures containerd 2.x registry trust on
workers so image pulls survive pod movement.
- Rebuilt worker IPs can change SSH host keys. Jeannie refreshes known-host
state and waits for guest SSH/qemu-agent readiness instead of assuming a VM is
reachable immediately after `qm start`.
- Image filesystem pressure on small VM roots can evict registry or website
pods. App deploys include deterministic stale-pod and unused image cleanup
rather than relying on manual `kubectl delete` or node shell history.
## Workload Placement
`bootstrap/cluster` labels nodes with homelab placement metadata:
- `node-role.kubernetes.io/worker=worker` on every worker so `kubectl get nodes`
shows `worker` instead of `<none>` in the ROLES column
- `homelab.dev/node-role=control-plane`, `homelab.dev/storage=local`, and
`homelab.dev/workload-class=control-plane` on the Debian control plane
- `homelab.dev/node-role=edge-app`, `homelab.dev/storage=local`, and
`homelab.dev/workload-class=edge` on the Raspberry Pi worker
- `homelab.dev/node-role=app`, `homelab.dev/storage=ssd`, and
`homelab.dev/workload-class=platform` on automated Pimox worker clones when
those workers are enabled
Override `control_plane_node_labels`, `worker_node_labels`,
`LAB_RASPBERRY_NODE_LABELS_JSON`, or `LAB_PIMOX_WORKER_NODE_LABELS_JSON` when
the physical layout changes. The current website, demos, and registry manifests
are not moved automatically because the public NodePort path and retained
OpenEBS hostpath PVs are node-local. Move workloads only after their storage and
edge path are ready on the target node. Gitea is outside Kubernetes and is moved
through its Debian-host Compose deployment instead.
Platform controllers use `homelab.dev/workload-class=platform`. Multi-node
profiles retain worker placement, topology spread and preferred anti-affinity;
single-node profiles reconcile that platform label on their selected control
plane. Scheduling preflight checks the live labels instead of assuming a VM
worker exists in a native K3s cluster.
PVC-backed monitoring StatefulSets are intentionally treated separately because
their retained OpenEBS hostpath volumes are node-local. Run
`./{{ main_script }} move-prometheus-stack-workers` from the Debian host to label existing
worker nodes, destroy only the existing `prometheus-stack` Helm release, delete
its retained PVC/PV objects, and recreate the stack on the worker selector when
you intentionally accept losing that monitoring data. A planned monitoring data
migration should be handled as a separate maintenance task with backup,
delete/recreate or storage migration steps, and post-restore checks.
The older NodePort path is now reserved for special cases such as the local
registry. `bootstrap/cluster` still contains `homelab-tailscale-nodeport`
support, but app traffic should normally enter through Traefik's MetalLB
address instead of per-app NodePorts. Before applying the edge stack, Jeannie
configures a Tailscale subnet router so the OCI edge can route to the Traefik
LoadBalancer address. The default route advertiser is the Debian control-plane
host because it can reach both Tailscale and the MetalLB address; set
`LAB_EDGE_TAILSCALE_ROUTER=rpi` to use the Raspberry Pi instead.
The cluster stack still supports worker-based subnet-route advertisement when
that is useful:
```hcl
metallb = {
enabled = true
repository = "https://metallb.github.io/metallb"
version = "0.16.0"
namespace = "metallb-system"
address_pool = ["192.168.100.240-192.168.100.240"]
l2_advertisement_enabled = true
pool_name = "homelab-lan"
}
traefik = {
enabled = true
repository = "https://helm.traefik.io/traefik"
chart_version = "40.2.0"
namespace = "traefik"
load_balancer_ip = "192.168.100.240"
ingress_class = "traefik"
}
tailscale_subnet_routes = {
enabled = true
worker_key = "raspberrypi"
routes = ["192.168.100.0/24"]
}
```
DuckDNS resolves `*.lab2025.duckdns.org` to the OCI edge, so public requests for
the service hostnames land on the same edge host. For direct LAN testing, point
LAN DNS, `/etc/hosts`, or a Tailscale DNS override for app hostnames at
Traefik's address:
```text
192.168.100.240 lab2025.duckdns.org
192.168.100.240 demos.lab2025.duckdns.org
192.168.100.240 n8n.lab2025.duckdns.org
192.168.100.240 prowlarr.lab2025.duckdns.org
192.168.100.240 sonarr.lab2025.duckdns.org
192.168.100.240 radarr.lab2025.duckdns.org
192.168.100.240 qbittorrent.lab2025.duckdns.org
192.168.100.240 kapowarr.lab2025.duckdns.org
192.168.100.240 suwayomi.lab2025.duckdns.org
192.168.100.240 maintainerr.lab2025.duckdns.org
192.168.100.240 grafana.lab2025.duckdns.org
192.168.100.240 argocd.lab2025.duckdns.org
```
Heimdall is external to Kubernetes. For direct LAN testing, use
`http://192.168.100.73:8082/`; public access still uses
`https://heimdall.lab2025.duckdns.org/` through the OCI edge.
The edge stack uses Traefik as its backend by default and validates
`http://192.168.100.240:80/` before updating the edge containers. If Tailscale
subnet-route approval is not automatic in the tailnet policy, the edge deploy
will fail clearly instead of silently keeping a broken public path.
For `./{{ main_script }} nuke`, set `WORKER_SSH_TARGETS` to a space-separated list of
remote SSH targets when more worker nodes exist. Set it to an empty string for a
single-node rebuild.
## Policy Guardrails
`bootstrap/platform` installs Kyverno and the upstream baseline Pod Security
policies in `Audit` mode. This gives the lab policy reports for unsafe workload
settings without blocking existing pods during the first rollout. After reports
are clean, individual policies can be promoted to `Enforce` in
`bootstrap/platform/main.tf`.
`apps/supply-chain-policy` adds a separate Kyverno `ImageValidatingPolicy` for
the images built by this repo and pushed to the local registry. The policy
targets `192.168.100.73:30500/php-website:*` and
`192.168.100.73:30500/demos-static:*`, mutates admitted pods to image digests,
and audits whether the image has both:
- a valid Cosign signature from the homelab signing key
- a signed SPDX SBOM attestation
The private Cosign key, generated password, and downloaded Cosign binary live in
`${XDG_DATA_HOME:-$HOME/.local/share}/homelab/` by default so the signing
identity survives temporary checkout cleanup. Repo-local image state files still
live under `.lab/`, which is ignored by Git. `./{{ main_script }} apps` creates or reuses
the persistent Cosign key, publishes the public key into the Kyverno namespace as
`homelab-cosign-public-key`, builds images with BuildKit SBOM attestations, signs
the pushed images, attaches a signed SPDX SBOM predicate, and verifies both
artifacts before refreshing the workload Applications. The policy starts in
`Audit` mode so an existing live deployment can recover while the current images
are signed; after `./{{ main_script }} apps` verifies both images, change `validationActions` in
`apps/supply-chain-policy/local-registry-image-policy.yaml` from `Audit` to
`Deny` to make it admission-enforcing. Set `COSIGN_PASSWORD` if you want to
manage the key password externally; otherwise the Debian runner creates
`cosign/cosign.password` under the homelab state directory for non-interactive
runs. Set `COSIGN_KEY_PREFIX`, `COSIGN_PASSWORD_FILE`, or `COSIGN_BIN` to override
those paths.
## DNS Cache
`bootstrap/platform` installs NodeLocal DNSCache in `kube-system` with
`registry.k8s.io/dns/k8s-dns-node-cache`. The default listens on
`169.254.20.10` and the kube-dns service IP `10.96.0.10`, which keeps the
rollout compatible with the current kube-proxy iptables path without rewriting
kubelet DNS settings across the nodes. Override `nodelocal_dns` if the service
CIDR or upstream DNS servers change.
## MetalLB
MetalLB is present in `bootstrap/platform` but disabled by default. Enable it
only after reserving a LAN IP range outside DHCP and other address pools:
```bash
export TF_VAR_metallb='{
enabled = true
repository = "https://metallb.github.io/metallb"
version = "0.16.0"
namespace = "metallb-system"
address_pool = ["192.168.100.240-192.168.100.250"]
l2_advertisement_enabled = true
pool_name = "homelab-lan"
}'
```
Traefik uses MetalLB for a LAN `LoadBalancer` address. Kubernetes app services
such as the website, demos, and n8n should be `ClusterIP` services behind
Ingress objects. The local registry remains a `NodePort` because the cluster
nodes use it as a pull endpoint. Gitea and Heimdall are not Kubernetes services;
they run on the Debian Docker host.
## Edge Services
The OCI jump box runs the public edge path:
```text
nginx -> HAProxy -> Varnish/Squid -> Traefik MetalLB IP
```
Tailnet access policy is tracked in `infra/tailscale/tailnet-policy.hujson`.
Validate it before applying with:
```bash
./{{ main_script }} tailnet-policy-check
```
The `bootstrap/edge` stack renders configs from `bootstrap/edge/templates` and
deploys them to `/opt/homelab-edge` on the OCI host. Defaults are in
`bootstrap/edge/variables.tf`; override them through `TF_VAR_*` or a `.tfvars`
file when the public host, SSH key, server name, backend Tailscale IP, or
Traefik backend address changes.
The `/git/` route is intentionally different from the Kubernetes app routes: it
proxies to Gitea on the Debian host through Tailscale instead of Traefik. This
keeps public read-only source browsing available even when the cluster has been
destroyed.
For the main website, nginx terminates TLS, serves cached HTML and static
assets, compresses text responses with gzip, advertises HTTP/2, reuses TLS
sessions, and keeps upstream connections open to the Traefik backend. The
application side marks pre-rendered HTML as
`Cache-Control: public, max-age=300, s-maxage=3600`; the edge keeps CSS and JS
under the stronger immutable asset policy. In local measurements, cached
single-resource requests are dominated by the remote TCP/TLS path, while a
reused HTTP/2 asset batch completes in roughly 60 ms after the connection is
established.
Use the configured `server_name` in the browser, for example
`https://lab2025.duckdns.org`. A raw OCI IP address will still show a browser
certificate warning because the trusted certificate is issued for the hostname.
The edge stack uses HTTP-01 validation and requests one certificate covering
`server_name` plus `additional_server_names`. DuckDNS resolves sub-subdomains
under `lab2025.duckdns.org` to the same edge IP, so inbound TCP 80 and 443 must
be open before `./{{ main_script }} up` runs. Set `TF_VAR_letsencrypt_email` to receive
expiry notices, or leave it empty to register without an email. Set
`TF_VAR_enable_letsencrypt=false` to keep using the temporary local certificate.
Operational runbooks:
- [Edge failures](docs/runbooks/edge-failures.md)
- [Gitea failures](docs/runbooks/gitea-failures.md)
- [Cluster stop/start failures](docs/runbooks/cluster-stop-start-failures.md)