- Replace stale ~/Sites references with ~/Workloads across README.md, AGENTS.md, docs/architecture.md, docs/operations.md, and ROADMAP.md (ADR-0004) - Document homelab.workloadGrants, /etc/homelab/grants.json, scripts/workload_grants.py, and nixos/instance.example.nix (ADR-0005) - Link ADR-0004 and ADR-0005 in ROADMAP.md and record Milestone P4.5 completion in nixos-core
26 KiB
🛠️ Homelab Core — Operator Runbook & Procedures
This document contains operational procedures, system maintenance workflows, diagnostic commands, and recovery runbooks for administering Homelab Core.
1. System Lifecycle & NixOS Administration
The host system runs NixOS configured declaratively via the flake in ~/Core.
Rebuilding the System Configuration
After modifying any file in nixos/ (including configuration.nix, hardware-configuration.nix, or any nixos/modules/*.nix), apply changes to the running host:
# Using the built-in shell alias:
nix-switch
# Or using the explicit command:
sudo nixos-rebuild switch --flake path:/home/operator/Core#server --impure
Note
Flake Fetcher Scheme for Untracked Files: When importing the gitignored
nixos/instance.nix, Nix's default Git fetcher filters it out unless thepath:scheme is used (path:/home/operator/Core#serverorpath:~/Core#server). Thepath:scheme instructs Nix to evaluate directly from the filesystem without filtering by the Git index. If using/etc/nixos/homelab-instance.nix, a standard--flake ~/Core#server --impureworks directly since/etc/nixosis outside the repository.
Dry Build Validation & Rollback
# Validate build without activating (catches evaluation and syntax errors)
nix flake check
nix build .#nixosConfigurations.server.config.system.build.toplevel --no-link
# Roll back to the previous generation if needed
sudo nixos-rebuild switch --rollback
System Maintenance & Disk Space Management
# Check disk usage across partitions
df -h
# Delete older system generations (older than 7 days)
sudo nix-env --delete-generations +7d --profile /nix/var/nix/profiles/system
# Prune unreachable Nix store paths
sudo nix-collect-garbage -d
# Prune old Docker resources (only containers stopped for >7 days)
docker system prune -a --volumes --filter "until=168h"
2. Managing Core Systemd Services
Homelab Core runs several platform services managed by systemd:
homeserver-core.service (Core Compose Stack)
Manages the lifecycle of Traefik, Authelia, LLDAP, Stalwart, Homepage, Dozzle, Watchtower, and Diun.
# Check service status
systemctl status homeserver-core
# View startup and runtime logs
journalctl -u homeserver-core -f
# Restart the entire Core stack
sudo systemctl restart homeserver-core
# Stop or Start the Core stack
sudo systemctl stop homeserver-core
sudo systemctl start homeserver-core
homelab-gitops.service (Dynamic GitOps Webhook)
Listens on port 9000 for Gitea webhook requests and dispatches automated deployments.
# Check status and port binding
systemctl status homelab-gitops
# Stream webhook reception and deployment worker logs
journalctl -u homelab-gitops -f -n 50
# Restart the webhook dispatcher daemon
sudo systemctl restart homelab-gitops
dynu-monitor.service & dynu-monitor.timer (Smart DDNS)
Runs every 30 minutes to detect WAN IP address changes and trigger ddclient.
# Check next scheduled timer execution
systemctl list-timers dynu-monitor.timer
# Check last monitor run status and output
systemctl status dynu-monitor.service
# Manually trigger an immediate IP check
sudo systemctl start dynu-monitor.service
# View historical WAN IP transitions log
tail -n 20 /var/lib/dynu/ip_history.jsonl
3. Workload Lifecycle Operations (appctl)
Applications in ~/Workloads are managed with the appctl CLI.
Inspection & Status
# Check status of all applications and their Git tracking state
appctl list
# Fetch remote changes from Git remotes before rendering status
appctl list --fetch
# Check applications and Core infrastructure services together
appctl list --core
# Check SSL/TLS certificate validity across all domains
appctl list --ssl --core
# Inspect diagnostic details for a specific service
appctl info docs
appctl info jellyfin --ssl
Deployment & Lifecycle Actions
# Start a service stack
appctl up docs
# Gracefully stop a service stack
appctl down docs
# Restart a service stack (re-injects environment)
appctl restart docs
# Restart an individual Core component without restarting the whole host
appctl restart traefik
appctl restart authelia
# Sequential stack update for independent Workloads (clean tree check -> git pull -> compose pull -> up -> sync)
appctl update docs
# Stream live container logs
appctl logs docs
appctl logs -f stalwart
# View resolved Docker Compose configuration
appctl config docs
Workload vs. Core Update Policy
Homelab enforces a strict architectural boundary between independent application workloads (~/Workloads/<app>) and Homelab Core (~/Core):
1. Independent Workloads (~/Workloads/<app>)
- Automated Lifecycle: Workloads declare their lifecycle via
app.yamlmanifests and Compose definitions. - Update Command:
appctl update <workload>performs pre-flight verification, branch matching,git pull --ff-only, container image pull, stack reload, and dashboard synchronization. - GitOps Webhook Dispatch: Workloads registered in
~/Workloads/deployments.yaml(withconfig/deployments.yamlas the example template) can be triggered automatically via authenticated GitOps webhooks on Gitea push events. - Daemon Permissions:
homelab-appctl.serviceholds read-write permissions over~/Workloadsto manage files, compose configurations, and workload state.
2. Homelab Core Platform Stack (~/Core)
- Host Foundation & Invariant Boundary: Core defines NixOS host definitions, platform secrets, edge ingress, and security sandboxes.
- No Untrusted Webhooks: Core does not register for webhook dispatch in
~/Workloads/deployments.yaml. External push events can never trigger an automated deployment or rebuild of Core. - Read-Only Sandbox: Under NixOS systemd sandboxing (
ProtectHome = "read-only"),homelab-appctl.servicehas strictly read-only access to/home/operator/Core. The daemon cannot mutate the Core Git repository or rungit pullon Core. - Operator-Driven Update Workflow: Core updates must be executed explicitly by the operator:
- Review and pull repository changes:
cd ~/Core && git pull --ff-only - If NixOS modules or secrets changed, evaluate and activate the new system generation:
sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure - If Compose definitions changed, restart the platform stack:
docker compose up -d --remove-orphans # or via systemd: sudo systemctl restart homeserver-core - Individual platform services can be restarted via appctl using an authenticated admin token (
appctl restart traefik,appctl restart authelia).
- Review and pull repository changes:
4. User Identity & Access Management (LLDAP & Authelia)
User accounts and group memberships are managed dynamically in LLDAP rather than static configuration files.
Accessing the Directory
- Open
https://users.${HOMELAB_DOMAIN}(e.g.,https://users.example.com) in your browser. - Authenticate using your admin credentials (
admin/ password configured innixos/secrets.yaml). - From the LLDAP UI, you can:
- Create and delete user accounts.
- Reset user passwords.
- Manage user email addresses.
- Assign users to groups (e.g.
admin,users,media).
Authelia Session & Authentication
- URL:
https://auth.${HOMELAB_DOMAIN}(e.g.,https://auth.example.com) - Session Lifetime: 7 days maximum session, 3 days inactivity timeout.
- ForwardAuth Guard: Applications requiring authentication attach the
authelia-auth@dockermiddleware.
5. Troubleshooting Common Failure Modes
A. SSL/TLS Certificate Failures (Let's Encrypt / Dynu)
- Symptom: Browser reports
NET::ERR_CERT_AUTHORITY_INVALIDor self-signed Traefik default certificate. - Diagnosis:
- Verify certificate status:
appctl ssl <service>orappctl list --ssl. - Inspect Traefik logs:
appctl logs traefik | grep -i acme. - Verify Dynu API key is valid and not rate-limited.
- Check
config/letsencrypt/acme.jsonpermissions (must be0600).
- Verify certificate status:
- Recovery:
# Check acme.json permissions ls -la ~/Core/config/letsencrypt/acme.json chmod 600 ~/Core/config/letsencrypt/acme.json # Restart Traefik to trigger challenge retry appctl restart traefik
B. Dynamic DNS (WAN IP) Drift
- Symptom: External domain (
${HOMELAB_DOMAIN}) does not resolve to the current ISP WAN address. - Diagnosis:
# Check current public IP vs resolved DNS IP curl -s https://api.ipify.org dig +short example.com @1.1.1.1 # Check dynu-monitor logs systemctl status dynu-monitor journalctl -u dynu-monitor -n 30 - Recovery:
# Trigger manual IP update run sudo systemctl start dynu-monitor
C. Docker Socket Communication Errors
- Symptom: Traefik fails to discover routers, or Dozzle shows "Cannot connect to Docker daemon".
- Diagnosis:
# Verify socket-proxy is running and healthy docker ps -f name=socket-proxy # Verify socket-proxy logs appctl logs socket-proxy # Test internal socket-proxy connectivity from another container docker exec -it traefik wget -qO- http://socket-proxy:2375/version - Recovery:
appctl restart socket-proxy appctl restart traefik
D. GitOps Deployment Stuck or Failed
- Symptom: Pushed commit to Gitea did not deploy or container is in an inconsistent state.
- Diagnosis:
# Check webhook daemon logs journalctl -u homelab-gitops -f -n 50 # Check execution status file for the target service cat ~/.local/state/homelab/gitops/<service>.status.json # Check if a lock file is held ls -la ~/.local/state/homelab/gitops/ - Recovery:
# Manually run deployment via appctl appctl update <service>
6. Backup & Disaster Recovery
Critical Persistent State Locations
To back up the homelab, create secure snapshots of the following state directories:
| Component | Host Path | Description |
|---|---|---|
| Secrets Key | /etc/ssh/ssh_host_ed25519_key |
Host SSH key used by sops-nix to decrypt secrets |
| Encrypted Secrets | ~/Core/nixos/secrets.yaml |
Encrypted secrets source |
| SSL Certificates | ~/Core/config/letsencrypt/acme.json |
Active Let's Encrypt certificates |
| User Directory | ~/Core/config/lldap/data/ |
LLDAP SQLite database (users.db) |
| Auth Database | ~/Core/config/authelia/db.sqlite3 |
Authelia session database |
| Mail Storage | ~/Core/config/stalwart/ |
Stalwart database, mailboxes, and DKIM keys |
| Workload State | ~/var/lib/homelab/<app>/ |
Per-workload persistent runtime state (e.g., snappymail) |
| Dashboard State | ~/Core/config/homepage/ |
Homepage configuration and custom icons |
Host Recovery Requirements
To bring up a replacement host from version control:
- Boot the target system with a NixOS installation medium and configure partitions according to
nixos/hardware-configuration.nix. - Restore the host SSH private key to
/etc/ssh/ssh_host_ed25519_key(mode0600) before runningnixos-install, assops-nixrequires this key during system evaluation and activation. - Install NixOS targeting the server flake:
nixos-install --flake /mnt/home/<operator>/Core#server reboot - Restore persistent data directories (
config/and~/var/lib/homelab/backups) and start the Core stack:sudo systemctl start homeserver-core
7. Operator Account Migration Runbook (Decision D2: Staged Coexistence Cutover)
Caution
MAINTENANCE WINDOW REQUIRED — EXECUTION ON LIVE HOST CURRENTLY BLOCKED
Live execution of this runbook against production hosts is strictly blocked until an authorized platform maintenance window is scheduled. This runbook is codified for procedural readiness and dry-run verification only.
This runbook defines the 4-stage staged coexistence cutover procedure to migrate host operation from a legacy personal operator account (<legacy-operator>) to the platform standard operator user (uid = 1000, extraGroups = [ "wheel" "docker" "homelab-operators" "networkmanager" ]), fulfilling Decision D2 and eliminating personal identity coupling.
Stage 1: Pre-Flight Checks & Session Preservation
Important
Maintain Active Legacy Shell Session:
Do not terminate your active SSH or terminal session as<legacy-operator>. Keep at least one authenticated shell open throughout the entire cutover process to prevent lockout in case of SSH key, user profile, or PAM misconfiguration.
-
Verify or provision
operatoraccount: Check if theoperatoruser exists in the running environment:id operatorIf
operatordoes not exist yet (ashomelab.operatorUserhas not been switched in the active NixOS generation), provision the initial coexistence user before proceeding:sudo useradd -m -s /run/current-system/sw/bin/bash -G wheel,docker,homelab-operators operator -
Verify SSH key provisioning & permissions: Ensure the operator's authorized keys are installed with strict permissions (copying from
<legacy-operator>if needed):sudo mkdir -p /home/operator/.ssh if [ ! -f /home/operator/.ssh/authorized_keys ] && [ -f /home/<legacy-operator>/.ssh/authorized_keys ]; then sudo cp /home/<legacy-operator>/.ssh/authorized_keys /home/operator/.ssh/authorized_keys fi sudo chmod 700 /home/operator/.ssh sudo chmod 600 /home/operator/.ssh/authorized_keys sudo chown -R operator:users /home/operator/.ssh -
Verify administrative (
sudo) access: Test thatoperatorcan authenticate and execute privileged commands without failure:sudo -u operator sudo -n true || echo "Passwordless or password sudo required for operator" -
Prepare persistent directories: Ensure
/home/operator/Sites,/home/operator/Core,/home/operator/var/lib/homelab, and state parent paths are ready:sudo mkdir -p /home/operator/{Core,Sites,.config/homelab,var/lib/homelab,.local/state/homelab} sudo chown -R operator:homelab-operators /home/operator/{Core,Sites,.config,var,.local}
Stage 2: State and Repository Synchronization
Synchronize repository checkouts, workload persistent data, and runtime state from the legacy user account to /home/operator/ using non-destructive archive flags (-aHAX preserves hard links, attributes, and extended ACLs):
-
Initial background synchronization: Seed the file trees for Core, Sites, workload databases, and configurations while services continue running:
sudo rsync -aHAX --info=progress2 \ --exclude=".venv" \ --exclude=".pytest_cache" \ /home/<legacy-operator>/Core/ /home/operator/Core/ sudo rsync -aHAX --info=progress2 \ /home/<legacy-operator>/Sites/ /home/operator/Sites/ if [ -d "/home/<legacy-operator>/var/lib/homelab" ]; then sudo rsync -aHAX --info=progress2 \ /home/<legacy-operator>/var/lib/homelab/ /home/operator/var/lib/homelab/ fi if [ -d "/home/<legacy-operator>/.local/state/homelab" ]; then sudo rsync -aHAX --info=progress2 \ /home/<legacy-operator>/.local/state/homelab/ /home/operator/.local/state/homelab/ fi if [ -d "/home/<legacy-operator>/.config/homelab" ]; then sudo rsync -aHAX --info=progress2 \ /home/<legacy-operator>/.config/homelab/ /home/operator/.config/homelab/ fi -
Quiesce active database writers: Stop running workload containers and the Core platform stack to guarantee point-in-time consistency across SQLite databases (e.g. LLDAP
users.db, Autheliadb.sqlite3, Stalwart storage, and workload app volumes in~/var/lib/homelab/) before the final sync:# Stop running workload containers appctl down --all 2>/dev/null || docker stop $(docker ps -q) 2>/dev/null || true # Stop platform core services sudo systemctl stop homeserver-core sudo systemctl stop homelab-appctl sudo systemctl stop homelab-gitops -
Final delta synchronization (
--delete): Perform a rapid final delta synchronization with--deleteto capture the quiesced database state and prune removed files:sudo rsync -aHAX --delete --info=progress2 \ --exclude=".venv" \ --exclude=".pytest_cache" \ /home/<legacy-operator>/Core/ /home/operator/Core/ sudo rsync -aHAX --delete --info=progress2 \ /home/<legacy-operator>/Sites/ /home/operator/Sites/ if [ -d "/home/<legacy-operator>/var/lib/homelab" ]; then sudo rsync -aHAX --delete --info=progress2 \ /home/<legacy-operator>/var/lib/homelab/ /home/operator/var/lib/homelab/ fi if [ -d "/home/<legacy-operator>/.local/state/homelab" ]; then sudo rsync -aHAX --delete --info=progress2 \ /home/<legacy-operator>/.local/state/homelab/ /home/operator/.local/state/homelab/ fi -
Fix ownership and permissions: Set primary ownership to
operatorand group tohomelab-operatorsacross all migrated trees:sudo chown -R operator:homelab-operators \ /home/operator/Core \ /home/operator/Sites \ /home/operator/.config \ /home/operator/.local \ /home/operator/var sudo chmod -R u+rwX,g+rX /home/operator/Core /home/operator/Sites /home/operator/var # ACME certificate security invariant: Traefik strictly requires 0600 on acme.json; # recursive group read permissions will cause Traefik to refuse to start. if [ -f /home/operator/Core/config/letsencrypt/acme.json ]; then sudo chmod 600 /home/operator/Core/config/letsencrypt/acme.json fi
Stage 3: Service Rebuild & Environment Cutover
Activate the declarative configuration under the operator profile:
-
Configure instance domain injection (Decision D1): Ensure
nixos/instance.nix(or/etc/nixos/homelab-instance.nix) is in place with the host's production domain:cat << 'EOF' | sudo -u operator tee /home/operator/Core/nixos/instance.nix > /dev/null { homelab.domain = "example.com"; } EOF chmod 600 /home/operator/Core/nixos/instance.nix -
Bootstrap appctl control plane tokens (CR-SO-08): The
homelab-appctl.servicecontrol plane daemon enforces 3-role RBAC (homelab-admin,homelab-operator,homelab-viewer) authenticated via SHA-256 Bearer tokens stored in/run/secrets/appctl/tokens.json.Generate the operator administrator token and local CLI credentials:
sudo -u operator python3 /home/operator/Core/scripts/bootstrap_token.pyThis command:
- Creates
~/.config/homelab/token(mode0600) owned byoperator:homelab-operatorscontaining the raw Bearer token used automatically by theappctlCLI. - Outputs the JSON token descriptor containing the SHA-256 digest:
{ "token_id": "operator-admin", "identity": "operator", "role": "homelab-admin", "sha256": "<64-character-sha256-digest>" }
Important
Unprovisioned Token Behavior & RBAC Fallback: If tokens are not provisioned in
/run/secrets/appctl/tokens.json, local UDS connections (/run/homelab/appctl.sock) fall back to LinuxSO_PEERCREDsocket credentials, granting callers inhomelab-operatorsthe read-onlyhomelab-viewerrole. Underhomelab-viewer, safe queries succeed (appctl list,appctl status,appctl health). However, all mutating and privileged operations (appctl up,appctl down,appctl restart,appctl update,appctl deploy,appctl config,appctl info) strictly require a valid Bearer token withhomelab-operatororhomelab-adminrole. If tokens are not enrolled in SOPS, attempting mutating actions fails with HTTP 403ERR_PERMISSION_DENIED.Enroll the token descriptor into SOPS secrets:
sops /home/operator/Core/nixos/secrets.yamlUnder
appctl.tokens_json, insert the descriptor into the JSON array:appctl: tokens_json: | [ { "token_id": "operator-admin", "identity": "operator", "role": "homelab-admin", "sha256": "<paste-sha256-digest-here>" } ](Optional: If GitOps webhook dispatch is enabled, generate and enroll a
gitops-webhooktoken withhomelab-operatorrole usingpython3 scripts/bootstrap_token.py --identity gitops --role homelab-operator --token-id gitops-webhook --print-json). - Creates
-
Rebuild NixOS host configuration: Execute the rebuild from the new canonical Core path using
--impureand thepath:scheme to import the untracked instance profile:cd /home/operator/Core sudo nixos-rebuild switch --flake path:/home/operator/Core#server --impureNote
The
path:scheme instructs Nix to evaluate directly from the filesystem without filtering by the Git index, ensuring untracked/gitignorednixos/instance.nixis evaluated. (If using/etc/nixos/homelab-instance.nix, bare--flake .#server --impureworks directly). Rebuilding also decrypts and projects/run/secrets/appctl/tokens.jsonviasops-nix. -
Restart platform services: Restart the Core Compose stack and control plane services to consume updated paths and secrets:
sudo systemctl restart homeserver-core sudo systemctl restart homelab-appctl sudo systemctl restart homelab-gitops
Stage 4: Post-Flight Verification
Validate system health and operational readiness under the operator identity:
-
Verify Git safe directory: Ensure Git does not complain about dubious ownership when invoked by
operatororhomelab-appctl:sudo -u operator git -C /home/operator/Core status sudo -u operator git -C /home/operator/Sites/<any-workload> status -
Verify SOPS secrets and tokens projection: Ensure
/run/secrets/appctl/tokens.jsonis readable byhomelab-appctl(mode0400, owned byhomelab-appctl:homelab-operators) and contains valid descriptors:sudo ls -l /run/secrets/appctl/tokens.json -
Verify appctl control plane status & RBAC authentication: Execute CLI inspection using both UDS peercred authentication (read-only viewer fallback) and authenticated admin token operations:
# 1. Peercred UDS inspection (demonstrates viewer fallback for read-only actions) sudo -u operator appctl list --core sudo -u operator appctl status sudo -u operator appctl health # 2. Authenticated operator admin verification (requires homelab-admin Bearer token) sudo -u operator appctl info docs sudo -u operator appctl config docsConfirm that
infoandconfigreturn resolved configuration withoutERR_PERMISSION_DENIED, verifying that~/.config/homelab/tokenmatches the provisioned SHA-256 digest in/run/secrets/appctl/tokens.json. -
Verify container reachability & proxy routing: Check that external endpoints and internal reverse proxies resolve:
docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" curl -s -k https://127.0.0.1 -H "Host: dashboard.example.com" | head -n 5
Rollback Procedure
If unexpected service degradation occurs during the cutover:
-
Revert NixOS system generation:
sudo nixos-rebuild switch --rollback -
Restart legacy Core services:
sudo systemctl restart homeserver-core sudo systemctl restart homelab-appctl sudo systemctl restart homelab-gitops -
Log rollback reason: Record the diagnostic failure logs in
journalctl -xeand investigate before attempting another cutover window.
8. Read-Only Agent Inspection (agents SSH Identity)
For automated troubleshooting and agentic workflows, use the dedicated agents SSH user instead of the operator account.
Workstation Setup
- Generate a dedicated Ed25519 keypair on the workstation (if not already provisioned during setup):
ssh-keygen -t ed25519 -f ~/.ssh/canopy_agents -C "canopy-agents" - Register the
.pubkey inusers.users.agents.openssh.authorizedKeys.keys(nixos/configuration.nix) and rebuild NixOS. - Add a host entry to
~/.ssh/config(using your server hostname orserver.example.test):Host server-agents HostName <server-host> User agents IdentityFile ~/.ssh/canopy_agents IdentitiesOnly yes
Safe Read-Only Usage Examples
Commands are passed non-interactively over SSH and validated by the ForceCommand wrapper:
# Container status and logs (via read-only socket-proxy)
ssh server-agents "docker ps"
ssh server-agents "docker logs --tail 50 <container>"
ssh server-agents "docker inspect <container>"
# Platform & workload status
ssh server-agents "appctl list --core"
ssh server-agents "appctl status"
ssh server-agents "appctl info <app>"
# Systemd service logs
ssh server-agents "journalctl -u homelab-appctl -n 5"
Security Boundaries & Allowlist
The agents account is constrained at both the OS and OpenSSH layers (nixos/configuration.nix and nixos/scripts/agents-force-command.sh):
- Allowlisted commands only (
Match User agentsForceCommand):docker:ps,logs,inspectonly (routed toDOCKER_HOST=tcp://127.0.0.1:2375;-H,--host,--context,-c, and--configoverrides are rejected).appctl:list,status,info,logs,ssl,health,resolveonly.journalctl: read-only queries only (mutating flags such as--flush,--rotate,--vacuum-*,--relinquish-var,--sync,--setup-keys, and--update-catalogare rejected).- Empty commands, control characters, and shell metacharacters (
;,&,|,`,$,(,),<,>,\,',") are rejected.
- No privilege escalation or interactive shell:
agentsis not inwheelordocker, has nosudoaccess, and OpenSSH enforcesPermitTTY no,PasswordAuthentication no,AllowTcpForwarding no,X11Forwarding no, andAllowAgentForwarding no. - No host state write access:
agentshas no write permissions to~/Core,~/Workloads, or~/var/lib/homelab/*.