my-homelab-configs/lib/jeannie/commands.sh

5141 lines
214 KiB
Bash

# shellcheck shell=bash
plan_homelab() {
local target="${1:-all}"
local stack
local -a stacks=()
require_debian_server "plan"
if [[ "${target}" == "all" ]]; then
if [[ -z "${LAB_CLUSTER_VAR_FILE:-}" && "${LAB_CLUSTER_RUNTIME:-kubeadm}" != "k3s" ]]; then
prepare_cluster_worker_var_file false
fi
stacks=(
"bootstrap/provisioning"
"bootstrap/cluster"
"bootstrap/platform"
"bootstrap/apps"
"bootstrap/edge"
)
else
stack="$(tofu_stack_from_plan_target "${target}")"
if [[ "${stack}" == "bootstrap/cluster" && -z "${LAB_CLUSTER_VAR_FILE:-}" && "${LAB_CLUSTER_RUNTIME:-kubeadm}" != "k3s" ]]; then
prepare_cluster_worker_var_file false
fi
stacks=("${stack}")
fi
for stack in "${stacks[@]}"; do
echo
echo "Planning ${stack}..."
run_tofu_plan_stack "${stack}"
done
}
host_bootstrap_manage() {
local host_target="${1:-}"
local action="${2:-plan}"
local rpi_host rpi_user rpi_key rpi_os_image rpi_os_url rpi_install_device
if [[ "${host_target}" != "rpi4" ]]; then
echo "Usage: ./jeannie host-bootstrap rpi4 [status|plan|nfs-stage|install-image|apply --yes]" >&2
return 2
fi
if [[ "${action}" == "--help" || "${action}" == "help" ]]; then
echo "Usage: ./jeannie host-bootstrap rpi4 [status|plan|nfs-stage|install-image|apply --yes]"
return 0
fi
rpi_host="${LAB_RPI_HOST:-${LAB_RASPBERRY_HOST:-192.168.100.89}}"
rpi_user="${LAB_RPI_USER:-${LAB_RASPBERRY_USER:-jv}}"
rpi_key="${LAB_RPI_SSH_KEY_PATH:-${LAB_RASPBERRY_SSH_KEY_PATH:-${HOME}/.ssh/id_ed25519}}"
rpi_os_image="${LAB_RPI4_OS_IMAGE_NAME:-Raspberry Pi OS Lite (64-bit)}"
rpi_os_url="${LAB_RPI4_OS_IMAGE_URL:-https://downloads.raspberrypi.com/raspios_lite_arm64_latest}"
rpi_install_device="${LAB_RPI4_INSTALL_DEVICE:-/dev/mmcblk0}"
case "${action}" in
nfs-stage)
"${REPO_ROOT}/scripts/rpi4-nfs-stage" "${3:-plan}" "${4:-}"
;;
install-image)
"${REPO_ROOT}/scripts/rpi4-image-install" "${3:-plan}" "${4:-}"
;;
status)
echo "== RPi4 host bootstrap status =="
echo "target=${rpi_user}@${rpi_host} key=${rpi_key}"
if ssh -i "${rpi_key}" -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new \
"${rpi_user}@${rpi_host}" 'set -eu; . /etc/os-release; printf "hostname=%s\\n" "$(hostname)"; printf "os=%s %s\\n" "${ID}" "${VERSION_ID}"; printf "arch=%s\\n" "$(uname -m)"; printf "kernel=%s\\n" "$(uname -r)"; command -v docker >/dev/null 2>&1 && echo docker=installed || echo docker=missing; test -d /boot && echo boot=present || echo boot=missing'; then
echo "SSH and host inspection succeeded."
else
echo "RPi4 is not reachable over SSH; OS installation cannot be completed by Jeannie yet." >&2
return 1
fi
;;
plan)
cat <<EOF
RPi4 host bootstrap plan
========================
target: ${rpi_user}@${rpi_host}
image: ${rpi_os_image}
image_url: ${rpi_os_url}
headless: true (no desktop packages)
install_device: ${rpi_install_device}
1. Provision the Raspberry Pi OS image through the configured network-boot or imaging provider.
2. Wait for SSH using ${rpi_key}.
3. Run the idempotent RPi host bootstrap and deploy Pi-hole, Unbound, and Uptime Kuma.
4. Continue the independent edge, cluster, platform, and application stages.
The selected image is the official Raspberry Pi OS Lite 64-bit channel for Raspberry Pi 4.
The existing PXE stack provisions Pimox ARM64 VMs; it does not reimage a physical RPi4.
Set LAB_RPI4_OS_PROVISIONER_COMMAND to a reviewed, site-specific imaging/netboot command before using apply.
No disk or OS changes are made by this plan.
EOF
;;
apply)
if [[ "${3:-}" != "--yes" ]]; then
echo "Refusing RPi4 OS/bootstrap changes without --yes." >&2
return 2
fi
if [[ "${LAB_RPI4_INSTALL_DEVICE:-/dev/mmcblk0}" != "/dev/mmcblk0" ]]; then
echo "RPi4 installs are fixed to /dev/mmcblk0; refusing a different target." >&2
return 2
fi
if [[ -n "${LAB_RPI4_OS_PROVISIONER_COMMAND:-}" ]]; then
if ssh -i "${rpi_key}" -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new \
"${rpi_user}@${rpi_host}" "test \"\$(findmnt -no SOURCE /)\" != \"${LAB_RPI4_INSTALL_DEVICE}\""; then
:
else
echo "Refusing to image ${LAB_RPI4_INSTALL_DEVICE}: it is still the RPi4 root filesystem. Boot the Pi from the Debian NFS staging root first." >&2
return 2
fi
echo "Running the configured RPi4 OS provisioner..."
export LAB_RPI4_OS_IMAGE_NAME="${rpi_os_image}" LAB_RPI4_OS_IMAGE_URL="${rpi_os_url}"
bash -lc "${LAB_RPI4_OS_PROVISIONER_COMMAND}"
else
"${REPO_ROOT}/scripts/rpi4-nfs-stage" apply --yes
"${REPO_ROOT}/scripts/rpi4-image-install" apply --yes
fi
check_rpi_ssh
deploy_rpi_services
;;
*)
echo "Usage: ./jeannie host-bootstrap rpi4 [status|plan|apply --yes]" >&2
return 2
;;
esac
}
cluster_profile_report() {
cat <<EOF
Active cluster profile: ${LAB_CLUSTER_PROFILE:-debian}
Profile state root: ${HOMELAB_STATE_DIR}/clusters/${LAB_CLUSTER_PROFILE:-debian}
Identity binding: ${HOMELAB_STATE_DIR}/clusters/${LAB_CLUSTER_PROFILE:-debian}/identity.json
Control plane node: ${LAB_CLUSTER_CONTROL_PLANE_NODE_NAME:-debian}
Control plane LAN IP: ${LAB_CLUSTER_CONTROL_PLANE_LAN_IP:-${LAB_DEBIAN_LAN_IP:-}}
Control plane SSH user: ${LAB_CLUSTER_CONTROL_PLANE_USER:-${LAB_DEBIAN_USER:-}}
Control plane SSH key: ${LAB_CLUSTER_CONTROL_PLANE_SSH_KEY_PATH:-/home/jv/.ssh/id_ed25519}
Kubeconfig path: ${LAB_KUBECONFIG_PATH:-${KUBECONFIG_PATH:-}}
Kubeconfig owner: ${LAB_CLUSTER_KUBECONFIG_OWNER:-}
Registry endpoint: ${LAB_REGISTRY_ENDPOINT:-}
Provisioning host: ${LAB_CLUSTER_PROVISIONING_HOST:-${LAB_DEBIAN_LAN_IP:-}}
Provisioning user: ${LAB_CLUSTER_PROVISIONING_USER:-${LAB_DEBIAN_USER:-}}
GitOps repo URL: ${LAB_GITOPS_REPO_URL:-}
Calico operator node: ${LAB_CALICO_OPERATOR_NODE_NAME:-${LAB_CLUSTER_CONTROL_PLANE_NODE_NAME:-}}
Cluster runtime: ${LAB_CLUSTER_RUNTIME:-kubeadm}
External services host: ${LAB_SERVICES_HOST:-debian} (${LAB_SERVICES_HOST_LAN_IP:-${LAB_DEBIAN_LAN_IP:-}}, tailscale ${LAB_SERVICES_HOST_TAILSCALE_IP:-${LAB_DEBIAN_TAILSCALE_IP:-}})
Gitea backend host: ${LAB_GITEA_BACKEND_HOST:-${LAB_GITEA_TAILSCALE_IP:-${LAB_GITEA_HOST:-}}}
Dex backend host: ${LAB_DEX_BACKEND_HOST:-${LAB_DEBIAN_TAILSCALE_IP:-}}
Ollama URL: ${LAB_OLLAMA_URL:-http://${LAB_DEBIAN_LAN_IP:-}:11434}
Pimox host: ${LAB_CLUSTER_PIMOX_USER:-${LAB_PIMOX_USER:-}}@${LAB_CLUSTER_PIMOX_HOST:-${LAB_PIMOX_HOST:-}}
Pimox bridge: ${LAB_CLUSTER_PIMOX_BRIDGE:-${LAB_PIMOX_BRIDGE:-}}
Pimox storage: ${LAB_CLUSTER_PIMOX_STORAGE:-${LAB_PIMOX_WORKER_STORAGE:-}}
Pimox control-plane VMID: ${LAB_CLUSTER_PIMOX_CONTROL_PLANE_VMID:-}
Pimox worker count: ${LAB_CLUSTER_PIMOX_WORKER_COUNT:-${LAB_PIMOX_WORKER_COUNT:-}}
Pimox worker static IPs: ${LAB_CLUSTER_PIMOX_WORKER_STATIC_IPS:-${LAB_PIMOX_WORKER_STATIC_IPS:-}}
EOF
}
cluster_apply() {
require_debian_server "cluster"
record_change_journal "cluster" "$@"
jeannie_log_start "cluster"
jeannie_step_plan 1
run_step "Cluster OpenTofu apply" run_tofu_stack "bootstrap/cluster"
echo "Log: ${JEANNIE_LOG_FILE}"
}
rebuild_cluster() {
require_debian_server "rebuild-cluster"
export WORKER_SSH_TARGETS="${WORKER_SSH_TARGETS:-}"
export LAB_INCLUDE_RASPBERRY_WORKER="${LAB_INCLUDE_RASPBERRY_WORKER:-false}"
export LAB_PIMOX_TEMPLATE_REPLACE_EXISTING="${LAB_PIMOX_TEMPLATE_REPLACE_EXISTING:-true}"
export LAB_PIMOX_WORKER_COUNT="${LAB_PIMOX_WORKER_COUNT:-2}"
export LAB_PIMOX_WORKER_REPLACE_EXISTING="${LAB_PIMOX_WORKER_REPLACE_EXISTING:-true}"
export TF_VAR_force_worker_rejoin="${TF_VAR_force_worker_rejoin:-true}"
echo "Rebuilding the Kubernetes cluster without touching external Gitea..."
jeannie_log_start "rebuild-cluster"
jeannie_step_plan 9
run_step "Preflight" homelab_preflight
run_step "Nuke existing cluster state" nuke_for_rebuild
run_step "Pimox provisioning and workers" run_pimox_pipeline
run_step "Worker var file" ensure_cluster_worker_var_file
run_step "Cluster OpenTofu apply" run_tofu_stack "bootstrap/cluster"
run_step "Version report" doctor_versions_report
run_step "Platform OpenTofu apply" run_tofu_stack "bootstrap/platform"
run_step "Applications" apps
run_step "Edge OpenTofu apply" run_tofu_stack "bootstrap/edge"
echo "Cluster rebuild successfully completed."
echo "Log: ${JEANNIE_LOG_FILE}"
}
nuke_for_rebuild() {
LAB_NUKE_SKIP_CONFIRM=true LAB_NUKE_ALLOW_REMOTE_CLEANUP_FAILURES=true nuke
}
cluster_worker_targets() {
local worker_ssh_targets="${WORKER_SSH_TARGETS-}"
local var_file="${REPO_ROOT}/.lab/cluster-workers.auto.tfvars.json"
CLUSTER_WORKER_TARGETS=()
read -r -a CLUSTER_WORKER_TARGETS <<< "${worker_ssh_targets}"
if [[ -s "${var_file}" ]] && command -v python3 >/dev/null 2>&1; then
while IFS= read -r target; do
[[ -n "${target}" ]] || continue
if [[ ! " ${CLUSTER_WORKER_TARGETS[*]-} " =~ [[:space:]]${target}[[:space:]] ]]; then
CLUSTER_WORKER_TARGETS+=("${target}")
fi
done < <(python3 - "${var_file}" <<'PY'
import json
import sys
var_file = sys.argv[1]
with open(var_file, encoding="utf-8") as handle:
document = json.load(handle)
for key, node in sorted((document.get("worker_nodes") or {}).items()):
host = node.get("host")
user = node.get("user")
if host and user:
print(f"{user}@{host}")
PY
)
fi
}
stop_local_kubernetes_services() {
echo "--> Stopping local Kubernetes services on the Debian control plane..."
sudo systemctl stop kubelet 2>/dev/null || true
if command -v crictl >/dev/null 2>&1; then
sudo crictl stop --all 2>/dev/null || true
elif command -v ctr >/dev/null 2>&1; then
sudo ctr -n k8s.io tasks ls -q 2>/dev/null |
while IFS= read -r task; do
[[ -n "${task}" ]] || continue
sudo ctr -n k8s.io tasks kill -s SIGTERM "${task}" 2>/dev/null || true
done
sleep 3
sudo ctr -n k8s.io tasks ls -q 2>/dev/null |
while IFS= read -r task; do
[[ -n "${task}" ]] || continue
sudo ctr -n k8s.io tasks kill -s SIGKILL "${task}" 2>/dev/null || true
sudo ctr -n k8s.io tasks rm -f "${task}" 2>/dev/null || true
done
fi
if truthy "${LAB_CLUSTER_STOP_CONTAINERD:-false}"; then
sudo systemctl stop containerd 2>/dev/null || true
sudo systemctl reset-failed containerd 2>/dev/null || true
fi
sudo systemctl reset-failed kubelet 2>/dev/null || true
}
start_local_kubernetes_services() {
echo "--> Starting local Kubernetes services on the Debian control plane..."
sudo systemctl start containerd
sudo systemctl start docker 2>/dev/null || true
sudo systemctl start kubelet
}
stop_remote_kubernetes_services() {
local target="$1"
echo "--> Stopping Kubernetes services on remote worker ${target}..."
if ! ssh -o ConnectTimeout=5 "${target}" \
"sudo systemctl stop kubelet 2>/dev/null || true
if command -v crictl >/dev/null 2>&1; then
sudo crictl stop --all 2>/dev/null || true
elif command -v ctr >/dev/null 2>&1; then
sudo ctr -n k8s.io tasks ls -q 2>/dev/null | while IFS= read -r task; do
[ -n \"\$task\" ] || continue
sudo ctr -n k8s.io tasks kill -s SIGTERM \"\$task\" 2>/dev/null || true
done
sleep 3
sudo ctr -n k8s.io tasks ls -q 2>/dev/null | while IFS= read -r task; do
[ -n \"\$task\" ] || continue
sudo ctr -n k8s.io tasks kill -s SIGKILL \"\$task\" 2>/dev/null || true
sudo ctr -n k8s.io tasks rm -f \"\$task\" 2>/dev/null || true
done
fi
if [ '${LAB_CLUSTER_STOP_CONTAINERD:-false}' = 'true' ]; then sudo systemctl stop containerd 2>/dev/null || true; sudo systemctl reset-failed containerd 2>/dev/null || true; fi
sudo systemctl reset-failed kubelet 2>/dev/null || true"; then
echo "Warning: could not SSH to ${target}; continuing because Pimox VM shutdown follows." >&2
fi
}
start_remote_kubernetes_services() {
local target="$1"
echo "--> Starting Kubernetes services on ${target}..."
ssh -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new "${target}" \
"sudo systemctl start containerd && sudo systemctl start kubelet"
}
ensure_pimox_registry_recovery_path() {
local registry_endpoint="${LAB_REGISTRY_ENDPOINT:-${TF_VAR_registry_endpoint:-}}"
if [[ "${LAB_CLUSTER_PROFILE:-debian}" != "pimox" ]]; then
return 0
fi
if [[ -z "${registry_endpoint}" ]]; then
echo "Skipping Pimox registry recovery wiring because LAB_REGISTRY_ENDPOINT is unset."
return 0
fi
echo "--> Reasserting Pimox registry recovery path for ${registry_endpoint}..."
ensure_pimox_registry_endpoint_forwarding "${registry_endpoint}"
ensure_pimox_containerd_registry_refresh "${registry_endpoint}"
}
wait_for_ssh_target() {
local target="$1"
local timeout_seconds="${2:-180}"
local elapsed=0
echo "--> Waiting for SSH on ${target} for up to ${timeout_seconds}s..."
until ssh -o BatchMode=yes -o ConnectTimeout=5 -o StrictHostKeyChecking=accept-new "${target}" "true" >/dev/null 2>&1; do
if ((elapsed >= timeout_seconds)); then
echo "Timed out waiting for SSH on ${target} after ${timeout_seconds}s." >&2
return 1
fi
sleep 5
elapsed=$((elapsed + 5))
done
}
wait_for_cluster_ssh_targets() {
local timeout_seconds="${LAB_CLUSTER_VM_SSH_WAIT_SECONDS:-180}"
local target
local failures=0
if ! [[ "${timeout_seconds}" =~ ^[0-9]+$ ]]; then
echo "LAB_CLUSTER_VM_SSH_WAIT_SECONDS must be an integer, got '${timeout_seconds}'." >&2
return 1
fi
if [[ "${LAB_CLUSTER_PROFILE:-debian}" == "pimox" ]]; then
local cp_host="${LAB_CLUSTER_CONTROL_PLANE_LAN_IP:-}"
local cp_user="${LAB_CLUSTER_CONTROL_PLANE_USER:-${LAB_DEBIAN_USER:-jv}}"
if [[ -n "${cp_host}" ]]; then
wait_for_ssh_target "${cp_user}@${cp_host}" "${timeout_seconds}" || failures=$((failures + 1))
fi
fi
for target in "${CLUSTER_WORKER_TARGETS[@]}"; do
wait_for_ssh_target "${target}" "${timeout_seconds}" || failures=$((failures + 1))
done
((failures == 0))
}
pimox_worker_count_default() {
local spec_file="${REPO_ROOT}/.lab/pimox-workers.tsv"
local var_file="${REPO_ROOT}/.lab/cluster-workers.auto.tfvars.json"
local worker_key_prefix="${LAB_PIMOX_WORKER_KEY_PREFIX:-pimox}"
local worker_node_prefix="${LAB_PIMOX_WORKER_NODE_PREFIX:-pimox-worker}"
local max_count=0
local count
local state_count
if [[ -s "${spec_file}" ]]; then
count="$(awk -F'\t' -v key_prefix="${worker_key_prefix}" -v node_prefix="${worker_node_prefix}-" '
$1 ~ "^" key_prefix "[0-9]+$" {
worker_index = substr($1, length(key_prefix) + 1) + 0
if (worker_index > max) max = worker_index
}
$4 ~ "^" node_prefix "[0-9]+$" {
worker_index = substr($4, length(node_prefix) + 1) + 0
if (worker_index > max) max = worker_index
}
END { print max + 0 }
' "${spec_file}")"
if [[ "${count}" =~ ^[0-9]+$ && "${count}" -gt "${max_count}" ]]; then
max_count="${count}"
fi
fi
if [[ -s "${var_file}" ]] && command -v python3 >/dev/null 2>&1; then
count="$(python3 - "${var_file}" "${worker_key_prefix}" "${worker_node_prefix}" <<'PY'
import json
import re
import sys
var_file, worker_key_prefix, worker_node_prefix = sys.argv[1:4]
with open(var_file, encoding="utf-8") as handle:
document = json.load(handle)
nodes = document.get("worker_nodes") or {}
highest = 0
key_pattern = re.compile(rf"^{re.escape(worker_key_prefix)}(\d+)$")
node_pattern = re.compile(rf"^{re.escape(worker_node_prefix)}-(\d+)$")
for key, node in nodes.items():
for candidate in (key, str(node.get("node_name", ""))):
match = key_pattern.match(candidate) or node_pattern.match(candidate)
if match:
highest = max(highest, int(match.group(1)))
print(highest)
PY
)"
if [[ "${count}" =~ ^[0-9]+$ && "${count}" -gt "${max_count}" ]]; then
max_count="${count}"
fi
fi
state_count="$(tofu -chdir="${REPO_ROOT}/bootstrap/cluster" state show null_resource.worker_nodes_required 2>/dev/null |
awk -F'"' '/"worker_count"[[:space:]]*=/ { print $4; found = 1 } END { exit found ? 0 : 1 }' || true)"
if [[ "${state_count}" =~ ^[0-9]+$ && "${state_count}" -gt "${max_count}" ]]; then
max_count="${state_count}"
fi
count="${LAB_PIMOX_DEFAULT_WORKER_COUNT:-1}"
if [[ "${count}" =~ ^[0-9]+$ && "${count}" -gt "${max_count}" ]]; then
max_count="${count}"
fi
printf '%s\n' "${max_count}"
}
pimox_worker_count_effective() {
local configured="${LAB_PIMOX_WORKER_COUNT:-}"
local detected
detected="$(pimox_worker_count_default)"
if [[ "${configured}" =~ ^[0-9]+$ && "${configured}" -gt "${detected}" ]]; then
printf '%s\n' "${configured}"
return 0
fi
printf '%s\n' "${detected}"
}
stop_pimox_worker_vms() {
local pimox_host="${LAB_PIMOX_HOST:-${TF_VAR_pimox_host:-192.168.100.80}}"
local pimox_user="${LAB_PIMOX_USER:-${TF_VAR_pimox_user:-jv}}"
local pimox_key="${LAB_PIMOX_SSH_KEY_PATH:-${TF_VAR_pimox_ssh_key_path:-/home/jv/.ssh/id_ed25519}}"
local qm_bin="${LAB_PIMOX_QM_BIN:-${TF_VAR_pimox_qm_bin:-/usr/sbin/qm}}"
local worker_count
local worker_base_vmid="${LAB_PIMOX_WORKER_BASE_VMID:-9010}"
local worker_skip_indexes="${LAB_PIMOX_SKIP_WORKER_INDEXES:-}"
local shutdown_timeout="${LAB_CLUSTER_STOP_VM_TIMEOUT_SECONDS:-120}"
local force_stop="${LAB_CLUSTER_STOP_FORCE:-true}"
local index
local vmid
worker_count="$(pimox_worker_count_effective)"
if ! [[ "${worker_count}" =~ ^[0-9]+$ ]]; then
echo "LAB_PIMOX_WORKER_COUNT must be an integer, got '${worker_count}'." >&2
exit 1
fi
if ! [[ "${shutdown_timeout}" =~ ^[0-9]+$ ]]; then
echo "LAB_CLUSTER_STOP_VM_TIMEOUT_SECONDS must be an integer, got '${shutdown_timeout}'." >&2
exit 1
fi
if ((worker_count == 0)); then
return 0
fi
echo "--> Stopping Pimox worker VMs on ${pimox_host}..."
for ((index = 1; index <= worker_count; index++)); do
if worker_index_is_skipped "${index}" "${worker_skip_indexes}"; then
echo "Skipping Pimox worker index ${index} because LAB_PIMOX_SKIP_WORKER_INDEXES=${worker_skip_indexes}."
continue
fi
vmid=$((worker_base_vmid + index - 1))
pimox_ssh "${pimox_host}" "${pimox_user}" "${pimox_key}" "set -eu
if ! sudo '${qm_bin}' status '${vmid}' >/dev/null 2>&1; then
echo 'Pimox worker VM ${vmid} does not exist; skipping.'
exit 0
fi
if sudo '${qm_bin}' status '${vmid}' | grep -q 'status: stopped'; then
echo 'Pimox worker VM ${vmid} is already stopped.'
exit 0
fi
echo 'Gracefully shutting down Pimox worker VM ${vmid}...'
if sudo '${qm_bin}' shutdown '${vmid}' --timeout '${shutdown_timeout}'; then
exit 0
fi
if [ '${force_stop}' = 'true' ]; then
echo 'Graceful shutdown timed out; forcing stop for Pimox worker VM ${vmid}.'
sudo '${qm_bin}' stop '${vmid}'
else
echo 'Graceful shutdown timed out for Pimox worker VM ${vmid}. Set LAB_CLUSTER_STOP_FORCE=true to force stop.' >&2
exit 1
fi"
done
}
verify_pimox_worker_vms_stopped() {
local pimox_host="${LAB_PIMOX_HOST:-${TF_VAR_pimox_host:-192.168.100.80}}"
local pimox_user="${LAB_PIMOX_USER:-${TF_VAR_pimox_user:-jv}}"
local pimox_key="${LAB_PIMOX_SSH_KEY_PATH:-${TF_VAR_pimox_ssh_key_path:-/home/jv/.ssh/id_ed25519}}"
local qm_bin="${LAB_PIMOX_QM_BIN:-${TF_VAR_pimox_qm_bin:-/usr/sbin/qm}}"
local worker_count
local worker_base_vmid="${LAB_PIMOX_WORKER_BASE_VMID:-9010}"
local worker_skip_indexes="${LAB_PIMOX_SKIP_WORKER_INDEXES:-}"
local index
local vmid
local failures=0
worker_count="$(pimox_worker_count_effective)"
for ((index = 1; index <= worker_count; index++)); do
if worker_index_is_skipped "${index}" "${worker_skip_indexes}"; then
continue
fi
vmid=$((worker_base_vmid + index - 1))
if ! pimox_ssh "${pimox_host}" "${pimox_user}" "${pimox_key}" "sudo '${qm_bin}' status '${vmid}' 2>/dev/null | grep -q 'status: stopped'"; then
echo "Pimox worker VM ${vmid} is not stopped." >&2
failures=$((failures + 1))
fi
done
((failures == 0))
}
destroy_pimox_worker_vms() {
local pimox_host="${LAB_PIMOX_HOST:-${TF_VAR_pimox_host:-192.168.100.80}}"
local pimox_user="${LAB_PIMOX_USER:-${TF_VAR_pimox_user:-jv}}"
local pimox_key="${LAB_PIMOX_SSH_KEY_PATH:-${TF_VAR_pimox_ssh_key_path:-/home/jv/.ssh/id_ed25519}}"
local qm_bin="${LAB_PIMOX_QM_BIN:-${TF_VAR_pimox_qm_bin:-/usr/sbin/qm}}"
local worker_count
local worker_base_vmid="${LAB_PIMOX_WORKER_BASE_VMID:-9010}"
local worker_skip_indexes="${LAB_PIMOX_SKIP_WORKER_INDEXES:-}"
local index
local vmid
if ! truthy "${LAB_NUKE_DESTROY_PIMOX_WORKERS:-true}"; then
echo "--> Leaving Pimox worker VMs intact because LAB_NUKE_DESTROY_PIMOX_WORKERS=${LAB_NUKE_DESTROY_PIMOX_WORKERS}."
return 0
fi
worker_count="$(pimox_worker_count_effective)"
if ! [[ "${worker_count}" =~ ^[0-9]+$ ]]; then
echo "LAB_PIMOX_WORKER_COUNT must be an integer, got '${worker_count}'." >&2
exit 1
fi
if ((worker_count == 0)); then
return 0
fi
echo "--> Destroying Pimox worker VMs on ${pimox_host}..."
for ((index = 1; index <= worker_count; index++)); do
if worker_index_is_skipped "${index}" "${worker_skip_indexes}"; then
echo "Skipping Pimox worker index ${index} because LAB_PIMOX_SKIP_WORKER_INDEXES=${worker_skip_indexes}."
continue
fi
vmid=$((worker_base_vmid + index - 1))
pimox_ssh "${pimox_host}" "${pimox_user}" "${pimox_key}" "set -eu
if ! sudo '${qm_bin}' status '${vmid}' >/dev/null 2>&1; then
echo 'Pimox worker VM ${vmid} does not exist; skipping.'
exit 0
fi
if sudo '${qm_bin}' config '${vmid}' | grep -q '^template: 1$'; then
echo 'Pimox VM ${vmid} is a template; refusing to destroy it as a worker.' >&2
exit 1
fi
sudo '${qm_bin}' stop '${vmid}' >/dev/null 2>&1 || true
sudo '${qm_bin}' destroy '${vmid}' --purge 1 >/dev/null 2>&1 || sudo '${qm_bin}' destroy '${vmid}'"
done
}
start_pimox_worker_vms() {
cluster_runtime_require --vm-start || return 1
local pimox_host="${LAB_PIMOX_HOST:-${TF_VAR_pimox_host:-192.168.100.80}}"
local pimox_user="${LAB_PIMOX_USER:-${TF_VAR_pimox_user:-jv}}"
local pimox_key="${LAB_PIMOX_SSH_KEY_PATH:-${TF_VAR_pimox_ssh_key_path:-/home/jv/.ssh/id_ed25519}}"
local qm_bin="${LAB_PIMOX_QM_BIN:-${TF_VAR_pimox_qm_bin:-/usr/sbin/qm}}"
local worker_count
local worker_base_vmid="${LAB_PIMOX_WORKER_BASE_VMID:-9010}"
local worker_skip_indexes="${LAB_PIMOX_SKIP_WORKER_INDEXES:-}"
local index
local vmid
worker_count="$(pimox_worker_count_effective)"
if ! [[ "${worker_count}" =~ ^[0-9]+$ ]]; then
echo "LAB_PIMOX_WORKER_COUNT must be an integer, got '${worker_count}'." >&2
exit 1
fi
if ((worker_count == 0)); then
return 0
fi
echo "--> Starting Pimox worker VMs on ${pimox_host}..."
for ((index = 1; index <= worker_count; index++)); do
if worker_index_is_skipped "${index}" "${worker_skip_indexes}"; then
echo "Skipping Pimox worker index ${index} because LAB_PIMOX_SKIP_WORKER_INDEXES=${worker_skip_indexes}."
continue
fi
vmid=$((worker_base_vmid + index - 1))
pimox_ssh "${pimox_host}" "${pimox_user}" "${pimox_key}" "set -eu
if ! sudo '${qm_bin}' status '${vmid}' >/dev/null 2>&1; then
echo 'Pimox worker VM ${vmid} does not exist; skipping.'
exit 0
fi
if sudo '${qm_bin}' status '${vmid}' | grep -q 'status: running'; then
echo 'Pimox worker VM ${vmid} is already running.'
exit 0
fi
echo 'Starting Pimox worker VM ${vmid}...'
sudo '${qm_bin}' start '${vmid}'"
done
}
start_pimox_control_plane_vm() {
local pimox_host="${LAB_PIMOX_HOST:-${TF_VAR_pimox_host:-192.168.100.80}}"
local pimox_user="${LAB_PIMOX_USER:-${TF_VAR_pimox_user:-jv}}"
local pimox_key="${LAB_PIMOX_SSH_KEY_PATH:-${TF_VAR_pimox_ssh_key_path:-/home/jv/.ssh/id_ed25519}}"
local qm_bin="${LAB_PIMOX_QM_BIN:-${TF_VAR_pimox_qm_bin:-/usr/sbin/qm}}"
local vmid="${LAB_CLUSTER_PIMOX_CONTROL_PLANE_VMID:-${LAB_PIMOX_CONTROL_PLANE_VMID:-}}"
if [[ "${LAB_CLUSTER_PROFILE:-debian}" != "pimox" ]]; then
return 0
fi
cluster_runtime_require --vm-start || return 1
if [[ -z "${vmid}" ]]; then
echo "LAB_CLUSTER_PIMOX_CONTROL_PLANE_VMID is not configured; cannot start Pimox control-plane VM." >&2
return 1
fi
if ! [[ "${vmid}" =~ ^[0-9]+$ ]]; then
echo "LAB_CLUSTER_PIMOX_CONTROL_PLANE_VMID must be an integer, got '${vmid}'." >&2
return 1
fi
echo "--> Starting Pimox control-plane VM ${vmid} on ${pimox_host}..."
pimox_ssh "${pimox_host}" "${pimox_user}" "${pimox_key}" "set -eu
if ! sudo '${qm_bin}' status '${vmid}' >/dev/null 2>&1; then
echo 'Pimox control-plane VM ${vmid} does not exist.' >&2
exit 1
fi
if sudo '${qm_bin}' status '${vmid}' | grep -q 'status: running'; then
echo 'Pimox control-plane VM ${vmid} is already running.'
exit 0
fi
echo 'Starting Pimox control-plane VM ${vmid}...'
sudo '${qm_bin}' start '${vmid}'"
}
stop_pimox_control_plane_vm() {
local pimox_host="${LAB_PIMOX_HOST:-${TF_VAR_pimox_host:-192.168.100.80}}"
local pimox_user="${LAB_PIMOX_USER:-${TF_VAR_pimox_user:-jv}}"
local pimox_key="${LAB_PIMOX_SSH_KEY_PATH:-${TF_VAR_pimox_ssh_key_path:-/home/jv/.ssh/id_ed25519}}"
local qm_bin="${LAB_PIMOX_QM_BIN:-${TF_VAR_pimox_qm_bin:-/usr/sbin/qm}}"
local vmid="${LAB_CLUSTER_PIMOX_CONTROL_PLANE_VMID:-${LAB_PIMOX_CONTROL_PLANE_VMID:-}}"
local shutdown_timeout="${LAB_CLUSTER_STOP_VM_TIMEOUT_SECONDS:-120}"
local force_stop="${LAB_CLUSTER_STOP_FORCE:-true}"
if [[ "${LAB_CLUSTER_PROFILE:-debian}" != "pimox" ]]; then
return 0
fi
if [[ -z "${vmid}" ]]; then
echo "LAB_CLUSTER_PIMOX_CONTROL_PLANE_VMID is not configured; cannot stop Pimox control-plane VM." >&2
return 1
fi
if ! [[ "${vmid}" =~ ^[0-9]+$ ]]; then
echo "LAB_CLUSTER_PIMOX_CONTROL_PLANE_VMID must be an integer, got '${vmid}'." >&2
return 1
fi
if ! [[ "${shutdown_timeout}" =~ ^[0-9]+$ ]]; then
echo "LAB_CLUSTER_STOP_VM_TIMEOUT_SECONDS must be an integer, got '${shutdown_timeout}'." >&2
return 1
fi
echo "--> Stopping Pimox control-plane VM ${vmid} on ${pimox_host}..."
pimox_ssh "${pimox_host}" "${pimox_user}" "${pimox_key}" "set -eu
if ! sudo '${qm_bin}' status '${vmid}' >/dev/null 2>&1; then
echo 'Pimox control-plane VM ${vmid} does not exist.' >&2
exit 1
fi
if sudo '${qm_bin}' status '${vmid}' | grep -q 'status: stopped'; then
echo 'Pimox control-plane VM ${vmid} is already stopped.'
exit 0
fi
echo 'Gracefully shutting down Pimox control-plane VM ${vmid}...'
if sudo '${qm_bin}' shutdown '${vmid}' --timeout '${shutdown_timeout}'; then
exit 0
fi
if [ '${force_stop}' = 'true' ]; then
echo 'Graceful shutdown timed out; forcing stop for Pimox control-plane VM ${vmid}.'
sudo '${qm_bin}' stop '${vmid}'
else
echo 'Graceful shutdown timed out for Pimox control-plane VM ${vmid}. Set LAB_CLUSTER_STOP_FORCE=true to force stop.' >&2
exit 1
fi"
}
verify_pimox_control_plane_vm_stopped() {
local pimox_host="${LAB_PIMOX_HOST:-${TF_VAR_pimox_host:-192.168.100.80}}"
local pimox_user="${LAB_PIMOX_USER:-${TF_VAR_pimox_user:-jv}}"
local pimox_key="${LAB_PIMOX_SSH_KEY_PATH:-${TF_VAR_pimox_ssh_key_path:-/home/jv/.ssh/id_ed25519}}"
local qm_bin="${LAB_PIMOX_QM_BIN:-${TF_VAR_pimox_qm_bin:-/usr/sbin/qm}}"
local vmid="${LAB_CLUSTER_PIMOX_CONTROL_PLANE_VMID:-${LAB_PIMOX_CONTROL_PLANE_VMID:-}}"
if [[ "${LAB_CLUSTER_PROFILE:-debian}" != "pimox" ]]; then
return 0
fi
if [[ -z "${vmid}" ]]; then
echo "LAB_CLUSTER_PIMOX_CONTROL_PLANE_VMID is not configured; cannot verify Pimox control-plane VM." >&2
return 1
fi
if ! [[ "${vmid}" =~ ^[0-9]+$ ]]; then
echo "LAB_CLUSTER_PIMOX_CONTROL_PLANE_VMID must be an integer, got '${vmid}'." >&2
return 1
fi
if ! pimox_ssh "${pimox_host}" "${pimox_user}" "${pimox_key}" "sudo '${qm_bin}' status '${vmid}' 2>/dev/null | grep -q 'status: stopped'"; then
echo "Pimox control-plane VM ${vmid} is not stopped." >&2
return 1
fi
}
stop_cluster() {
local target
local failures=0
declare -a CLUSTER_WORKER_TARGETS=()
require_debian_server "stop-cluster"
cluster_context_require || return 1
if [[ "${LAB_CLUSTER_RUNTIME:-kubeadm}" == k3s ]]; then
echo "Stopping direct-host K3s on ${LAB_CLUSTER_CONTROL_PLANE_LAN_IP}; preserving Pimox, VM disks and cluster data."
ssh -i "${LAB_CLUSTER_CONTROL_PLANE_SSH_KEY_PATH}" -o BatchMode=yes -o ConnectTimeout=10 \
"${LAB_CLUSTER_CONTROL_PLANE_USER}@${LAB_CLUSTER_CONTROL_PLANE_LAN_IP}" \
'bash -s' <"${REPO_ROOT}/scripts/k3s-stop.sh" || return 1
return 0
fi
cluster_worker_targets
echo "Stopping Kubernetes cluster runtime without destroying state..."
if [[ "${LAB_CLUSTER_PROFILE:-debian}" == "pimox" ]]; then
echo "--> Pimox profile detected; stopping VMs through the Pimox host instead of SSHing into guest nodes."
stop_pimox_worker_vms
stop_pimox_control_plane_vm || failures=$((failures + 1))
if truthy "${LAB_CLUSTER_STOP_DEBIAN_K8S_IN_PIMOX_PROFILE:-false}"; then
stop_local_kubernetes_services
else
echo "--> Skipping local Debian Kubernetes service stop because active cluster profile is Pimox."
echo " Set LAB_CLUSTER_STOP_DEBIAN_K8S_IN_PIMOX_PROFILE=true to stop leftover local Debian kubelet/containerd tasks too."
fi
else
for target in "${CLUSTER_WORKER_TARGETS[@]}"; do
stop_remote_kubernetes_services "${target}"
done
stop_pimox_worker_vms
stop_local_kubernetes_services
fi
if kubernetes_api_reachable; then
echo "Kubernetes API is still reachable after stop; control-plane containers may still be running." >&2
failures=$((failures + 1))
fi
if ! verify_pimox_control_plane_vm_stopped; then
failures=$((failures + 1))
fi
if ! verify_pimox_worker_vms_stopped; then
failures=$((failures + 1))
fi
if ((failures > 0)); then
echo "Cluster stop finished with ${failures} verification failure(s)." >&2
return 1
fi
echo "Kubernetes runtime stopped. OpenTofu state, kubeadm files, PV data, and VM disks were left intact."
}
lab_window() {
local action="${1:-status}"
case "${action}" in
status)
printf 'profile=%s runtime=%s\n' "${LAB_CLUSTER_PROFILE:-unset}" "${LAB_CLUSTER_RUNTIME:-unset}"
status_systemd_units docker jeannie-server.service
cluster_runtime_require
;;
start)
require_debian_server "lab-window start"
echo "Starting the scheduled lab window for profile ${LAB_CLUSTER_PROFILE:-unset}..."
start_debian_services
start_rpi_services || return 1
start_cluster || return 1
;;
stop)
echo "Scheduled shutdown is disabled: the API execution worker must remain available for the next startup." >&2
return 1
;;
*)
echo "Usage: ./jeannie lab-window {start|stop|status}" >&2
return 2
;;
esac
}
shutdown_remote_compose_stack() {
local label="$1"
local target="$2"
local install_dir="$3"
local key_path="${4:-}"
local ssh_args=(-o BatchMode=yes -o ConnectTimeout=15 -o StrictHostKeyChecking=accept-new)
[[ -n "${key_path}" ]] && ssh_args+=(-i "${key_path}")
echo "--> Stopping ${label} services on ${target} (${install_dir})..."
ssh "${ssh_args[@]}" "${target}" "
set -eu
if [ -f '${install_dir}/docker-compose.yml' ] || [ -f '${install_dir}/compose.yml' ]; then
cd '${install_dir}'
if sudo docker compose version >/dev/null 2>&1; then
sudo docker compose stop || true
elif command -v docker-compose >/dev/null 2>&1; then
sudo docker-compose stop || true
else
echo 'Docker Compose is unavailable; leaving the stack unchanged.' >&2
exit 1
fi
else
echo '${install_dir}/docker-compose.yml not found; leaving the stack unchanged.' >&2
fi"
}
start_remote_compose_stack() {
local label="$1"
local target="$2"
local install_dir="$3"
local key_path="${4:-}"
local ssh_args=(-o BatchMode=yes -o ConnectTimeout=15 -o StrictHostKeyChecking=accept-new)
[[ -n "${key_path}" ]] && ssh_args+=(-i "${key_path}")
echo "--> Starting ${label} services on ${target} (${install_dir})..."
ssh "${ssh_args[@]}" "${target}" "
set -eu
if [ -f '${install_dir}/docker-compose.yml' ] || [ -f '${install_dir}/compose.yml' ]; then
cd '${install_dir}'
if sudo docker compose version >/dev/null 2>&1; then
sudo docker compose start || sudo docker compose up -d --remove-orphans
elif command -v docker-compose >/dev/null 2>&1; then
sudo docker-compose start || sudo docker-compose up -d --remove-orphans
else
echo 'Docker Compose is unavailable.' >&2
exit 1
fi
else
echo '${install_dir}/docker-compose.yml not found.' >&2
exit 1
fi"
}
tailscale_edge_host() {
[[ -n "${LAB_EDGE_TAILSCALE_IP:-}" ]] && { printf '%s\n' "${LAB_EDGE_TAILSCALE_IP}"; return 0; }
command -v tailscale >/dev/null 2>&1 || return 1
tailscale status 2>/dev/null | awk '$2 == "homelab-oci-edge" || $2 == "homelab-oci-edge.tail767cd.ts.net" { print $1; exit }'
}
start_bastion_compose_stack() {
local label="$1" bastion_id="$2" instance_id="$3" user="$4" public_key="$5" private_key="$6" install_dir="$7"
[[ -n "${bastion_id}" && -n "${instance_id}" ]] || {
echo "${label} Bastion target is not configured; cannot start through the private path." >&2
return 1
}
echo "--> Starting ${label} services through OCI Bastion (${instance_id})..."
"${REPO_ROOT}/scripts/oci-bastion-ssh" --command "cd '${install_dir}' && (sudo docker compose start || sudo docker compose up -d --remove-orphans)" \
"${bastion_id}" "${instance_id}" "${user}" "${public_key}" "${private_key}"
}
shutdown_rpi_services() {
local rpi_host="${LAB_RPI_HOST:-${LAB_RASPBERRY_HOST:-192.168.100.89}}"
local rpi_user="${LAB_RPI_USER:-${LAB_RASPBERRY_USER:-jv}}"
local rpi_key="${LAB_RPI_SSH_KEY_PATH:-${LAB_RASPBERRY_SSH_KEY_PATH:-${HOME}/.ssh/id_ed25519}}"
local install_dir="${LAB_RPI_SERVICES_INSTALL_DIR:-/opt/homelab-rpi-services}"
shutdown_remote_compose_stack "RPi4" "${rpi_user}@${rpi_host}" "${install_dir}" "${rpi_key}"
}
shutdown_oci_edge_services() {
local edge_host="${LAB_EDGE_HOST:-${LAB_OCI_EDGE_PUBLIC_IP:-}}"
local edge_tailnet_host
local edge_user="${LAB_EDGE_USER:-ubuntu}"
local edge_key="${LAB_EDGE_SSH_KEY_PATH:-${LAB_OCI_SSH_PRIVATE_KEY:-}}"
local install_dir="${LAB_EDGE_INSTALL_DIR:-/opt/homelab-edge}"
edge_tailnet_host="$(tailscale_edge_host || true)"
[[ -n "${edge_tailnet_host}" ]] && edge_host="${edge_tailnet_host}"
[[ -n "${edge_host}" ]] || {
echo "OCI edge host is not configured; set LAB_EDGE_HOST or LAB_OCI_EDGE_PUBLIC_IP." >&2
return 1
}
shutdown_remote_compose_stack "OCI edge" "${edge_user}@${edge_host}" "${install_dir}" "${edge_key}"
}
shutdown_oci_email_services() {
local email_host="${LAB_EMAIL_PUBLIC_IP:-${LAB_OCI_EMAIL_PUBLIC_IP:-}}"
local email_user="${LAB_EMAIL_SSH_USER:-ubuntu}"
local email_key="${LAB_EMAIL_SSH_PRIVATE_KEY:-${HOME}/.ssh/id_ed25519}"
if [[ -z "${email_host}" ]]; then
email_host="$(tofu -chdir="${REPO_ROOT}/bootstrap/oci" output -raw email_public_ip 2>/dev/null || true)"
fi
[[ -n "${email_host}" && "${email_host}" != "null" ]] || {
echo "OCI email host is not configured; skipping mail VM." >&2
return 0
}
echo "--> Stopping email services on ${email_user}@${email_host}..."
ssh -i "${email_key}" -o BatchMode=yes -o ConnectTimeout=15 -o StrictHostKeyChecking=accept-new \
"${email_user}@${email_host}" \
"sudo systemctl stop postfix dovecot fail2ban prometheus-node-exporter 2>/dev/null || true"
}
shutdown_debian_services() {
echo "--> Stopping Debian homelab services (jeannie-server is preserved)..."
sudo systemctl stop \
jeannie-eventd.service \
jeannie-temporal-worker.service \
homelab-edge-traefik-route.service \
homelab-pimox-registry-forward.service \
homelab-gitea-runner.service \
homelab-gitea-backup.service \
homelab-gitea-restore-drill.service \
homelab-profile-backup.service \
2>/dev/null || true
if command -v docker >/dev/null 2>&1; then
local containers
containers="$(sudo docker ps -q 2>/dev/null || true)"
if [[ -n "${containers}" ]]; then
echo "Stopping ${containers//$'\n'/ } Debian Docker container(s)..."
# Jeannie API is a host process/systemd service, not a container.
printf '%s\n' "${containers}" | xargs -r sudo docker stop >/dev/null
fi
fi
}
start_debian_services() {
echo "--> Starting Debian homelab services (jeannie-server is already preserved)..."
sudo systemctl start docker 2>/dev/null || true
sudo systemctl start \
jeannie-eventd.service \
jeannie-temporal-worker.service \
homelab-edge-traefik-route.service \
homelab-pimox-registry-forward.service \
homelab-gitea-runner.service \
homelab-gitea-backup.service \
homelab-gitea-restore-drill.service \
homelab-profile-backup.service \
2>/dev/null || true
local containers
containers="$(sudo docker ps -aq 2>/dev/null || true)"
if [[ -n "${containers}" ]]; then
echo "Starting Debian Docker container(s)..."
printf '%s\n' "${containers}" | xargs -r sudo docker start >/dev/null
fi
}
start_rpi_services() {
local rpi_host="${LAB_RPI_HOST:-${LAB_RASPBERRY_HOST:-192.168.100.89}}"
local rpi_user="${LAB_RPI_USER:-${LAB_RASPBERRY_USER:-jv}}"
local rpi_key="${LAB_RPI_SSH_KEY_PATH:-${LAB_RASPBERRY_SSH_KEY_PATH:-${HOME}/.ssh/id_ed25519}}"
local install_dir="${LAB_RPI_SERVICES_INSTALL_DIR:-/opt/homelab-rpi-services}"
start_remote_compose_stack "RPi4" "${rpi_user}@${rpi_host}" "${install_dir}" "${rpi_key}"
}
start_oci_edge_services() {
local edge_host="${LAB_EDGE_HOST:-${LAB_OCI_EDGE_PUBLIC_IP:-}}"
local edge_tailnet_host
local edge_user="${LAB_EDGE_USER:-ubuntu}"
local edge_key="${LAB_EDGE_SSH_KEY_PATH:-${LAB_OCI_SSH_PRIVATE_KEY:-${HOME}/.ssh/id_ed25519}}"
local install_dir="${LAB_EDGE_INSTALL_DIR:-/opt/homelab-edge}"
edge_tailnet_host="$(tailscale_edge_host || true)"
if [[ -n "${edge_tailnet_host}" ]]; then
export LAB_EDGE_TAILSCALE_IP="${edge_tailnet_host}"
echo "--> Starting OCI edge services over the homelab tailnet (${edge_tailnet_host})..."
start_remote_compose_stack "OCI edge" "${edge_user}@${edge_tailnet_host}" "${install_dir}" "${edge_key}"
else
[[ -n "${edge_host}" ]] || { echo "OCI edge host is not configured." >&2; return 1; }
start_remote_compose_stack "OCI edge" "${edge_user}@${edge_host}" "${install_dir}" "${edge_key}"
fi
}
start_oci_email_services() {
local email_host="${LAB_EMAIL_PUBLIC_IP:-${LAB_OCI_EMAIL_PUBLIC_IP:-}}"
local email_user="${LAB_EMAIL_SSH_USER:-ubuntu}"
local email_key="${LAB_EMAIL_SSH_PRIVATE_KEY:-${HOME}/.ssh/id_ed25519}"
if [[ -z "${email_host}" ]]; then
email_host="$(tofu -chdir="${REPO_ROOT}/bootstrap/oci" output -raw email_public_ip 2>/dev/null || true)"
fi
[[ -n "${email_host}" && "${email_host}" != "null" ]] || { echo "OCI email host is not configured; skipping mail VM."; return 0; }
if truthy "${LAB_OCI_BASTION_ENABLED:-true}" && [[ -n "${LAB_OCI_BASTION_ID:-}" && -n "${LAB_OCI_EMAIL_INSTANCE_ID:-}" ]]; then
echo "--> Starting OCI email services through OCI Bastion..."
"${REPO_ROOT}/scripts/oci-bastion-ssh" --command "sudo systemctl start postfix dovecot fail2ban prometheus-node-exporter 2>/dev/null || true" \
"${LAB_OCI_BASTION_ID}" "${LAB_OCI_EMAIL_INSTANCE_ID}" "${email_user}" "${email_key}.pub" "${email_key}"
else
echo "--> Starting OCI email services on ${email_user}@${email_host}..."
ssh -i "${email_key}" -o BatchMode=yes -o ConnectTimeout=15 -o StrictHostKeyChecking=accept-new \
"${email_user}@${email_host}" \
"sudo systemctl start postfix dovecot fail2ban prometheus-node-exporter 2>/dev/null || true"
fi
}
homelab_start() {
local action="${1:-plan}"
local failures=0
case "${action}" in
plan)
cat <<'EOF'
Homelab startup plan
====================
Start Debian services and containers, Kubernetes/Pimox, RPi4 services,
OCI edge services, and OCI email services. Existing disks and configuration
are preserved; already-running services are left unchanged.
Run ./jeannie start apply to execute this plan.
EOF
;;
apply)
require_debian_server "start"
oci_foundation_load_config
if truthy "${LAB_OCI_BASTION_ENABLED:-true}" && [[ -n "${LAB_OCI_TENANCY_ID:-}" ]]; then
local discovered_bastion discovered_edge discovered_email
discovered_bastion="$(oci_discover_active_bastion_id "${LAB_OCI_TENANCY_ID}" "${LAB_OCI_BASTION_NAME:-homelab-bastion}" || true)"
LAB_OCI_BASTION_ID="${discovered_bastion}"
discovered_edge="$(oci_discover_active_instance_id "${LAB_OCI_EDGE_DISPLAY_NAME:-homelab-edge}" "${LAB_OCI_TENANCY_ID}" || true)"
[[ -n "${discovered_edge}" ]] && LAB_OCI_EDGE_INSTANCE_ID="${discovered_edge}"
discovered_email="$(oci_discover_active_instance_id "${LAB_OCI_EMAIL_DISPLAY_NAME:-homelab-mail}" "${LAB_OCI_TENANCY_ID}" || true)"
[[ -n "${discovered_email}" ]] && LAB_OCI_EMAIL_INSTANCE_ID="${discovered_email}"
oci_foundation_save_config
fi
echo "Starting all managed homelab services..."
start_debian_services || failures=$((failures + 1))
start_cluster || failures=$((failures + 1))
start_rpi_services || failures=$((failures + 1))
start_oci_edge_services || failures=$((failures + 1))
start_oci_email_services || failures=$((failures + 1))
oci_foundation_save_config
if systemctl is-active --quiet jeannie-server.service 2>/dev/null; then
echo "PASS jeannie-server.service is active."
else
echo "FAIL jeannie-server.service is not active." >&2
failures=$((failures + 1))
fi
((failures == 0)) || { echo "Homelab startup finished with ${failures} failure(s)." >&2; return 1; }
echo "Homelab services started."
;;
--help|help) echo "Usage: ./jeannie start {plan|apply}" ;;
*) echo "Usage: ./jeannie start {plan|apply}" >&2; return 2 ;;
esac
}
homelab_shutdown() {
local action="${1:-plan}"
local failures=0
case "${action}" in
--help|help)
echo "Usage: ./jeannie shutdown {plan|apply --yes}"
return 0
;;
plan)
cat <<'EOF'
Homelab shutdown plan
=====================
The apply action stops managed services on Debian, RPi4, OCI edge, and OCI email,
then stops the Kubernetes/Pimox runtime. Hosts, disks, SSH, and jeannie-server
remain running so the API can receive the next command. Docker volumes and VM
disks are not deleted.
Targets:
- Debian Docker containers and managed homelab systemd units
- RPi4 Docker Compose services
- OCI edge Docker Compose services
- OCI Postfix, Dovecot, fail2ban, and node-exporter
- Kubernetes services and Pimox control-plane/worker VMs
Run ./jeannie shutdown apply --yes to execute this plan.
EOF
;;
apply)
if [[ "${2:-}" != "--yes" ]]; then
echo "Refusing homelab-wide shutdown without --yes." >&2
echo "Run ./jeannie shutdown plan first, then ./jeannie shutdown apply --yes." >&2
return 2
fi
require_debian_server "shutdown"
echo "Shutting down managed homelab services; jeannie-server will remain running."
shutdown_rpi_services || failures=$((failures + 1))
shutdown_oci_edge_services || failures=$((failures + 1))
shutdown_oci_email_services || failures=$((failures + 1))
stop_cluster || failures=$((failures + 1))
shutdown_debian_services || failures=$((failures + 1))
if systemctl is-active --quiet jeannie-server.service 2>/dev/null; then
echo "PASS jeannie-server.service remains active."
else
echo "FAIL jeannie-server.service is not active; the API is unavailable." >&2
failures=$((failures + 1))
fi
if ((failures > 0)); then
echo "Homelab shutdown finished with ${failures} failure(s)." >&2
return 1
fi
echo "Homelab services stopped. jeannie-server and host SSH remain available."
;;
*)
echo "Usage: ./jeannie shutdown {plan|apply --yes}" >&2
return 2
;;
esac
}
start_cluster() {
local target
local control_plane_target=""
declare -a CLUSTER_WORKER_TARGETS=()
require_debian_server "start-cluster"
cluster_context_require_startup || return 1
cluster_runtime_require || return 1
if [[ "${LAB_CLUSTER_RUNTIME:-kubeadm}" == k3s ]]; then
echo "Starting direct-host K3s on ${LAB_CLUSTER_CONTROL_PLANE_LAN_IP}; Pimox VMs remain stopped."
ssh -i "${LAB_CLUSTER_CONTROL_PLANE_SSH_KEY_PATH}" -o BatchMode=yes -o ConnectTimeout=10 \
"${LAB_CLUSTER_CONTROL_PLANE_USER}@${LAB_CLUSTER_CONTROL_PLANE_LAN_IP}" \
'set -euo pipefail; vms="$(sudo -n qm list | awk '\''NR > 1 && $3 != "stopped" {print $1}'\'')"; test -z "$vms" || { echo "Pimox VMs are running: $vms" >&2; exit 1; }; sudo -n systemctl start k3s' || return 1
wait_for_kubernetes_api "${LAB_CLUSTER_START_WAIT_SECONDS:-360}" || return 1
cluster_context_require || return 1
remember_cluster_profile || return 1
return 0
fi
cluster_worker_targets
echo "Starting Kubernetes cluster runtime without rebuilding state..."
if [[ "${LAB_CLUSTER_PROFILE:-debian}" == "pimox" ]]; then
start_pimox_control_plane_vm
start_pimox_worker_vms
wait_for_cluster_ssh_targets
ensure_pimox_registry_recovery_path
if [[ -n "${LAB_CLUSTER_CONTROL_PLANE_LAN_IP:-}" ]]; then
control_plane_target="${LAB_CLUSTER_CONTROL_PLANE_USER:-${LAB_DEBIAN_USER:-jv}}@${LAB_CLUSTER_CONTROL_PLANE_LAN_IP}"
start_remote_kubernetes_services "${control_plane_target}"
fi
for target in "${CLUSTER_WORKER_TARGETS[@]}"; do
start_remote_kubernetes_services "${target}"
done
wait_for_kubernetes_api "${LAB_CLUSTER_START_WAIT_SECONDS:-360}"
else
start_local_kubernetes_services
start_pimox_worker_vms
wait_for_cluster_ssh_targets
for target in "${CLUSTER_WORKER_TARGETS[@]}"; do
start_remote_kubernetes_services "${target}"
done
fi
wait_for_kubernetes_api "${LAB_CLUSTER_START_WAIT_SECONDS:-360}" || return 1
cluster_context_require || return 1
echo "Kubernetes runtime started and pinned cluster identity verified."
remember_cluster_profile || return 1
}
cleanup_debian_k8s_after_pimox_offload() {
require_debian_server "cleanup-debian-k8s"
cluster_context_require || return 1
if [[ "${LAB_CLUSTER_PROFILE:-debian}" != "pimox" ]]; then
echo "Skipping Debian Kubernetes cleanup because LAB_CLUSTER_PROFILE=${LAB_CLUSTER_PROFILE:-debian}."
echo "Select the enrolled Pimox profile before retiring the separate Debian cluster."
return 0
fi
if ! sudo test -e /etc/kubernetes/pki/ca.crt && ! sudo test -d /var/lib/etcd/member; then
retire_debian_service_hooks || return 1
echo "No Debian control-plane data remains; retired service hooks reconciled."
return 0
fi
# Retirement touches a different cluster from the active Pimox profile.
python3 "${REPO_ROOT}/scripts/cluster-context.py" check-local-host --profile debian || return 1
echo "Cleaning Debian-hosted Kubernetes runtime now that the active cluster profile is Pimox..."
echo "--> Disabling kubelet so the old local control plane does not restart on reboot..."
sudo systemctl disable --now kubelet 2>/dev/null || true
sudo systemctl reset-failed kubelet 2>/dev/null || true
echo "--> Stopping leftover Kubernetes containers in containerd's k8s.io namespace..."
if command -v crictl >/dev/null 2>&1; then
sudo crictl ps -aq 2>/dev/null | xargs -r sudo crictl stop 2>/dev/null || true
sudo crictl ps -aq 2>/dev/null | xargs -r sudo crictl rm 2>/dev/null || true
sudo crictl pods -q 2>/dev/null | xargs -r sudo crictl rmp -f 2>/dev/null || true
fi
if command -v ctr >/dev/null 2>&1; then
sudo ctr -n k8s.io tasks ls -q 2>/dev/null |
while IFS= read -r task; do
[[ -n "${task}" ]] || continue
sudo ctr -n k8s.io tasks kill -s SIGKILL "${task}" 2>/dev/null || true
sudo ctr -n k8s.io tasks rm -f "${task}" 2>/dev/null || true
done
sudo ctr -n k8s.io containers ls -q 2>/dev/null |
while IFS= read -r container; do
[[ -n "${container}" ]] || continue
sudo ctr -n k8s.io containers rm "${container}" 2>/dev/null || true
done
fi
echo "--> Resetting kubeadm state and removing local Kubernetes runtime files..."
sudo kubeadm reset --force 2>/dev/null || true
if command -v findmnt >/dev/null 2>&1; then
while IFS= read -r mountpoint; do
[[ -n "${mountpoint}" ]] || continue
sudo umount -f "${mountpoint}" 2>/dev/null || sudo umount -l "${mountpoint}" 2>/dev/null || true
done < <(
for mount_root in /var/lib/kubelet /run/calico /run/calico/cgroup /var/run/calico /var/run/calico/cgroup; do
findmnt -Rno TARGET "${mount_root}" 2>/dev/null || true
done | sort -ru
)
fi
sudo rm -rf \
/etc/kubernetes/ \
/var/lib/etcd/ \
/var/lib/kubelet/ \
/var/lib/cni/ \
/etc/cni/net.d \
/run/flannel \
/var/lib/calico \
/var/log/calico \
/run/calico \
/var/run/calico
echo "--> Removing local CNI/Calico interfaces without flushing host iptables..."
ip link show | awk -F: '/^[0-9]+: cali/ {print $2}' | cut -d@ -f1 |
xargs -r -n1 sudo ip link delete 2>/dev/null || true
sudo ip link delete vxlan.calico 2>/dev/null || true
sudo ip link delete tunl0 2>/dev/null || true
sudo ip link delete cni0 2>/dev/null || true
sudo ip link delete kube-ipvs0 2>/dev/null || true
retire_debian_service_hooks || return 1
echo "Debian Kubernetes runtime cleanup complete. Retired service hooks were detached; Docker and Jeannie forwarding rules remain active."
}
nuke_remote_cleanup_failed() {
local target="$1"
if truthy "${LAB_NUKE_ALLOW_REMOTE_CLEANUP_FAILURES:-false}"; then
echo "Warning: remote cleanup failed for ${target}; continuing because rebuild will destroy and recreate generated worker VMs." >&2
return 0
fi
echo "Remote cleanup failed for ${target}; not deleting OpenTofu state." >&2
return 1
}
kubernetes_api_reachable() {
kubectl --kubeconfig "${KUBECONFIG_PATH}" get --raw=/readyz >/dev/null 2>&1
}
wait_for_kubernetes_api_stable() {
local timeout_seconds="${1:-300}"
local stable_seconds="${2:-30}"
local interval_seconds="${3:-5}"
local elapsed=0
local stable_elapsed=0
echo "Waiting for Kubernetes API to stay ready for ${stable_seconds}s..."
until ((stable_elapsed >= stable_seconds)); do
if kubernetes_api_reachable; then
stable_elapsed=$((stable_elapsed + interval_seconds))
else
stable_elapsed=0
fi
if ((stable_elapsed >= stable_seconds)); then
return 0
fi
if ((elapsed >= timeout_seconds)); then
echo "Kubernetes API did not stay ready for ${stable_seconds}s within ${timeout_seconds}s." >&2
return 1
fi
sleep "${interval_seconds}"
elapsed=$((elapsed + interval_seconds))
done
}
ensure_kubernetes_api_ready_for_tofu_stack() {
local stack="$1"
case "${stack}" in
bootstrap/platform|bootstrap/apps)
wait_for_kubernetes_api_stable \
"${LAB_KUBERNETES_API_WAIT_TIMEOUT_SECONDS:-300}" \
"${LAB_KUBERNETES_API_STABLE_SECONDS:-30}" \
"${LAB_KUBERNETES_API_STABLE_INTERVAL_SECONDS:-5}"
;;
esac
}
cluster_control_plane_tracked() {
tofu_state_has_resource "bootstrap/cluster" "null_resource.kubeadm_control_plane"
}
cluster_admin_kubeconfig_present() {
[[ -s "${KUBECONFIG_PATH}" ]] ||
sudo test -s /etc/kubernetes/admin.conf 2>/dev/null ||
[[ -n "${KUBECONFIG:-}" && -s "${KUBECONFIG}" ]]
}
wait_for_kubernetes_api() {
local timeout_seconds="${1:-180}"
local elapsed=0
until kubernetes_api_reachable; do
if ((elapsed >= timeout_seconds)); then
echo "Kubernetes API did not become reachable after ${timeout_seconds}s." >&2
return 1
fi
sleep 5
elapsed=$((elapsed + 5))
done
}
ensure_existing_cluster_started_for_up() {
if ! cluster_control_plane_tracked; then
echo "No tracked kubeadm control plane found; bootstrap/cluster will create one."
return 0
fi
if ! cluster_admin_kubeconfig_present; then
cat >&2 <<EOF
OpenTofu tracks a kubeadm control plane, but no admin kubeconfig is present.
Checked: ${KUBECONFIG_PATH}, /etc/kubernetes/admin.conf, and KUBECONFIG.
Run ./jeannie rebuild-cluster to recreate kubeadm state and write a fresh kubeconfig.
EOF
return 1
fi
if kubernetes_api_reachable; then
echo "Existing Kubernetes control plane is reachable."
return 0
fi
echo "Existing Kubernetes control plane is tracked but API is down; starting cluster runtime..."
start_cluster
wait_for_kubernetes_api "${LAB_CLUSTER_START_WAIT_SECONDS:-180}"
echo "Existing Kubernetes control plane is reachable after start."
}
status_section() {
STATUS_CURRENT_SECTION="$1"
if truthy "${JEANNIE_REPORT_MODE:-false}"; then
return 0
fi
printf '\n== %s ==\n' "$1"
}
status_run() {
local description="$1"
shift
printf '\n-- %s\n' "${description}"
if ! "$@"; then
printf 'status check failed: %s\n' "${description}" >&2
fi
}
check_pimox_worker_tailnet_egress() {
local spec_file="${REPO_ROOT}/.lab/pimox-workers.tsv"
local probe_host="${LAB_PIMOX_WORKER_TAILNET_PROBE_HOST:-${LAB_DEBIAN_TAILSCALE_IP:-}}"
local probe_port="${LAB_PIMOX_WORKER_TAILNET_PROBE_PORT:-${LAB_GITEA_HTTP_PORT:-3000}}"
local failures=0
local found=0
local worker_key
local host
local user
local node_name
local key_path
local output
if [[ ! -s "${spec_file}" ]]; then
echo "No Pimox worker spec found at ${spec_file}; run ./jeannie up or set LAB_CLUSTER_VAR_FILE."
return 1
fi
if [[ -z "${probe_host}" ]]; then
echo "No tailnet probe host configured; set LAB_PIMOX_WORKER_TAILNET_PROBE_HOST or LAB_DEBIAN_TAILSCALE_IP."
return 1
fi
while IFS=$'\t' read -r worker_key host user node_name key_path; do
[[ -n "${worker_key}" && -n "${host}" && -n "${user}" && -n "${node_name}" && -n "${key_path}" ]] || continue
found=1
printf '%-28s ' "${node_name}"
if output="$(ssh -n -i "${key_path}" -o BatchMode=yes -o ConnectTimeout=8 -o StrictHostKeyChecking=accept-new "${user}@${host}" "
set -eu
command -v tailscale >/dev/null || { echo 'tailscale command missing'; exit 1; }
sudo systemctl is-active --quiet tailscaled || { echo 'tailscaled is not active'; exit 1; }
tailscale_ip=\"\$(tailscale ip -4 2>/dev/null | head -n 1 || true)\"
[ -n \"\$tailscale_ip\" ] || { echo 'worker is not joined to Tailscale'; exit 1; }
timeout 6 bash -c 'exec 3<>/dev/tcp/${probe_host}/${probe_port}' || { echo 'tailnet TCP probe failed'; exit 1; }
echo \"tailscale_ip=\$tailscale_ip\"
" 2>&1)"; then
printf 'ok - %s:%s reachable over tailnet (%s)\n' "${probe_host}" "${probe_port}" "${output}"
else
printf 'fail - %s\n' "$(printf '%s' "${output}" | head -n 1)"
failures=$((failures + 1))
fi
done <"${spec_file}"
if ((found == 0)); then
echo "No Pimox workers were listed in ${spec_file}."
return 1
fi
((failures == 0))
}
status_http() {
local name="$1"
local url="$2"
if command -v curl >/dev/null 2>&1; then
printf '%-28s ' "${name}"
curl -k -sS -o /dev/null --connect-timeout 5 --max-time 10 -w '%{http_code} %{url_effective}\n' "${url}" ||
printf 'unreachable %s\n' "${url}"
else
printf '%-28s curl not installed\n' "${name}"
fi
}
status_http_response() {
local url="$1"
if ! command -v curl >/dev/null 2>&1; then
echo "curl not installed" >&2
return 1
fi
curl -k -sS -o /dev/null --connect-timeout 5 --max-time 10 -w '%{http_code}' "${url}"
}
status_http_ok() {
local url="$1"
local status
status="$(report_ui_cached_probe status_http_response "${url}")" || {
echo "unreachable ${url}" >&2
return 1
}
case "${status}" in
2* | 3*)
return 0
;;
*)
echo "HTTP ${status} from ${url}" >&2
return 1
;;
esac
}
status_http_reachable() {
local url="$1"
local status
status="$(report_ui_cached_probe status_http_response "${url}")" || {
echo "unreachable ${url}" >&2
return 1
}
case "${status}" in
2* | 3* | 4*)
return 0
;;
*)
echo "HTTP ${status} from ${url}" >&2
return 1
;;
esac
}
status_gitea_public_ok() {
local root_url="${LAB_GITEA_ROOT_URL:-${LAB_PUBLIC_URL:?LAB_PUBLIC_URL is required from homelab.yml}/git/}"
status_http_reachable "${root_url}"
}
status_cascade_check() {
local description="$1"
local output
shift
if truthy "${JEANNIE_REPORT_MODE:-false}"; then
report_ui_check fail "${STATUS_CURRENT_SECTION:-Status}" "${description}" "./jeannie explain status" "" "" "$@" || return 1
return 0
fi
printf '%-36s ' "${description}"
if output="$("$@" 2>&1)"; then
printf 'ok\n'
if truthy "${LAB_STATUS_SHOW_OK_OUTPUT:-false}" && [[ -n "${output}" ]]; then
printf '%s\n' "${output}" | sed -n '1,6p' | sed 's/^/ /'
fi
return 0
fi
printf 'fail\n'
if [[ -n "${output}" ]]; then
printf '%s\n' "${output}" | sed -n '1,8p' | sed 's/^/ /'
fi
return 1
}
status_cascade_warn() {
local description="$1"
local output
local fix="./jeannie explain status"
shift
if truthy "${JEANNIE_REPORT_MODE:-false}"; then
[[ "${description}" != "Backup freshness" ]] || fix="./jeannie backup oci freshness"
[[ "${description}" != "Dex credential drift" ]] || fix="./jeannie doctor-dex"
report_ui_check warn "${STATUS_CURRENT_SECTION:-Status}" "${description}" "${fix}" "" "" "$@"
return 0
fi
printf '%-36s ' "${description}"
if output="$("$@" 2>&1)"; then
printf 'ok\n'
if truthy "${LAB_STATUS_SHOW_OK_OUTPUT:-false}" && [[ -n "${output}" ]]; then
printf '%s\n' "${output}" | sed -n '1,6p' | sed 's/^/ /'
fi
return 0
fi
printf 'warn\n'
if [[ -n "${output}" ]]; then
printf '%s\n' "${output}" | sed -n '1,6p' | sed 's/^/ /'
fi
return 0
}
status_container_running() {
local container="$1"
if ! command -v docker >/dev/null 2>&1; then
echo "docker not installed" >&2
return 1
fi
if ! sudo docker inspect -f '{{.State.Running}}' "${container}" 2>/dev/null | grep -qx true; then
echo "container ${container} is not running" >&2
return 1
fi
}
status_kubernetes_api_ok() {
if ! command -v kubectl >/dev/null 2>&1; then
echo "kubectl not installed" >&2
return 1
fi
if [[ ! -s "${KUBECONFIG_PATH}" ]]; then
echo "kubeconfig missing: ${KUBECONFIG_PATH}" >&2
return 1
fi
kubectl --kubeconfig "${KUBECONFIG_PATH}" --request-timeout=10s get --raw=/readyz >/dev/null
}
status_kubernetes_snapshot_fetch() {
local resource="$1"
local -a scope=()
[[ "${resource}" == nodes ]] || scope=(-A)
kubectl --kubeconfig "${KUBECONFIG_PATH}" --request-timeout=15s get "${resource}" "${scope[@]}" -o json
}
status_kubernetes_snapshot_check() {
local resource="$1" action="$2" snapshot
shift 2
if ! snapshot="$(report_ui_cached_probe status_kubernetes_snapshot_fetch "${resource}")"; then
printf 'Cannot read %s snapshot: %s\n' "${resource}" "${snapshot}" >&2
return 1
fi
printf '%s' "${snapshot}" | python3 "${REPO_ROOT}/scripts/report-kubernetes.py" "${action}" "$@"
}
status_kubernetes_nodes_ready() {
if [[ "${REPORT_UI_PARALLEL:-false}" == true && -n "${REPORT_UI_WORK_DIR:-}" ]]; then
status_kubernetes_snapshot_check nodes nodes-ready
return
fi
local nodes
local not_ready
nodes="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" get nodes --no-headers 2>/dev/null)" || return 1
if [[ -z "${nodes}" ]]; then
echo "no Kubernetes nodes found" >&2
return 1
fi
not_ready="$(awk '$2 !~ /^Ready/ { print $1 ":" $2 }' <<<"${nodes}")"
if [[ -n "${not_ready}" ]]; then
echo "not ready: ${not_ready}" >&2
return 1
fi
}
status_kubernetes_deployment_ready() {
local namespace="$1"
local deployment="$2"
if [[ "${REPORT_UI_PARALLEL:-false}" == true && -n "${REPORT_UI_WORK_DIR:-}" ]]; then
status_kubernetes_snapshot_check deployments deployment-ready "${namespace}" "${deployment}"
return
fi
kubectl --kubeconfig "${KUBECONFIG_PATH}" -n "${namespace}" rollout status "deployment/${deployment}" --timeout=5s >/dev/null
}
status_kubernetes_statefulset_ready() {
local namespace="$1"
local statefulset="$2"
if [[ "${REPORT_UI_PARALLEL:-false}" == true && -n "${REPORT_UI_WORK_DIR:-}" ]]; then
status_kubernetes_snapshot_check statefulsets statefulset-ready "${namespace}" "${statefulset}"
return
fi
kubectl --kubeconfig "${KUBECONFIG_PATH}" -n "${namespace}" rollout status "statefulset/${statefulset}" --timeout=5s >/dev/null
}
status_kubernetes_deployment_image_not_bootstrap() {
local namespace="$1"
local deployment="$2"
local container="$3"
local image
if [[ "${REPORT_UI_PARALLEL:-false}" == true && -n "${REPORT_UI_WORK_DIR:-}" ]]; then
status_kubernetes_snapshot_check deployments image "${namespace}" "${deployment}" "${container}"
return
fi
image="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" -n "${namespace}" get deployment "${deployment}" \
-o "jsonpath={.spec.template.spec.containers[?(@.name==\"${container}\")].image}" 2>/dev/null || true)"
if [[ -z "${image}" ]]; then
echo "could not read image for ${namespace}/deployment/${deployment} container ${container}" >&2
return 1
fi
if [[ "${image}" == *":bootstrap" ]]; then
echo "${namespace}/deployment/${deployment} still points to bootstrap image: ${image}" >&2
return 1
fi
}
status_no_problem_pods() {
local rows
if [[ "${REPORT_UI_PARALLEL:-false}" == true && -n "${REPORT_UI_WORK_DIR:-}" ]]; then
status_kubernetes_snapshot_check pods pods-problems
return
fi
rows="$(
kubectl --kubeconfig "${KUBECONFIG_PATH}" get pods -A --no-headers 2>/dev/null |
awk '$4 != "Running" && $4 != "Completed" { print $1 "/" $2 ":" $4 }'
)"
if [[ -n "${rows}" ]]; then
printf '%s\n' "${rows}" >&2
return 1
fi
}
status_recent_deployments() {
local rows
if [[ "${REPORT_UI_PARALLEL:-false}" == true && -n "${REPORT_UI_WORK_DIR:-}" ]]; then
status_kubernetes_snapshot_check deployments deployments
return
fi
rows="$(
kubectl --kubeconfig "${KUBECONFIG_PATH}" get deployments -A \
-o custom-columns='NAMESPACE:.metadata.namespace,NAME:.metadata.name,READY:.status.readyReplicas,DESIRED:.spec.replicas,UPDATED:.status.updatedReplicas,AVAILABLE:.status.availableReplicas,AGE:.metadata.creationTimestamp' \
--no-headers 2>/dev/null |
awk '{ ready = ($3 == "<none>" ? 0 : $3); updated = ($5 == "<none>" ? 0 : $5); available = ($6 == "<none>" ? 0 : $6); if (ready != $4 || updated != $4 || available != $4) print }'
)"
if [[ -n "${rows}" ]]; then
printf '%s\n' "${rows}" >&2
return 1
fi
}
status_pod_restart_pressure() {
local threshold="${LAB_STATUS_RESTART_THRESHOLD:-3}"
local rows
if [[ "${REPORT_UI_PARALLEL:-false}" == true && -n "${REPORT_UI_WORK_DIR:-}" ]]; then
status_kubernetes_snapshot_check pods pod-restarts "${threshold}"
return
fi
rows="$(
kubectl --kubeconfig "${KUBECONFIG_PATH}" get pods -A --no-headers 2>/dev/null |
awk -v threshold="${threshold}" '$5 + 0 >= threshold { print $1 "/" $2 ": restarts=" $5 " age=" $6 }'
)"
if [[ -n "${rows}" ]]; then
printf '%s\n' "${rows}" >&2
return 1
fi
}
status_node_pressure() {
local rows
if [[ "${REPORT_UI_PARALLEL:-false}" == true && -n "${REPORT_UI_WORK_DIR:-}" ]]; then
status_kubernetes_snapshot_check nodes node-pressure
return
fi
rows="$(
kubectl --kubeconfig "${KUBECONFIG_PATH}" get nodes -o jsonpath='{range .items[*]}{.metadata.name}{" "}{range .status.conditions[*]}{.type}{"="}{.status}{" "}{end}{"\n"}{end}' 2>/dev/null |
awk '/MemoryPressure=True|DiskPressure=True|PIDPressure=True|NetworkUnavailable=True/ { print }'
)"
if [[ -n "${rows}" ]]; then
printf '%s\n' "${rows}" >&2
return 1
fi
}
status_disk_pressure() {
local threshold="${LAB_STATUS_DISK_USE_THRESHOLD:-85}"
local rows
rows="$(df -P / /data 2>/dev/null | awk -v threshold="${threshold}" 'NR > 1 { gsub(/%/, "", $5); if ($5 + 0 >= threshold) print $6 ": " $5 "% used" }')"
if [[ -n "${rows}" ]]; then
printf '%s\n' "${rows}" >&2
return 1
fi
}
status_traefik_error_rates() {
local since="${LAB_STATUS_LOG_SINCE:-5m}"
local sample
local count_502
local count_404
if ! sample="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" -n traefik logs -l app.kubernetes.io/name=traefik --since="${since}" --tail=2000 2>&1)"; then
echo "Unable to read Traefik logs; service state is unknown." >&2
return 1
fi
if [[ -z "${sample}" ]]; then
return 0
fi
count_502="$(grep -Eac '(^|[^0-9])50[234]([^0-9]|$)|level=error' <<<"${sample}" || true)"
count_404="$(grep -Eac '(^|[^0-9])404([^0-9]|$)' <<<"${sample}" || true)"
if ((count_502 > 0)); then
printf '5xx/error lines in last %s: %s\n' "${since}" "${count_502}" >&2
return 1
fi
printf '404 lines in last %s: %s\n' "${since}" "${count_404}" >&2
}
status_gitea_recent_errors() {
local since="${LAB_STATUS_LOG_SINCE:-5m}"
local container="${GITEA_CONTAINER_NAME:-homelab-gitea}"
local sample
local matches
if ! command -v docker >/dev/null 2>&1; then
echo "docker not installed" >&2
return 1
fi
if ! sudo docker inspect "${container}" >/dev/null 2>&1; then
echo "container ${container} not found" >&2
return 1
fi
if ! sample="$(sudo docker logs --since "${since}" --tail 2000 "${container}" 2>&1)"; then
echo "Unable to read Gitea logs; service state is unknown." >&2
return 1
fi
matches="$(grep -Eai 'error|panic|fatal|authentication failed|denied| 50[0-9] ' <<<"${sample}" | tail -10 || true)"
if [[ -n "${matches}" ]]; then
local all_matches count
all_matches="$(grep -Eai 'error|panic|fatal|authentication failed|denied| 50[0-9] ' <<<"${sample}" || true)"
count="$(printf '%s\n' "${all_matches}" | wc -l | tr -d ' ')"
if ((count <= 3)) && ! grep -Eavi 'broken pipe|connection reset by peer' <<<"${all_matches}" >/dev/null && \
report_ui_cached_probe status_container_running "${container}" >/dev/null 2>&1 && \
report_ui_cached_probe status_http_ok "http://127.0.0.1:${LAB_GITEA_HTTP_PORT:-3000}/" >/dev/null 2>&1 && \
report_ui_cached_probe status_gitea_public_ok >/dev/null 2>&1; then
printf 'Recent client disconnects (%s in %s); Gitea container and HTTP checks currently pass. No fix indicated; monitor for recurrence.\n%s\n' "${count}" "${since}" "${matches}"
return 3
fi
printf '%s\n' "${matches}" >&2
return 1
fi
}
status_cascade_recent_gitea() {
if truthy "${JEANNIE_REPORT_MODE:-false}" && [[ "${REPORT_UI_PARALLEL:-false}" == true ]]; then
report_ui_enqueue status_cascade_recent_gitea_sync
else
status_cascade_recent_gitea_sync
fi
}
status_cascade_recent_gitea_sync() {
local output status=0
output="$(status_gitea_recent_errors 2>&1)" || status=$?
if truthy "${JEANNIE_REPORT_MODE:-false}"; then
case "${status}" in
0) report_ui_emit ok "${STATUS_CURRENT_SECTION:-Status}" "Gitea recent errors" "ok" ;;
3) report_ui_emit info "Recent events" "Gitea client disconnects" "$(printf '%s\n' "${output}" | report_ui_first_line)" "${output}" ;;
*) report_ui_emit warn "${STATUS_CURRENT_SECTION:-Status}" "Gitea recent errors" "$(printf '%s\n' "${output}" | report_ui_first_line)" "${output}" "./jeannie doctor-gitea" ;;
esac
elif (( status != 0 )); then
printf '%s\n' "${output}"
fi
return 0
}
status_registry_ok() {
status_http_ok "http://${LAB_REGISTRY_ENDPOINT:-192.168.100.73:30500}/v2/"
}
status_registry_from_pimox_workers() {
local spec_file="${REPO_ROOT}/.lab/pimox-workers.tsv"
local registry_endpoint="${LAB_REGISTRY_ENDPOINT:-192.168.100.73:30500}"
local failures=0
local found=0
local worker_key
local host
local user
local node_name
local key_path
local output
if [[ "${LAB_CLUSTER_RUNTIME:-kubeadm}" == k3s ]]; then
echo "native K3s uses its control-plane registry probe" >&2
return 1
fi
if [[ ! -s "${spec_file}" ]]; then
echo "No Pimox worker spec found at ${spec_file}; run ./jeannie up or set LAB_CLUSTER_VAR_FILE." >&2
return 1
fi
while IFS=$'\t' read -r worker_key host user node_name key_path; do
[[ -n "${worker_key}" && -n "${host}" && -n "${user}" && -n "${node_name}" && -n "${key_path}" ]] || continue
found=1
if ! output="$(ssh -n -i "${key_path}" -o BatchMode=yes -o ConnectTimeout=8 -o StrictHostKeyChecking=accept-new "${user}@${host}" \
"curl -fsS --connect-timeout 5 --max-time 10 'http://${registry_endpoint}/v2/' >/dev/null && echo ok" 2>&1)"; then
echo "${node_name}: ${output}" >&2
failures=$((failures + 1))
fi
done <"${spec_file}"
if ((found == 0)); then
echo "No Pimox workers were listed in ${spec_file}." >&2
return 1
fi
((failures == 0))
}
status_dex_local_ok() {
status_http_reachable "http://127.0.0.1:${LAB_DEX_HTTP_PORT:-5556}/healthz"
}
status_ollama_local_ok() {
local url="${LAB_OLLAMA_URL:-http://${LAB_DEBIAN_LAN_IP:-192.168.100.73}:11434}"
status_http_ok "${url%/}/api/tags"
}
status_rpi_uptime_kuma_ok() {
local rpi_host="${LAB_RPI_HOST:-${LAB_RASPBERRY_HOST:-192.168.100.89}}"
local rpi_user="${LAB_RPI_USER:-${LAB_RASPBERRY_USER:-jv}}"
local rpi_key="${LAB_RPI_SSH_KEY_PATH:-${LAB_RASPBERRY_SSH_KEY_PATH:-/home/jv/.ssh/id_ed25519}}"
local uptime_kuma_port="${UPTIME_KUMA_PORT:-3001}"
ssh -i "${rpi_key}" -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new "${rpi_user}@${rpi_host}" \
"curl -fsS --max-time 5 'http://127.0.0.1:${uptime_kuma_port}/' >/dev/null"
}
status_pimox_workers_running() {
if [[ "${LAB_CLUSTER_RUNTIME:-kubeadm}" == k3s ]]; then
echo "Native K3s uses the Orange Pi host; worker VMs are expected to be stopped."
return 0
fi
local pimox_host="${LAB_PIMOX_HOST:-${TF_VAR_pimox_host:-192.168.100.80}}"
local pimox_user="${LAB_PIMOX_USER:-${TF_VAR_pimox_user:-jv}}"
local pimox_key="${LAB_PIMOX_SSH_KEY_PATH:-${TF_VAR_pimox_ssh_key_path:-/home/jv/.ssh/id_ed25519}}"
local qm_bin="${LAB_PIMOX_QM_BIN:-${TF_VAR_pimox_qm_bin:-/usr/sbin/qm}}"
local worker_count
local worker_base_vmid="${LAB_PIMOX_WORKER_BASE_VMID:-9010}"
local worker_skip_indexes="${LAB_PIMOX_SKIP_WORKER_INDEXES:-}"
local index
local vmid
local failures=0
worker_count="$(pimox_worker_count_effective)"
if ! [[ "${worker_count}" =~ ^[0-9]+$ ]]; then
echo "invalid worker count ${worker_count}" >&2
return 1
fi
for ((index = 1; index <= worker_count; index++)); do
if worker_index_is_skipped "${index}" "${worker_skip_indexes}"; then
continue
fi
vmid=$((worker_base_vmid + index - 1))
if ! pimox_ssh "${pimox_host}" "${pimox_user}" "${pimox_key}" "sudo '${qm_bin}' status '${vmid}' | grep -q 'status: running'"; then
echo "VM ${vmid} is not running" >&2
failures=$((failures + 1))
fi
done
((failures == 0))
}
status_pimox_control_plane_running() {
local pimox_host="${LAB_PIMOX_HOST:-${TF_VAR_pimox_host:-192.168.100.80}}"
local pimox_user="${LAB_PIMOX_USER:-${TF_VAR_pimox_user:-jv}}"
local pimox_key="${LAB_PIMOX_SSH_KEY_PATH:-${TF_VAR_pimox_ssh_key_path:-/home/jv/.ssh/id_ed25519}}"
local qm_bin="${LAB_PIMOX_QM_BIN:-${TF_VAR_pimox_qm_bin:-/usr/sbin/qm}}"
local vmid="${LAB_CLUSTER_PIMOX_CONTROL_PLANE_VMID:-${LAB_PIMOX_CONTROL_PLANE_VMID:-}}"
if [[ "${LAB_CLUSTER_PROFILE:-debian}" != "pimox" ]]; then
echo "cluster profile is ${LAB_CLUSTER_PROFILE:-debian}, not pimox" >&2
return 1
fi
if [[ -z "${vmid}" ]]; then
echo "Pimox control-plane VMID is not configured." >&2
return 1
fi
pimox_ssh "${pimox_host}" "${pimox_user}" "${pimox_key}" "sudo '${qm_bin}' status '${vmid}' | grep -q 'status: running'"
}
status_cluster_profile_valid() {
cluster_context_require_startup
}
status_cluster_control_runtime() {
local unit=kubelet
[[ "${LAB_CLUSTER_RUNTIME:-kubeadm}" != k3s ]] || unit=k3s
ssh -n -i "${LAB_CLUSTER_CONTROL_PLANE_SSH_KEY_PATH}" \
-o BatchMode=yes -o ConnectTimeout=8 -o StrictHostKeyChecking=accept-new \
"${LAB_CLUSTER_CONTROL_PLANE_USER}@${LAB_CLUSTER_CONTROL_PLANE_LAN_IP}" \
"systemctl is-active ${unit}"
}
status_cluster_storage() {
if [[ "${LAB_CLUSTER_RUNTIME:-kubeadm}" != k3s ]]; then
check_pimox_storage
return
fi
local mount="${LAB_CLUSTER_REQUIRED_DATA_MOUNT:-}"
local runtime_check='mountpoint -q /var/lib/rancher/k3s && '
[[ "${1:-runtime}" != bootstrap ]] || runtime_check=''
if [[ -n "${mount}" && "${mount}" =~ ^/[a-zA-Z0-9_./-]+$ && "${mount}" != *..* ]]; then
ssh -n -i "${LAB_CLUSTER_CONTROL_PLANE_SSH_KEY_PATH}" \
-o BatchMode=yes -o ConnectTimeout=8 -o StrictHostKeyChecking=accept-new \
"${LAB_CLUSTER_CONTROL_PLANE_USER}@${LAB_CLUSTER_CONTROL_PLANE_LAN_IP}" \
"mountpoint -q '${mount}' && ${runtime_check}findmnt -n -M '${mount}' -o OPTIONS | grep -E '(^|,)rw(,|$)'"
else
echo "Native K3s data mount is not declared." >&2
return 1
fi
}
status_registry_from_cluster_nodes() {
if [[ "${LAB_CLUSTER_RUNTIME:-kubeadm}" != k3s ]]; then
status_registry_from_pimox_workers
return
fi
local endpoint="${LAB_REGISTRY_ENDPOINT}"
[[ "${endpoint}" =~ ^[a-zA-Z0-9.:-]+$ ]] || return 1
ssh -n -i "${LAB_CLUSTER_CONTROL_PLANE_SSH_KEY_PATH}" \
-o BatchMode=yes -o ConnectTimeout=8 -o StrictHostKeyChecking=accept-new \
"${LAB_CLUSTER_CONTROL_PLANE_USER}@${LAB_CLUSTER_CONTROL_PLANE_LAN_IP}" \
"curl -fsS --connect-timeout 5 --max-time 10 'http://${endpoint}/v2/' >/dev/null"
}
status_external_services_host_declared() {
if [[ -z "${LAB_SERVICES_HOST_LAN_IP:-${LAB_DEBIAN_LAN_IP:-}}" ]]; then
echo "external services host LAN IP is not resolved from homelab.yml" >&2
return 1
fi
if [[ -z "${LAB_GITEA_BACKEND_HOST:-${LAB_GITEA_TAILSCALE_IP:-${LAB_DEBIAN_TAILSCALE_IP:-}}}" ]]; then
echo "Gitea/edge backend host is not resolved from homelab.yml" >&2
return 1
fi
if [[ -z "${LAB_REGISTRY_ENDPOINT:-}" ]]; then
echo "registry endpoint is not resolved from homelab.yml" >&2
return 1
fi
}
status_cascade_report() {
local failures=0
status_section "Status Cascade"
if [[ "${JEANNIE_STATUS_MODE:-deep}" == deep ]]; then
status_cascade_check "inventory YAML" inventory_check || failures=$((failures + 1))
status_cascade_check "Debian Docker root" check_debian_docker_root || failures=$((failures + 1))
fi
status_cascade_check "Debian Docker service" check_systemd_active docker || failures=$((failures + 1))
status_cascade_check "Debian containerd service" check_systemd_active containerd || failures=$((failures + 1))
status_cascade_check "Debian Tailscale IP" check_debian_tailscale_ip || failures=$((failures + 1))
status_section "Git And Local Services"
status_cascade_check "Gitea container" status_container_running "${GITEA_CONTAINER_NAME:-homelab-gitea}" || failures=$((failures + 1))
status_cascade_check "Gitea local HTTP" status_http_ok "http://127.0.0.1:${LAB_GITEA_HTTP_PORT:-3000}/" || failures=$((failures + 1))
status_cascade_warn "Arr Radarr HTTP" status_http_ok "http://127.0.0.1:7878/"
status_cascade_warn "Arr Sonarr HTTP" status_http_ok "http://127.0.0.1:8989/"
status_cascade_warn "Arr Prowlarr HTTP" status_http_ok "http://127.0.0.1:9696/"
status_section "RPi Bootstrap And DNS"
if [[ "${JEANNIE_STATUS_MODE:-deep}" == deep ]]; then
status_cascade_check "RPi SSH" check_rpi_ssh || failures=$((failures + 1))
status_cascade_check "RPi Docker root state" check_rpi_docker_root_state || failures=$((failures + 1))
fi
status_cascade_check "Pi-hole DNS" check_pihole_dns_query || failures=$((failures + 1))
if [[ "${JEANNIE_STATUS_MODE:-deep}" == deep ]]; then
status_cascade_warn "RPi Tailscale IP" check_rpi_tailscale_ip
status_cascade_warn "Uptime Kuma HTTP" status_rpi_uptime_kuma_ok
fi
status_section "Cluster (${LAB_CLUSTER_PROFILE} / ${LAB_CLUSTER_RUNTIME})"
status_cascade_check "Cluster storage" status_cluster_storage || failures=$((failures + 1))
status_cascade_check "Control-plane runtime" status_cluster_control_runtime || failures=$((failures + 1))
status_cascade_check "Inactive profiles stopped" cluster_runtime_require || failures=$((failures + 1))
if [[ "${LAB_CLUSTER_RUNTIME}" != k3s ]]; then
status_cascade_check "Pimox workers running" status_pimox_workers_running || failures=$((failures + 1))
fi
status_cascade_check "Kubernetes API" status_kubernetes_api_ok || failures=$((failures + 1))
status_cascade_check "Cluster identity" cluster_context_require || failures=$((failures + 1))
status_cascade_check "Kubernetes nodes Ready" status_kubernetes_nodes_ready || failures=$((failures + 1))
status_cascade_warn "No problem pods" status_no_problem_pods
status_section "What Broke Signals"
if [[ "${JEANNIE_STATUS_MODE:-deep}" == deep ]]; then
status_cascade_warn "Backup freshness" backup_status
fi
status_cascade_warn "Recent deployments healthy" status_recent_deployments
status_cascade_warn "Dex credential drift" dex_drift_check
if [[ "${JEANNIE_STATUS_MODE:-deep}" == deep ]]; then
status_cascade_warn "Pod restart pressure" status_pod_restart_pressure
fi
status_cascade_warn "Node pressure" status_node_pressure
status_cascade_warn "Disk usage" status_disk_pressure
if [[ "${JEANNIE_STATUS_MODE:-deep}" == deep ]]; then
status_cascade_warn "Traefik 5xx/404 signals" status_traefik_error_rates
status_cascade_recent_gitea
fi
status_section "Platform And Apps"
status_cascade_check "Local registry" status_registry_ok || failures=$((failures + 1))
status_cascade_check "Traefik deployment" status_kubernetes_deployment_ready traefik traefik || failures=$((failures + 1))
status_cascade_check "Website deployment" status_kubernetes_deployment_ready website-production php-website-deployment || failures=$((failures + 1))
status_cascade_warn "Argo CD server" status_kubernetes_deployment_ready argocd argocd-server
status_section "Edge And Public URLs"
if [[ "${JEANNIE_STATUS_MODE:-deep}" == deep ]]; then
status_cascade_check "OCI edge SSH" check_edge_ssh || failures=$((failures + 1))
fi
status_cascade_check "Traefik LoadBalancer HTTP" status_http_reachable "http://${LAB_TRAEFIK_LB_IP:?LAB_TRAEFIK_LB_IP is required from homelab.yml}/" || failures=$((failures + 1))
status_cascade_check "Website public URL" status_http_ok "${LAB_PUBLIC_URL:?LAB_PUBLIC_URL is required from homelab.yml}/" || failures=$((failures + 1))
status_cascade_check "Gitea public route" status_gitea_public_ok || failures=$((failures + 1))
if truthy "${JEANNIE_REPORT_MODE:-false}"; then
return "${failures}"
fi
if ((failures > 0)); then
printf '\nStatus cascade found %s blocking failure(s).\n' "${failures}" >&2
return 1
fi
printf '\nStatus cascade passed.\n'
}
backstage_brain_enabled() {
local provider="${LAB_AI_GATEWAY_PROVIDER:-ollama}"
local enabled="${LAB_BACKSTAGE_BRAIN_ENABLED:-false}"
[[ "${provider,,}" =~ ^(ollama|omniroute|openai)$ ]] && truthy "${enabled}"
}
backstage_brain_note() {
# Verbose output is not a structured report and cannot support evidence
# validation. Use the compact doctor with --ai for a validated explanation.
if backstage_brain_enabled; then
echo "AI explanation skipped for verbose output; run the compact doctor with --ai."
fi
return 0
}
status_systemd_units() {
local unit
for unit in "$@"; do
if systemctl list-unit-files --no-legend "${unit}.service" 2>/dev/null | grep -q .; then
printf '%-28s %s\n' "${unit}" "$(systemctl is-active "${unit}" 2>/dev/null || true)"
else
printf '%-28s not-installed\n' "${unit}"
fi
done
}
status_compose_stack() {
local name="$1"
local directory="$2"
printf '\n-- Docker Compose: %s (%s)\n' "${name}" "${directory}"
if [[ ! -d "${directory}" ]]; then
printf 'missing directory\n'
return 0
fi
if ! command -v docker >/dev/null 2>&1; then
printf 'docker not installed\n'
return 0
fi
if ! sudo docker compose version >/dev/null 2>&1; then
printf 'docker compose unavailable\n'
return 0
fi
(cd "${directory}" && sudo docker compose ps) || true
}
status_kubernetes() {
status_section "Kubernetes"
if ! command -v kubectl >/dev/null 2>&1; then
printf 'kubectl not installed\n'
return 0
fi
if [[ ! -s "${KUBECONFIG_PATH}" ]]; then
printf 'kubeconfig missing: %s\n' "${KUBECONFIG_PATH}"
return 0
fi
if ! kubectl --kubeconfig "${KUBECONFIG_PATH}" get --raw=/readyz >/dev/null 2>&1; then
printf 'API server not reachable through %s\n' "${KUBECONFIG_PATH}"
return 0
fi
status_run "nodes" kubectl --kubeconfig "${KUBECONFIG_PATH}" get nodes -o wide
status_kubernetes_problem_pods
status_run "traefik services" kubectl --kubeconfig "${KUBECONFIG_PATH}" -n traefik get svc,pods -o wide
status_run "website pods" kubectl --kubeconfig "${KUBECONFIG_PATH}" -n website-production get pods -o wide
}
status_kubernetes_problem_pods() {
local rows
printf '\n-- pods not Running/Completed\n'
rows="$(
kubectl --kubeconfig "${KUBECONFIG_PATH}" get pods -A --no-headers -o wide |
awk '$4 != "Running" && $4 != "Completed" { print }'
)"
if [[ -n "${rows}" ]]; then
printf '%s\n' "${rows}"
else
printf 'none\n'
fi
}
status_pimox_workers() {
if [[ "${LAB_CLUSTER_RUNTIME:-kubeadm}" == k3s ]]; then
status_section "Native K3s"
status_run "K3s service" status_cluster_control_runtime
status_run "K3s data mount" status_cluster_storage
return
fi
local pimox_host="${LAB_PIMOX_HOST:-${TF_VAR_pimox_host:-192.168.100.80}}"
local pimox_user="${LAB_PIMOX_USER:-${TF_VAR_pimox_user:-jv}}"
local pimox_key="${LAB_PIMOX_SSH_KEY_PATH:-${TF_VAR_pimox_ssh_key_path:-/home/jv/.ssh/id_ed25519}}"
local qm_bin="${LAB_PIMOX_QM_BIN:-${TF_VAR_pimox_qm_bin:-/usr/sbin/qm}}"
local worker_count
local worker_base_vmid="${LAB_PIMOX_WORKER_BASE_VMID:-9010}"
local worker_skip_indexes="${LAB_PIMOX_SKIP_WORKER_INDEXES:-}"
local index
local vmid
status_section "Pimox Workers"
worker_count="$(pimox_worker_count_effective)"
if ! [[ "${worker_count}" =~ ^[0-9]+$ ]]; then
printf 'invalid LAB_PIMOX_WORKER_COUNT: %s\n' "${worker_count}"
return 0
fi
if ((worker_count == 0)); then
printf 'worker count is 0\n'
return 0
fi
for ((index = 1; index <= worker_count; index++)); do
if worker_index_is_skipped "${index}" "${worker_skip_indexes}"; then
printf 'worker index %s skipped\n' "${index}"
continue
fi
vmid=$((worker_base_vmid + index - 1))
printf 'VM %-6s ' "${vmid}"
pimox_ssh "${pimox_host}" "${pimox_user}" "${pimox_key}" "sudo '${qm_bin}' status '${vmid}'" 2>/dev/null ||
printf 'unreachable or missing\n'
done
}
status_rpi_services() {
local rpi_host="${LAB_RPI_HOST:-${LAB_RASPBERRY_HOST:-192.168.100.89}}"
local rpi_user="${LAB_RPI_USER:-${LAB_RASPBERRY_USER:-jv}}"
local rpi_key="${LAB_RPI_SSH_KEY_PATH:-${LAB_RASPBERRY_SSH_KEY_PATH:-/home/jv/.ssh/id_ed25519}}"
local install_dir="${LAB_RPI_SERVICES_INSTALL_DIR:-/opt/homelab-rpi-services}"
local docker_nvme_root="${LAB_RPI_DOCKER_ROOT:-${LAB_RPI_DOCKER_NVME_ROOT:-/nvme-storage/docker}}"
local docker_fallback_root="${LAB_RPI_DOCKER_FALLBACK_ROOT:-/var/lib/docker}"
local pihole_container="${PIHOLE_CONTAINER_NAME:-homelab-pihole}"
local unbound_container="${UNBOUND_CONTAINER_NAME:-homelab-unbound}"
local uptime_kuma_port="${UPTIME_KUMA_PORT:-3001}"
status_section "RPi Services"
ssh -i "${rpi_key}" -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new "${rpi_user}@${rpi_host}" "
set +e
dns_query() {
server=\"\$1\"
port=\"\$2\"
name=\"\$3\"
python3 - \"\$server\" \"\$port\" \"\$name\" <<'PY'
import random
import socket
import struct
import sys
server, port, name = sys.argv[1], int(sys.argv[2]), sys.argv[3].rstrip('.')
query_id = random.randrange(0, 65536)
packet = struct.pack('!HHHHHH', query_id, 0x0100, 1, 0, 0, 0)
for label in name.split('.'):
packet += bytes([len(label)]) + label.encode('ascii')
packet += b'\x00' + struct.pack('!HH', 1, 1)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.settimeout(5)
sock.sendto(packet, (server, port))
data, _ = sock.recvfrom(512)
if len(data) < 12:
raise SystemExit('short DNS response')
response_id, flags, _qd, an, _ns, _ar = struct.unpack('!HHHHHH', data[:12])
rcode = flags & 0x000f
if response_id != query_id:
raise SystemExit('mismatched DNS response id')
if rcode != 0:
raise SystemExit(f'DNS rcode {rcode}')
if an < 1:
raise SystemExit('DNS response had no answers')
print(f'ok answers={an}')
PY
}
check() {
label=\"\$1\"
shift
printf '%-34s ' \"\$label\"
output=\"\$("\$@" 2>&1)\"
status=\$?
if [ \"\$status\" -eq 0 ]; then
printf 'ok'
if [ -n \"\$output\" ]; then
printf ' - %s' \"\$(printf '%s' \"\$output\" | head -n 1)\"
fi
printf '\n'
else
printf 'fail - %s\n' \"\$(printf '%s' \"\$output\" | head -n 1)\"
fi
return 0
}
docker_root=\"\$(sudo docker info --format '{{.DockerRootDir}}' 2>/dev/null || true)\"
printf '%-34s %s\n' 'Docker root' \"\${docker_root:-unknown}\"
if [ \"\$docker_root\" = '${docker_nvme_root}' ]; then
if mountpoint -q '${docker_nvme_root}'; then
printf '%-34s ok - nvme mount active\n' 'Docker root class'
else
printf '%-34s warn - configured for nvme but mountpoint is missing\n' 'Docker root class'
fi
elif [ \"\$docker_root\" = '${docker_fallback_root}' ]; then
printf '%-34s warn - fallback root active; expected ${docker_nvme_root}\n' 'Docker root class'
else
printf '%-34s warn - unexpected docker root\n' 'Docker root class'
fi
if [ -d '${install_dir}' ]; then
cd '${install_dir}'
sudo docker compose ps || true
unbound_ip=\"\$(sudo docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' '${unbound_container}' 2>/dev/null || true)\"
check 'Pi-hole DNS query' dns_query 127.0.0.1 53 cloudflare.com
if [ -n \"\$unbound_ip\" ]; then
check 'Unbound DNS query' dns_query \"\$unbound_ip\" 53 cloudflare.com
else
printf '%-34s fail - container IP unavailable\n' 'Unbound DNS query'
fi
upstreams=\"\$(sudo docker inspect -f '{{range .Config.Env}}{{println .}}{{end}}' '${pihole_container}' 2>/dev/null | grep -E '^PIHOLE_DNS_=|^FTLCONF_dns_upstreams=' || true)\"
if printf '%s\n' \"\$upstreams\" | grep -Eq '1\\.1\\.1\\.1|9\\.9\\.9\\.9|8\\.8\\.8\\.8'; then
printf '%-34s ok - public fallback configured\n' 'Pi-hole fallback config'
else
printf '%-34s warn - no public fallback found in visible config\n' 'Pi-hole fallback config'
fi
check 'Fallback resolver 1.1.1.1' dns_query 1.1.1.1 53 cloudflare.com
check 'Fallback resolver 9.9.9.9' dns_query 9.9.9.9 53 cloudflare.com
check 'Uptime Kuma HTTP' curl -fsS --max-time 5 \"http://127.0.0.1:${uptime_kuma_port}/\"
else
echo 'RPi services install directory is missing: ${install_dir}'
fi" || printf 'unable to reach %s@%s\n' "${rpi_user}" "${rpi_host}"
}
status_usage() {
cat <<'EOF'
Usage: ./jeannie status [all|oci|rpi|opi5|debian|cluster] [options]
Without arguments, show a fast overview of all areas. A scope limits the
overview to that area; cluster uses the selected cluster profile.
all All areas, including Compose and Argo CD applications
oci OCI edge connectivity and Compose services
rpi Raspberry Pi services and Compose containers
opi5 Orange Pi host, Compose containers, and selected K3s runtime
debian Debian services and Compose containers
cluster Selected Kubernetes cluster and Argo CD applications
Scoped overview options:
--details Accepted for compatibility; text stays concise.
--json Output structured JSON.
--all Include all results (the scoped overview default).
--no-local-rca Disable AI explanations (already disabled for scopes).
Unscoped diagnostic options retain the existing status report:
--fast Run the existing fast diagnostic checks.
--deep Run the deeper diagnostic checks.
--json Output the existing machine-readable diagnostic report.
--details Accepted for compatibility; text stays concise.
--all Include passing and skipped checks.
--ai Enable AI analysis in the healing workflow.
--no-local-rca Disable AI explanations.
--verbose Run deep checks with concise status output.
--heal-plan Show the proposed healing plan using deep checks.
--heal Run the existing healing workflow using deep checks.
Examples:
./jeannie status oci --details
./jeannie remote status cluster --json
./jeannie status --deep --no-local-rca
EOF
}
status_report() {
local cascade_status=0
local heal_mode=""
local requested_mode=""
local -x JEANNIE_STATUS_MODE=fast
local status_json
local -a status_args=()
case "${1:-}" in
-h|--help) status_usage; return 0 ;;
all|oci|rpi|opi5|debian|cluster)
case "${2:-}" in -h|--help) status_usage; return 0 ;; esac
;;
esac
require_debian_server "status"
if (($# == 0)); then
status_focused_report all
return $?
fi
case "${1:-}" in
all|oci|rpi|opi5|debian|cluster)
local focus="$1"
shift
status_focused_report "${focus}" "$@"
return $?
;;
esac
while (($# > 0)); do
case "$1" in
--fast|--deep)
if [[ -n "${requested_mode}" && "${requested_mode}" != "${1#--}" ]]; then
echo "Choose either --fast or --deep." >&2
return 2
fi
requested_mode="${1#--}"
shift
;;
--heal-plan)
heal_mode="plan"
shift
;;
--heal)
heal_mode="apply"
shift
;;
*)
status_args+=("$1")
shift
;;
esac
done
if ! report_ui_parse_args "${status_args[@]}"; then
return 1
fi
if [[ "${requested_mode}" == fast && ( -n "${heal_mode}" || "${REPORT_UI_VERBOSE}" == true ) ]]; then
echo "Healing and verbose status require deep checks; omit --fast." >&2
return 2
fi
if [[ "${requested_mode}" == deep || -n "${heal_mode}" || "${REPORT_UI_VERBOSE}" == true ]]; then
JEANNIE_STATUS_MODE=deep
fi
if [[ -z "${heal_mode}" && "${REPORT_UI_VERBOSE}" == true ]]; then
REPORT_UI_VERBOSE=false
fi
if [[ -n "${heal_mode}" ]]; then
status_json="$(mktemp "${TMPDIR:-/tmp}/jeannie-status-json.XXXXXX")"
# shellcheck disable=SC2034
REPORT_UI_JSON=true
# shellcheck disable=SC2034
REPORT_UI_ONLY=problems
report_ui_begin
local REPORT_UI_PARALLEL=true
JEANNIE_REPORT_MODE=true status_cascade_report >/dev/null || cascade_status=$?
report_ui_finish
((REPORT_UI_FAILURES == 0)) || cascade_status=1
report_ui_render "Jeannie Status" >"${status_json}"
report_ui_cleanup
local -a heal_args=("${heal_mode}" --status-json "${status_json}")
if truthy "${REPORT_UI_LOCAL_RCA:-false}"; then
heal_args+=(--ai)
fi
"${REPO_ROOT}/scripts/heal" "${heal_args[@]}"
rm -f "${status_json}"
return "${cascade_status}"
fi
if [[ "${REPORT_UI_VERBOSE}" != "true" ]]; then
report_ui_begin
local REPORT_UI_PARALLEL=true
# shellcheck disable=SC2034
local REPORT_UI_STATUS_SUMMARY=true
JEANNIE_REPORT_MODE=true status_cascade_report || cascade_status=$?
report_ui_finish
((REPORT_UI_FAILURES == 0)) || cascade_status=1
report_ui_render "Jeannie Status"
report_ui_cleanup
return "${cascade_status}"
fi
status_cascade_report || cascade_status=$?
if ! truthy "${LAB_STATUS_DETAILS:-false}" && [[ "${REPORT_UI_DETAILS}" != "true" ]]; then
return "${cascade_status}"
fi
status_section "Host"
printf 'hostname: %s\n' "$(hostname -f 2>/dev/null || hostname)"
printf 'date: %s\n' "$(date -Is)"
printf 'uptime: %s\n' "$(uptime -p 2>/dev/null || uptime)"
status_run "memory" free -h
status_run "disk" df -h / /data /data/openebs/local
status_section "Systemd"
status_systemd_units ssh docker containerd kubelet tailscaled homelab-gitea-runner
status_section "Docker"
if command -v docker >/dev/null 2>&1; then
status_run "docker containers" sudo docker ps --format 'table {{.Names}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}'
else
printf 'docker not installed\n'
fi
status_compose_stack "gitea" "/data/homelab-gitea"
status_compose_stack "heimdall" "${LAB_HEIMDALL_INSTALL_DIR:-/data/homelab-heimdall}"
status_compose_stack "dex" "${LAB_DEX_INSTALL_DIR:-/data/homelab-dex}"
status_compose_stack "arr-stack" "${REPO_ROOT}/infra/arr-stack"
status_kubernetes
status_pimox_workers
status_rpi_services
status_section "Tailscale"
if command -v tailscale >/dev/null 2>&1; then
status_run "tailscale ip" tailscale ip -4
status_run "tailscale peers" tailscale status
else
printf 'tailscale not installed\n'
fi
status_section "HTTP"
status_http "website public" "${LAB_PUBLIC_URL:?LAB_PUBLIC_URL is required from homelab.yml}/"
status_http "gitea public" "${LAB_GITEA_ROOT_URL:-${LAB_PUBLIC_URL:?LAB_PUBLIC_URL is required from homelab.yml}/git/}"
status_http "heimdall public" "${LAB_HEIMDALL_PUBLIC_URL:-https://heimdall.${LAB_DOMAIN:?LAB_DOMAIN is required from homelab.yml}/}"
status_http "dex public" "${LAB_DEX_PUBLIC_URL:-https://auth.${LAB_DOMAIN:?LAB_DOMAIN is required from homelab.yml}/}"
status_http "gitea local" "http://127.0.0.1:${LAB_GITEA_HTTP_PORT:-3000}/"
status_http "heimdall local" "http://127.0.0.1:${LAB_HEIMDALL_HTTP_PORT:-8082}/"
status_http "dex local" "http://127.0.0.1:${LAB_DEX_HTTP_PORT:-5556}/healthz"
status_http "traefik lb" "http://${LAB_TRAEFIK_LB_IP:?LAB_TRAEFIK_LB_IP is required from homelab.yml}/"
status_http "arr radarr" "http://127.0.0.1:7878/"
status_http "arr sonarr" "http://127.0.0.1:8989/"
status_http "arr prowlarr" "http://127.0.0.1:9696/"
return "${cascade_status}"
}
check_edge_traefik_backend() {
local edge_host="${LAB_EDGE_HOST:?LAB_EDGE_HOST is required from homelab.yml}"
local edge_user="${LAB_EDGE_USER:-ubuntu}"
local traefik_ip="${LAB_TRAEFIK_LB_IP:?LAB_TRAEFIK_LB_IP is required from homelab.yml}"
ssh -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new "${edge_user}@${edge_host}" \
"curl -sS -o /dev/null --connect-timeout 5 --max-time 10 -w '%{http_code}' 'http://${traefik_ip}:80/' | grep -Eq '^[234]'"
}
check_edge_gitea_backend() {
local edge_host="${LAB_EDGE_HOST:?LAB_EDGE_HOST is required from homelab.yml}"
local edge_user="${LAB_EDGE_USER:-ubuntu}"
local gitea_ts_ip="${LAB_GITEA_TAILSCALE_IP:?LAB_GITEA_TAILSCALE_IP is required from homelab.yml}"
local gitea_http_port="${LAB_GITEA_HTTP_PORT:-3000}"
ssh -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new "${edge_user}@${edge_host}" \
"curl -sS -o /dev/null --connect-timeout 5 --max-time 10 -w '%{http_code}' 'http://${gitea_ts_ip}:${gitea_http_port}/' | grep -Eq '^[234]'"
}
check_edge_heimdall_backend() {
local edge_host="${LAB_EDGE_HOST:?LAB_EDGE_HOST is required from homelab.yml}"
local edge_user="${LAB_EDGE_USER:-ubuntu}"
local heimdall_host="${LAB_HEIMDALL_BACKEND_HOST:-${LAB_GITEA_TAILSCALE_IP:?LAB_GITEA_TAILSCALE_IP is required from homelab.yml}}"
local heimdall_http_port="${LAB_HEIMDALL_HTTP_PORT:-8082}"
ssh -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new "${edge_user}@${edge_host}" \
"curl -sS -o /dev/null --connect-timeout 5 --max-time 10 -w '%{http_code}' 'http://${heimdall_host}:${heimdall_http_port}/' | grep -Eq '^[234]'"
}
check_gitea_git_remote() {
git ls-remote gitea main >/dev/null
}
check_gitea_ssh() {
local gitea_host="${LAB_GITEA_HOST:-192.168.100.73}"
local gitea_ssh_port="${LAB_GITEA_SSH_PORT:-32222}"
ssh -T -p "${gitea_ssh_port}" -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new "git@${gitea_host}" 2>&1 |
grep -Eiq 'successfully authenticated|Hi |shell access is disabled'
}
doctor_edge() {
local edge_host="${LAB_EDGE_HOST:?LAB_EDGE_HOST is required from homelab.yml}"
local edge_user="${LAB_EDGE_USER:-ubuntu}"
local traefik_ip="${LAB_TRAEFIK_LB_IP:?LAB_TRAEFIK_LB_IP is required from homelab.yml}"
local gitea_ts_ip="${LAB_GITEA_TAILSCALE_IP:?LAB_GITEA_TAILSCALE_IP is required from homelab.yml}"
local gitea_http_port="${LAB_GITEA_HTTP_PORT:-3000}"
local heimdall_host="${LAB_HEIMDALL_BACKEND_HOST:-${gitea_ts_ip}}"
local heimdall_http_port="${LAB_HEIMDALL_HTTP_PORT:-8082}"
local failures=0
require_debian_server "doctor-edge"
if ! report_ui_parse_args "$@"; then
return 1
fi
if [[ "${REPORT_UI_VERBOSE}" != "true" ]]; then
report_ui_begin
report_ui_check fail "Public URLs" "Website public" "./jeannie doctor-edge --verbose" "" "" status_http_ok "${LAB_PUBLIC_URL:?LAB_PUBLIC_URL is required from homelab.yml}/" || failures=$((failures + 1))
report_ui_check fail "Public URLs" "Gitea public" "./jeannie doctor-gitea" "" "" status_gitea_public_ok || failures=$((failures + 1))
report_ui_check fail "Edge" "OCI edge SSH" "./jeannie preflight" "" "" check_edge_ssh || failures=$((failures + 1))
report_ui_check fail "Backends" "Traefik from edge" "./jeannie doctor-cluster" "" "" check_edge_traefik_backend || failures=$((failures + 1))
report_ui_check fail "Backends" "Gitea from edge" "./jeannie doctor-gitea" "" "" check_edge_gitea_backend || failures=$((failures + 1))
report_ui_check fail "Backends" "Heimdall from edge" "./jeannie deploy-heimdall" "" "" check_edge_heimdall_backend || failures=$((failures + 1))
report_ui_render "Doctor Edge"
report_ui_cleanup
return "${failures}"
fi
status_section "Doctor Edge"
status_http "website public" "${LAB_PUBLIC_URL:?LAB_PUBLIC_URL is required from homelab.yml}/"
status_http "gitea public" "${LAB_GITEA_ROOT_URL:-${LAB_PUBLIC_URL:?LAB_PUBLIC_URL is required from homelab.yml}/git/}"
status_http "heimdall public" "${LAB_HEIMDALL_PUBLIC_URL:-https://heimdall.${LAB_DOMAIN:?LAB_DOMAIN is required from homelab.yml}/}"
printf '\n-- edge backend reachability\n'
if ! ssh -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new "${edge_user}@${edge_host}" "
set +e
printf '%-28s ' 'traefik backend'
curl -sS -o /dev/null --connect-timeout 5 --max-time 10 -w '%{http_code}\n' 'http://${traefik_ip}:80/' || echo unreachable
printf '%-28s ' 'gitea backend'
curl -sS -o /dev/null --connect-timeout 5 --max-time 10 -w '%{http_code}\n' 'http://${gitea_ts_ip}:${gitea_http_port}/' || echo unreachable
printf '%-28s ' 'heimdall backend'
curl -sS -o /dev/null --connect-timeout 5 --max-time 10 -w '%{http_code}\n' 'http://${heimdall_host}:${heimdall_http_port}/' || echo unreachable
printf '\n-- tailscale\n'
tailscale status || true
"; then
printf 'unable to reach edge host %s@%s\n' "${edge_user}" "${edge_host}"
fi
cat <<'EOF'
Next steps:
- If only Traefik is unreachable, check cluster/MetalLB or run ./jeannie doctor-cluster.
- If only Gitea is unreachable, run ./jeannie doctor-gitea.
- If only Heimdall is unreachable, run ./jeannie deploy-heimdall.
- If both are unreachable from OCI, check Tailscale routes and bootstrap/edge.
- Runbook: docs/runbooks/edge-failures.md
EOF
backstage_brain_note "doctor-edge" <<EOF
Doctor command: doctor-edge
Public domain: ${LAB_PUBLIC_URL:?LAB_PUBLIC_URL is required from homelab.yml}/
Public Gitea URL: ${LAB_GITEA_ROOT_URL:-${LAB_PUBLIC_URL:?LAB_PUBLIC_URL is required from homelab.yml}/git/}
OCI edge SSH target: ${edge_user}@${edge_host}
Traefik backend from edge: http://${traefik_ip}:80/
Gitea backend from edge: http://${gitea_ts_ip}:${gitea_http_port}/
Known runbook: docs/runbooks/edge-failures.md
EOF
}
doctor_gitea() {
local edge_host="${LAB_EDGE_HOST:?LAB_EDGE_HOST is required from homelab.yml}"
local edge_user="${LAB_EDGE_USER:-ubuntu}"
local gitea_ts_ip="${LAB_GITEA_TAILSCALE_IP:?LAB_GITEA_TAILSCALE_IP is required from homelab.yml}"
local gitea_host="${LAB_GITEA_HOST:-192.168.100.73}"
local gitea_http_port="${LAB_GITEA_HTTP_PORT:-3000}"
local gitea_ssh_port="${LAB_GITEA_SSH_PORT:-32222}"
local failures=0
require_debian_server "doctor-gitea"
if ! report_ui_parse_args "$@"; then
return 1
fi
if [[ "${REPORT_UI_VERBOSE}" != "true" ]]; then
report_ui_begin
report_ui_check fail "Local Gitea" "Container running" "./jeannie deploy-gitea" "" "" status_container_running "${GITEA_CONTAINER_NAME:-homelab-gitea}" || failures=$((failures + 1))
report_ui_check fail "Local Gitea" "Local HTTP" "./jeannie deploy-gitea" "" "" status_http_ok "http://127.0.0.1:${gitea_http_port}/" || failures=$((failures + 1))
report_ui_check fail "Public Gitea" "Public route" "./jeannie doctor-edge" "" "" status_gitea_public_ok || failures=$((failures + 1))
report_ui_check warn "Git" "Gitea remote" "git remote -v" "" "" check_gitea_git_remote
report_ui_check warn "Git" "Gitea SSH" "Check Gitea SSH key and remote URL." "" "" check_gitea_ssh
report_ui_check fail "Edge" "Edge backend reachability" "./jeannie doctor-edge" "" "" check_edge_gitea_backend || failures=$((failures + 1))
report_ui_render "Doctor Gitea"
report_ui_cleanup
return "${failures}"
fi
status_section "Doctor Gitea"
status_http "gitea local" "http://127.0.0.1:${gitea_http_port}/"
status_http "gitea public" "${LAB_GITEA_ROOT_URL:-${LAB_PUBLIC_URL:?LAB_PUBLIC_URL is required from homelab.yml}/git/}"
status_compose_stack "gitea" "/data/homelab-gitea"
status_run "gitea git remote" git ls-remote gitea main
printf '\n-- gitea SSH\n'
ssh -T -p "${gitea_ssh_port}" -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new "git@${gitea_host}" || true
printf '\n-- edge to gitea backend\n'
if ! ssh -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new "${edge_user}@${edge_host}" \
"curl -I --max-time 5 'http://${gitea_ts_ip}:${gitea_http_port}/'"; then
printf 'edge host cannot reach Gitea backend %s:%s\n' "${gitea_ts_ip}" "${gitea_http_port}"
fi
cat <<'EOF'
Next steps:
- If local Gitea is down, run ./jeannie deploy-gitea.
- If local works but public /git/ fails, check Tailscale and bootstrap/edge.
- If Git SSH fails, check the gitea remote and registered SSH key.
- Runbook: docs/runbooks/gitea-failures.md
EOF
backstage_brain_note "doctor-gitea" <<EOF
Doctor command: doctor-gitea
Gitea local URL: http://127.0.0.1:${gitea_http_port}/
Gitea LAN host: ${gitea_host}
Gitea Tailscale backend: http://${gitea_ts_ip}:${gitea_http_port}/
Gitea SSH port: ${gitea_ssh_port}
Gitea public URL: ${LAB_GITEA_ROOT_URL:-${LAB_PUBLIC_URL:?LAB_PUBLIC_URL is required from homelab.yml}/git/}
Known runbook: docs/runbooks/gitea-failures.md
EOF
}
doctor_rpi() {
local failures=0
require_debian_server "doctor-rpi"
if ! report_ui_parse_args "$@"; then
return 1
fi
if [[ "${REPORT_UI_VERBOSE}" != "true" ]]; then
report_ui_begin
report_ui_check fail "RPi" "SSH" "./jeannie rpi-services" "" "" check_rpi_ssh || failures=$((failures + 1))
report_ui_check fail "RPi" "Docker root state" "./jeannie rpi-services" "" "" check_rpi_docker_root_state || failures=$((failures + 1))
report_ui_check fail "DNS" "Pi-hole DNS" "./jeannie rpi-services" "" "" check_pihole_dns_query || failures=$((failures + 1))
report_ui_check warn "DNS" "RPi Tailscale IP" "Check tailscaled on RPi." "" "" check_rpi_tailscale_ip
report_ui_check warn "Services" "Uptime Kuma HTTP" "./jeannie rpi-services" "" "" status_rpi_uptime_kuma_ok
report_ui_render "Doctor RPi"
report_ui_cleanup
return "${failures}"
fi
status_rpi_services
cat <<'EOF'
Next steps:
- Docker root should be /nvme-storage/docker; if it is /var/lib/docker, the NVMe mount is unavailable or failed the writable check.
- If Pi-hole works but Unbound fails, DNS should still resolve through configured public fallbacks.
- If Pi-hole DNS fails, clients using the RPi as DNS will be affected.
- Reapply the stack with ./jeannie rpi-services.
EOF
backstage_brain_note "doctor-rpi" <<EOF
Doctor command: doctor-rpi
RPi LAN host: ${LAB_RPI_HOST:-${LAB_RASPBERRY_HOST:-192.168.100.89}}
RPi Tailscale IP: ${LAB_RPI_TAILSCALE_IP:-unknown}
Docker root: ${LAB_RPI_DOCKER_ROOT:-${LAB_RPI_DOCKER_NVME_ROOT:-/nvme-storage/docker}}
Docker fallback root: ${LAB_RPI_DOCKER_FALLBACK_ROOT:-/var/lib/docker}
Services: Pi-hole, Unbound, Uptime Kuma
EOF
}
doctor_cluster() {
local failures=0
require_debian_server "doctor-cluster"
if ! report_ui_parse_args "$@"; then
return 1
fi
if [[ "${REPORT_UI_VERBOSE}" != "true" ]]; then
report_ui_begin
report_ui_check fail "Cluster Runtime" "Control-plane runtime" "./jeannie start-cluster" "" "" status_cluster_control_runtime || failures=$((failures + 1))
report_ui_check fail "Cluster Runtime" "Cluster storage" "./jeannie workers disk-status control-plane" "" "" status_cluster_storage || failures=$((failures + 1))
report_ui_check fail "Cluster Runtime" "Inactive profiles stopped" "./jeannie cluster-runtime check" "" "" cluster_runtime_require || failures=$((failures + 1))
report_ui_check warn "Host Runtime" "docker" "sudo systemctl restart docker" "" "" check_systemd_active docker
report_ui_check fail "Kubernetes" "API" "./jeannie start-cluster" "" "" status_kubernetes_api_ok || failures=$((failures + 1))
report_ui_check fail "Kubernetes" "Cluster identity" "./jeannie cluster-context check" "" "" cluster_context_require || failures=$((failures + 1))
report_ui_check fail "Kubernetes" "Nodes Ready" "kubectl get nodes -o wide" "" "" status_kubernetes_nodes_ready || failures=$((failures + 1))
report_ui_check warn "Kubernetes" "Problem pods" "kubectl get pods -A -o wide" "" "" status_no_problem_pods
if [[ "${LAB_CLUSTER_RUNTIME}" != k3s ]]; then
report_ui_check fail "Pimox" "Workers running" "./jeannie start-cluster" "" "" status_pimox_workers_running || failures=$((failures + 1))
report_ui_check fail "Pimox" "Worker tailnet egress" "./jeannie workers tailnet" "" "" check_pimox_worker_tailnet_egress || failures=$((failures + 1))
fi
report_ui_check fail "Networking" "Traefik LoadBalancer" "./jeannie doctor-edge" "" "" status_http_reachable "http://${LAB_TRAEFIK_LB_IP:?LAB_TRAEFIK_LB_IP is required from homelab.yml}/" || failures=$((failures + 1))
report_ui_render "Doctor Cluster"
report_ui_cleanup
return "${failures}"
fi
status_section "Doctor Cluster"
status_run "selected control-plane runtime" status_cluster_control_runtime
status_run "selected cluster storage" status_cluster_storage
status_kubernetes
status_pimox_workers
if [[ "${LAB_CLUSTER_RUNTIME}" != k3s ]]; then
status_run "pimox worker tailnet egress" check_pimox_worker_tailnet_egress
else
python3 "${REPO_ROOT}/scripts/k3s-node-diagnostics.py" status || failures=$((failures + 1))
fi
status_http "traefik lb" "http://${LAB_TRAEFIK_LB_IP:?LAB_TRAEFIK_LB_IP is required from homelab.yml}/"
if [[ "${LAB_CLUSTER_RUNTIME}" != k3s ]]; then
status_run "selected control-plane CRI" ssh -n -i "${LAB_CLUSTER_CONTROL_PLANE_SSH_KEY_PATH}" \
-o BatchMode=yes -o ConnectTimeout=8 -o StrictHostKeyChecking=accept-new \
"${LAB_CLUSTER_CONTROL_PLANE_USER}@${LAB_CLUSTER_CONTROL_PLANE_LAN_IP}" \
'sudo -n crictl ps -a | head -15'
fi
cat <<'EOF'
Next steps:
- If API server is unreachable after a stop, run ./jeannie start-cluster.
- If the API is reachable but pods/nodes are unhealthy, run Holmes for read-only Kubernetes triage before changing workloads.
- If nodes are NotReady, inspect kube-system pods and containerd/kubelet on that node.
- If Pimox workers are stopped, start them with ./jeannie start-cluster.
- If kubelet versions drift, run ./jeannie doctor-versions.
- Runbook: docs/runbooks/cluster-stop-start-failures.md
EOF
backstage_brain_note "doctor-cluster" <<EOF
Doctor command: doctor-cluster
Kubeconfig path: ${KUBECONFIG_PATH}
Traefik LoadBalancer IP: ${LAB_TRAEFIK_LB_IP:?LAB_TRAEFIK_LB_IP is required from homelab.yml}
Pimox host: ${LAB_PIMOX_USER:-${TF_VAR_pimox_user:-jv}}@${LAB_PIMOX_HOST:-${TF_VAR_pimox_host:-192.168.100.80}}
Worker storage: ${LAB_PIMOX_WORKER_STORAGE:-${TF_VAR_pimox_worker_storage:-opi5_ssd}}
Pimox worker tailnet probe: ${LAB_PIMOX_WORKER_TAILNET_PROBE_HOST:-${LAB_DEBIAN_TAILSCALE_IP:-unset}}:${LAB_PIMOX_WORKER_TAILNET_PROBE_PORT:-${LAB_GITEA_HTTP_PORT:-3000}}
Known runbook: docs/runbooks/cluster-stop-start-failures.md
EOF
}
doctor_k8s() {
local run_holmes=true
local output_json=false
local artifact_base="${LAB_DOCTOR_K8S_ARTIFACT_DIR:-${HOMELAB_STATE_DIR:-${HOME}/.local/share/homelab}/doctor-k8s}"
local tools_env_file="${LAB_AI_STACK_TOOLS_ENV_FILE:-/data/homelab-ai-stack/ai-tools.env}"
local timestamp
local artifact_dir
local kubeconfig="${KUBECONFIG_PATH}"
local failures=0
local api_status=0
local nodes_status=0 pods_status=0 events_status=0
local node_not_ready_count=0
local problem_pods_count=0
local holmes_status=0
local holmes_bin=""
local holmes_timeout="${LAB_HOLMES_TRIAGE_TIMEOUT_SECONDS:-360}"
local prompt_file
local holmes_stdout
local holmes_raw
local holmes_stderr
local holmes_config="${LAB_HOLMES_CONFIG_FILE:-/data/homelab-ai-stack/holmes-config.yaml}"
local holmes_api_key="${LAB_AI_GATEWAY_API_KEY:-${OPENAI_API_KEY:-sk_omniroute}}"
local holmes_model="${LAB_HOLMES_MODEL:-${AI_STACK_AGENT_SMART_MODEL:-${AI_STACK_AGENT_FAST_MODEL:-agent-smart-free}}}"
local holmes_fast_model="${LAB_HOLMES_FAST_MODEL:-${AI_STACK_AGENT_FAST_MODEL:-agent-fast-free}}"
local holmes_max_steps="${LAB_HOLMES_MAX_STEPS:-12}"
local arg
require_debian_server "doctor-k8s"
while (($# > 0)); do
arg="$1"
case "${arg}" in
--no-holmes)
run_holmes=false
shift
;;
--holmes)
run_holmes=true
shift
;;
--json)
output_json=true
shift
;;
-h|--help)
cat <<'EOF'
Usage: ./jeannie doctor-k8s [--no-holmes] [--json]
Runs read-only Kubernetes checks, optionally asks Holmes for read-only triage,
and writes artifacts under ~/.local/share/homelab/doctor-k8s.
EOF
return 0
;;
*)
echo "Unknown doctor-k8s option: ${arg}" >&2
return 2
;;
esac
done
timestamp="$(date -u +%Y%m%dT%H%M%SZ)"
(umask 077; mkdir -p "${artifact_base}")
artifact_dir="$(mktemp -d "${artifact_base}/${timestamp}.XXXXXX")"
prompt_file="${artifact_dir}/holmes-prompt.txt"
holmes_stdout="${artifact_dir}/holmes-output.txt"
holmes_raw="${artifact_dir}/holmes-raw-output.txt"
holmes_stderr="${artifact_dir}/holmes-error.txt"
if [[ -r "${tools_env_file}" && -s "${tools_env_file}" ]]; then
# shellcheck disable=SC1090
. "${tools_env_file}"
holmes_api_key="${OPENAI_API_KEY:-${LAB_AI_GATEWAY_API_KEY:-${holmes_api_key}}}"
holmes_model="${LAB_HOLMES_MODEL:-${AI_STACK_AGENT_SMART_MODEL:-${AI_STACK_AGENT_FAST_MODEL:-${holmes_model}}}}"
holmes_fast_model="${LAB_HOLMES_FAST_MODEL:-${AI_STACK_AGENT_FAST_MODEL:-${holmes_fast_model}}}"
fi
if [[ "${holmes_model}" != */* ]]; then
holmes_model="openai/${holmes_model}"
fi
if [[ "${holmes_fast_model}" != */* ]]; then
holmes_fast_model="openai/${holmes_fast_model}"
fi
if [[ ! -r "${holmes_config}" ]]; then
printf '{}\n' >"${artifact_dir}/holmes-empty-config.yaml"
holmes_config="${artifact_dir}/holmes-empty-config.yaml"
fi
{
printf 'command=doctor-k8s\n'
printf 'timestamp=%s\n' "${timestamp}"
printf 'kubeconfig=%s\n' "${kubeconfig}"
printf 'cluster_profile=%s\n' "${LAB_CLUSTER_PROFILE:-debian}"
printf 'holmes_config=%s\n' "${holmes_config}"
printf 'holmes_model=%s\n' "${holmes_model}"
printf 'holmes_fast_model=%s\n' "${holmes_fast_model}"
} >"${artifact_dir}/metadata.env"
if [[ ! -s "${kubeconfig}" ]]; then
printf 'missing kubeconfig: %s\n' "${kubeconfig}" >"${artifact_dir}/api-readyz.txt"
printf 'missing kubeconfig: %s\n' "${kubeconfig}" >"${artifact_dir}/api-readyz.err"
api_status=1
failures=$((failures + 1))
elif ! kubectl --kubeconfig "${kubeconfig}" --request-timeout=15s get --raw=/readyz >"${artifact_dir}/api-readyz.txt" 2>"${artifact_dir}/api-readyz.err"; then
api_status=1
failures=$((failures + 1))
fi
kubectl --kubeconfig "${kubeconfig}" config current-context >"${artifact_dir}/context.txt" 2>&1 || true
kubectl --kubeconfig "${kubeconfig}" --request-timeout=15s get nodes -o wide >"${artifact_dir}/nodes.txt" 2>&1 || nodes_status=$?
kubectl --kubeconfig "${kubeconfig}" --request-timeout=15s get pods -A -o wide >"${artifact_dir}/pods.txt" 2>&1 || pods_status=$?
kubectl --kubeconfig "${kubeconfig}" --request-timeout=15s get events -A --sort-by=.lastTimestamp >"${artifact_dir}/events.txt" 2>&1 || events_status=$?
kubectl --kubeconfig "${kubeconfig}" --request-timeout=15s get pvc -A -o wide >"${artifact_dir}/pvcs.txt" 2>&1 || true
kubectl --kubeconfig "${kubeconfig}" --request-timeout=15s get ingress -A -o wide >"${artifact_dir}/ingress.txt" 2>&1 || true
if ((pods_status == 0)); then
awk 'NR == 1 || ($4 != "Running" && $4 != "Completed" && $4 != "Succeeded")' "${artifact_dir}/pods.txt" >"${artifact_dir}/problem-pods.txt"
problem_pods_count="$(awk 'NR > 1 {count++} END {print count + 0}' "${artifact_dir}/problem-pods.txt")"
else
problem_pods_count=-1
printf 'Pod collection failed; state unknown.\n' >"${artifact_dir}/problem-pods.txt"
failures=$((failures + 1))
fi
if ((nodes_status == 0)) && ! awk 'NR > 1 && NF {found=1} END {exit !found}' "${artifact_dir}/nodes.txt"; then
printf '\nNo Kubernetes nodes found; node health is unknown.\n' >>"${artifact_dir}/nodes.txt"
nodes_status=1
fi
if ((nodes_status == 0)); then
node_not_ready_count="$(awk 'NR > 1 && $2 !~ /^Ready(,|$)/ {count++} END {print count + 0}' "${artifact_dir}/nodes.txt")"
else
node_not_ready_count=-1
failures=$((failures + 1))
fi
if ((problem_pods_count > 0 || node_not_ready_count > 0)); then
failures=$((failures + 1))
fi
: >"${artifact_dir}/problem-pod-details.txt"
if ((pods_status == 0)); then
awk 'NR > 1 {print $1, $2}' "${artifact_dir}/problem-pods.txt" |
while read -r pod_namespace pod_name; do
[[ -n "${pod_namespace}" && -n "${pod_name}" ]] || continue
{
printf -- '---- %s/%s ----\n' "${pod_namespace}" "${pod_name}"
kubectl --kubeconfig "${kubeconfig}" --request-timeout=10s -n "${pod_namespace}" describe pod "${pod_name}" 2>&1 |
sed -n '/Events:/,$p' |
tail -n 35 || true
printf '\n'
} >>"${artifact_dir}/problem-pod-details.txt"
done
fi
python3 "${REPO_ROOT}/scripts/holmes-evidence.py" prepare "${artifact_dir}" \
--api "${api_status}" --nodes "${nodes_status}" --pods "${pods_status}" --events "${events_status}" || return 1
if [[ "${run_holmes}" == "true" ]]; then
if command -v jeannie-holmes >/dev/null 2>&1; then
holmes_bin="$(command -v jeannie-holmes)"
elif command -v holmes >/dev/null 2>&1; then
holmes_bin="$(command -v holmes)"
fi
if [[ -n "${LAB_HOLMES_TRIAGE_COMMAND:-}" ]]; then
set +e
timeout "${holmes_timeout}" env KUBECONFIG="${kubeconfig}" bash -lc "${LAB_HOLMES_TRIAGE_COMMAND}" <"${prompt_file}" >"${holmes_raw}" 2>"${holmes_stderr}"
holmes_status=$?
set -e
elif [[ -n "${holmes_bin}" ]]; then
set +e
timeout "${holmes_timeout}" env KUBECONFIG="${kubeconfig}" OPENAI_BASE_URL="${OPENAI_BASE_URL:-http://127.0.0.1:20128/v1}" OPENAI_API_BASE="${OPENAI_API_BASE:-${OPENAI_BASE_URL:-http://127.0.0.1:20128/v1}}" OPENAI_API_KEY="${holmes_api_key}" \
"${holmes_bin}" ask \
--config "${holmes_config}" \
--prompt-file "${prompt_file}" \
--api-key "${holmes_api_key}" \
--model "${holmes_model}" \
--fast-model "${holmes_fast_model}" \
--max-steps "${holmes_max_steps}" \
--fast-mode \
--no-interactive \
--bash-always-deny \
>"${holmes_raw}" 2>"${holmes_stderr}"
holmes_status=$?
set -e
else
holmes_status=127
printf 'holmes is not installed; run ./jeannie deploy-ai-tools\n' >"${holmes_stderr}"
fi
else
holmes_status=0
printf 'Holmes triage skipped by --no-holmes.\n' >"${holmes_stdout}"
fi
if [[ "${run_holmes}" == "true" && "${holmes_status}" == "0" ]] &&
sed -n '1,160p' "${holmes_stderr}" 2>/dev/null |
grep -Eiq 'validation error|invalid config|extra inputs are not permitted|traceback|exception|error:'; then
holmes_status=1
fi
if [[ "${run_holmes}" == "true" ]]; then
if [[ "${holmes_status}" == "0" ]]; then
if ! python3 "${REPO_ROOT}/scripts/holmes-evidence.py" validate \
"${artifact_dir}/holmes-evidence.json" "${holmes_raw}" >"${holmes_stdout}"; then
holmes_status=1
fi
else
printf 'Holmes failed or timed out; deterministic evidence is available.\n' >"${holmes_stdout}"
fi
fi
cat >"${artifact_dir}/triage.md" <<EOF
# Jeannie Kubernetes Doctor
- Artifact directory: ${artifact_dir}
- Kubeconfig: ${kubeconfig}
- API readyz status: ${api_status}
- NotReady node count: ${node_not_ready_count}
- Problem pod count: ${problem_pods_count}
- Holmes status: ${holmes_status}
## Holmes read-only triage
$(sed -n '1,160p' "${holmes_stdout}" 2>/dev/null || true)
$([[ "${holmes_status}" == "124" ]] && printf 'Holmes timed out after %s seconds. The deterministic Kubernetes artifact above is still valid.\n' "${holmes_timeout}" || true)
## Diagnostics
Raw model output and stderr are stored in the private artifact directory for review.
EOF
python3 - "${artifact_dir}/summary.json" "${artifact_dir}" "${kubeconfig}" "${api_status}" "${node_not_ready_count}" "${problem_pods_count}" "${holmes_status}" "${run_holmes}" "${nodes_status}" "${pods_status}" "${events_status}" <<'PY'
import json
import os
import sys
summary_file, artifact_dir, kubeconfig, api_status, node_count, pod_count, holmes_status, run_holmes, nodes_status, pods_status, events_status = sys.argv[1:12]
summary = {
"artifact_dir": artifact_dir,
"kubeconfig": kubeconfig,
"cluster": {"profile": os.environ.get("LAB_CLUSTER_PROFILE"), "runtime": os.environ.get("LAB_CLUSTER_RUNTIME"),
"node": os.environ.get("LAB_CLUSTER_CONTROL_PLANE_NODE_NAME")},
"api_status": int(api_status),
"collection_status": {"nodes": int(nodes_status), "pods": int(pods_status), "events": int(events_status)},
"node_not_ready_count": int(node_count),
"problem_pods_count": int(pod_count),
"holmes_enabled": run_holmes == "true",
"holmes_status": int(holmes_status),
"files": {
"triage": f"{artifact_dir}/triage.md",
"nodes": f"{artifact_dir}/nodes.txt",
"problem_pods": f"{artifact_dir}/problem-pods.txt",
"events": f"{artifact_dir}/events.txt",
"holmes_output": f"{artifact_dir}/holmes-output.txt",
"holmes_evidence": f"{artifact_dir}/holmes-evidence.json",
"holmes_error": f"{artifact_dir}/holmes-error.txt",
},
}
with open(summary_file, "w", encoding="utf-8") as handle:
json.dump(summary, handle, indent=2)
handle.write("\n")
PY
if [[ "${output_json}" == "true" ]]; then
cat "${artifact_dir}/summary.json"
else
status_section "Doctor K8s"
printf '%-28s %s\n' "artifact dir" "${artifact_dir}"
printf '%-28s %s\n' "api readyz" "$([[ "${api_status}" == "0" ]] && printf ok || printf failed)"
printf '%-28s %s\n' "not ready nodes" "${node_not_ready_count}"
printf '%-28s %s\n' "problem pods" "${problem_pods_count}"
printf '%-28s %s\n' "holmes status" "${holmes_status}"
printf '%-28s %s\n' "triage" "${artifact_dir}/triage.md"
if ((problem_pods_count > 0)); then
printf '\n-- problem pods\n'
sed -n '1,20p' "${artifact_dir}/problem-pods.txt"
fi
printf '\nNext steps:\n'
printf '%s\n' "- Review ${artifact_dir}/triage.md"
printf '%s\n' "- Keep remediation deterministic: use Jeannie heal/runbook commands only after reviewing the artifact."
fi
return "${failures}"
}
doctor_homelab() {
local failures=0
if ! report_ui_parse_args "$@"; then
return 1
fi
require_debian_server "doctor-homelab"
if [[ "${REPORT_UI_VERBOSE}" != "true" ]]; then
report_ui_begin
local REPORT_UI_PARALLEL=true
report_ui_check fail "Architecture Boundary" "Selected cluster identity" "./jeannie cluster-context check" "" "" cluster_context_require || failures=$((failures + 1))
report_ui_check fail "Architecture Boundary" "External services host resolved" "./jeannie cluster-profile" "" "" status_external_services_host_declared || failures=$((failures + 1))
report_ui_check fail "Cluster Runtime" "Cluster storage" "./jeannie doctor-cluster" "" "" status_cluster_storage || failures=$((failures + 1))
report_ui_check fail "Cluster Runtime" "Control-plane runtime" "./jeannie start-cluster" "" "" status_cluster_control_runtime || failures=$((failures + 1))
report_ui_check fail "Cluster Runtime" "Inactive profiles stopped" "./jeannie cluster-runtime check" "" "" cluster_runtime_require || failures=$((failures + 1))
if [[ "${LAB_CLUSTER_PROFILE}" == pimox ]]; then
report_ui_check fail "Pimox Runtime" "Control-plane VM running" "./jeannie start-cluster" "" "" status_pimox_control_plane_running || failures=$((failures + 1))
fi
if [[ "${LAB_CLUSTER_RUNTIME}" != k3s ]]; then
report_ui_check fail "Pimox Runtime" "Worker VMs running" "./jeannie start-cluster" "" "" status_pimox_workers_running || failures=$((failures + 1))
fi
report_ui_check fail "Kubernetes" "API ready" "./jeannie start-cluster" "" "" status_kubernetes_api_ok || failures=$((failures + 1))
report_ui_check fail "Kubernetes" "Nodes Ready" "kubectl get nodes -o wide" "" "" status_kubernetes_nodes_ready || failures=$((failures + 1))
report_ui_check fail "Kubernetes" "No problem pods" "kubectl get pods -A -o wide" "" "" status_no_problem_pods || failures=$((failures + 1))
report_ui_check warn "Kubernetes" "Recent deployments healthy" "kubectl get deployments -A" "" "" status_recent_deployments
report_ui_check warn "Kubernetes" "Node pressure" "kubectl describe nodes" "" "" status_node_pressure
report_ui_check fail "Platform" "Traefik deployment" "./jeannie platform" "" "" status_kubernetes_deployment_ready traefik traefik || failures=$((failures + 1))
report_ui_check fail "Platform" "Traefik LoadBalancer HTTP" "./jeannie edge apply" "" "" status_http_reachable "http://${LAB_TRAEFIK_LB_IP:?LAB_TRAEFIK_LB_IP is required from homelab.yml}/" || failures=$((failures + 1))
report_ui_check fail "Platform" "Argo CD server" "./jeannie platform" "" "" status_kubernetes_deployment_ready argocd argocd-server || failures=$((failures + 1))
report_ui_check fail "Platform" "Grafana StatefulSet" "./jeannie platform" "" "" status_kubernetes_statefulset_ready monitoring prometheus-stack-grafana || failures=$((failures + 1))
report_ui_check fail "Applications" "Website deployment" "./jeannie apps" "" "" status_kubernetes_deployment_ready website-production php-website-deployment || failures=$((failures + 1))
report_ui_check fail "Applications" "Demos deployment" "./jeannie apps" "" "" status_kubernetes_deployment_ready demos-static demos-static || failures=$((failures + 1))
report_ui_check fail "Applications" "Website image not bootstrap" "./jeannie apps" "" "" status_kubernetes_deployment_image_not_bootstrap website-production php-website-deployment php-app || failures=$((failures + 1))
report_ui_check fail "Applications" "Demos image not bootstrap" "./jeannie apps" "" "" status_kubernetes_deployment_image_not_bootstrap demos-static demos-static demos-static || failures=$((failures + 1))
report_ui_check fail "Applications" "n8n deployment" "./jeannie apps" "" "" status_kubernetes_deployment_ready n8n n8n || failures=$((failures + 1))
report_ui_check fail "Registry" "Registry HTTP" "./jeannie apps" "" "" status_registry_ok || failures=$((failures + 1))
report_ui_check fail "Registry" "Registry reachable from cluster nodes" "./jeannie apps" "" "" status_registry_from_cluster_nodes || failures=$((failures + 1))
report_ui_check fail "Debian Services" "Docker service" "sudo systemctl restart docker" "" "" check_systemd_active docker || failures=$((failures + 1))
report_ui_check fail "Debian Services" "Gitea container" "./jeannie deploy-gitea" "" "" status_container_running "${GITEA_CONTAINER_NAME:-homelab-gitea}" || failures=$((failures + 1))
report_ui_check fail "Debian Services" "Gitea local HTTP" "./jeannie deploy-gitea" "" "" status_http_ok "http://127.0.0.1:${LAB_GITEA_HTTP_PORT:-3000}/" || failures=$((failures + 1))
report_ui_check fail "Debian Services" "Dex local HTTP" "./jeannie deploy-dex" "" "" status_dex_local_ok || failures=$((failures + 1))
report_ui_check warn "Debian Services" "Ollama API" "./jeannie ollama-setup" "" "" status_ollama_local_ok
report_ui_check warn "Debian Services" "Gitea runner service" "./jeannie install-gitea-runner" "" "" check_systemd_active homelab-gitea-runner
report_ui_check warn "RPi DNS" "Pi-hole DNS" "./jeannie rpi-services" "" "" check_pihole_dns_query
report_ui_check warn "RPi DNS" "Uptime Kuma HTTP" "./jeannie rpi-services" "" "" status_rpi_uptime_kuma_ok
report_ui_check fail "Edge/Public" "OCI edge SSH" "./jeannie edge apply" "" "" check_edge_ssh || failures=$((failures + 1))
report_ui_check fail "Edge/Public" "Edge to Traefik backend" "./jeannie edge apply" "" "" check_edge_traefik_backend || failures=$((failures + 1))
report_ui_check fail "Edge/Public" "Website public URL" "./jeannie doctor-edge" "" "" status_http_ok "${LAB_PUBLIC_URL:?LAB_PUBLIC_URL is required from homelab.yml}/" || failures=$((failures + 1))
report_ui_check fail "Edge/Public" "Gitea public URL" "./jeannie doctor-gitea" "" "" status_gitea_public_ok || failures=$((failures + 1))
report_ui_check fail "Edge/Public" "Grafana public URL" "./jeannie platform" "" "" status_http_ok "https://grafana.${LAB_DOMAIN:?LAB_DOMAIN is required from homelab.yml}/login" || failures=$((failures + 1))
report_ui_check fail "Edge/Public" "Argo CD public URL" "./jeannie platform" "" "" status_http_reachable "https://argocd.${LAB_DOMAIN:?LAB_DOMAIN is required from homelab.yml}/" || failures=$((failures + 1))
report_ui_check fail "Edge/Public" "Demos public URL" "./jeannie apps" "" "" status_http_ok "https://demos.${LAB_DOMAIN:?LAB_DOMAIN is required from homelab.yml}/" || failures=$((failures + 1))
report_ui_check fail "Edge/Public" "Dex public URL" "./jeannie deploy-dex" "" "" status_http_reachable "${LAB_DEX_PUBLIC_URL:-https://auth.${LAB_DOMAIN:?LAB_DOMAIN is required from homelab.yml}/}" || failures=$((failures + 1))
report_ui_check warn "Operations" "Backup freshness" "./jeannie backup" "" "" backup_status
report_ui_check warn "Operations" "Disk usage" "df -h / /data" "" "" status_disk_pressure
report_ui_check warn "Operations" "Pod restart pressure" "kubectl get pods -A" "" "" status_pod_restart_pressure
report_ui_check warn "Operations" "Traefik 5xx/404 signals" "kubectl -n traefik logs -l app.kubernetes.io/name=traefik --since=5m" "" "" status_traefik_error_rates
report_ui_finish
failures=$((failures + REPORT_UI_FAILURES))
report_ui_render "Post-Migration Homelab Doctor"
report_ui_cleanup
return "${failures}"
fi
status_section "Post-Migration Homelab Doctor"
cluster_profile_report
status_section "Selected Cluster: ${LAB_CLUSTER_PROFILE}"
status_run "cluster storage" status_cluster_storage
status_run "control-plane runtime" status_cluster_control_runtime
status_pimox_workers
status_kubernetes
status_section "Platform And Apps"
status_run "registry HTTP" status_registry_ok
status_run "registry from cluster nodes" status_registry_from_cluster_nodes
status_run "traefik deployment" kubectl --kubeconfig "${KUBECONFIG_PATH}" -n traefik get deploy,svc,pod -o wide
status_run "website image" kubectl --kubeconfig "${KUBECONFIG_PATH}" -n website-production get deployment php-website-deployment -o jsonpath='{.spec.template.spec.containers[0].image}{"\n"}'
status_run "demos image" kubectl --kubeconfig "${KUBECONFIG_PATH}" -n demos-static get deployment demos-static -o jsonpath='{.spec.template.spec.containers[0].image}{"\n"}'
status_section "Debian External Services"
status_systemd_units docker tailscaled homelab-gitea-runner
status_compose_stack "gitea" "/data/homelab-gitea"
status_compose_stack "dex" "${LAB_DEX_INSTALL_DIR:-/data/homelab-dex}"
status_http "gitea local" "http://127.0.0.1:${LAB_GITEA_HTTP_PORT:-3000}/"
status_http "dex local" "http://127.0.0.1:${LAB_DEX_HTTP_PORT:-5556}/healthz"
status_http "ollama" "${LAB_OLLAMA_URL:-http://${LAB_DEBIAN_LAN_IP:-192.168.100.73}:11434}/api/tags"
status_section "Edge And Public URLs"
status_http "traefik lb" "http://${LAB_TRAEFIK_LB_IP:?LAB_TRAEFIK_LB_IP is required from homelab.yml}/"
status_http "website public" "${LAB_PUBLIC_URL:?LAB_PUBLIC_URL is required from homelab.yml}/"
status_http "gitea public" "${LAB_GITEA_ROOT_URL:-${LAB_PUBLIC_URL:?LAB_PUBLIC_URL is required from homelab.yml}/git/}"
status_http "grafana public" "https://grafana.${LAB_DOMAIN:?LAB_DOMAIN is required from homelab.yml}/login"
status_http "argocd public" "https://argocd.${LAB_DOMAIN:?LAB_DOMAIN is required from homelab.yml}/"
status_http "demos public" "https://demos.${LAB_DOMAIN:?LAB_DOMAIN is required from homelab.yml}/"
status_http "dex public" "${LAB_DEX_PUBLIC_URL:-https://auth.${LAB_DOMAIN:?LAB_DOMAIN is required from homelab.yml}/}"
status_section "Operations"
backup_status || true
cat <<'EOF'
Next steps:
- If a Kubernetes check fails, run ./jeannie doctor-cluster --verbose.
- If a public URL fails but local backends pass, run ./jeannie doctor-edge --verbose.
- If a registry/image check fails, run ./jeannie apps with the selected cluster profile.
- If Debian service checks fail, rerun the matching deploy command rather than moving the service into Kubernetes.
EOF
}
nuke() {
local target
local target_host
local worker_known_hosts_file="${REPO_ROOT}/.lab/rebuild-worker-known_hosts"
declare -a CLUSTER_WORKER_TARGETS=()
require_debian_server "nuke"
if ! truthy "${LAB_NUKE_SKIP_CONFIRM:-false}" && [[ "${LAB_CONFIRM_NUKE:-}" != "homelab" ]]; then
cat >&2 <<'EOF'
nuke destroys Kubernetes state and Pimox worker VMs.
Rerun with LAB_CONFIRM_NUKE=homelab when that destructive action is intended.
EOF
exit 1
fi
echo "Brutally nuking the homelab infrastructure..."
cluster_worker_targets
if ((${#CLUSTER_WORKER_TARGETS[@]} > 0)); then
mkdir -p "$(dirname "${worker_known_hosts_file}")"
touch "${worker_known_hosts_file}"
chmod 0600 "${worker_known_hosts_file}"
fi
echo "OpenTofu processes for other profiles are preserved; state locks remain authoritative."
echo "--> Eviscerating local Kubernetes components..."
cleanup_node || return 1
sudo rm -f "${KUBECONFIG_PATH}"
for target in "${CLUSTER_WORKER_TARGETS[@]}"; do
echo "--> Eviscerating remote Kubernetes components (${target})..."
target_host="${target#*@}"
target_host="${target_host%%:*}"
ssh-keygen -R "${target_host}" -f "${worker_known_hosts_file}" >/dev/null 2>&1 || true
if ! ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile="${worker_known_hosts_file}" "${target}" "bash -s" <<'EOF'
set -euo pipefail
cleanup_calico_links() {
ip link show | awk -F: '/^[0-9]+: cali/ {print $2}' | cut -d@ -f1 | xargs -r -n1 sudo ip link delete 2>/dev/null || true
sudo ip link delete vxlan.calico 2>/dev/null || true
sudo ip link delete tunl0 2>/dev/null || true
sudo ip link delete cni0 2>/dev/null || true
sudo ip link delete kube-ipvs0 2>/dev/null || true
ip netns list | awk '/^(cni-|calico)/ {print $1}' | xargs -r -n1 sudo ip netns delete 2>/dev/null || true
}
cleanup_iptables() {
sudo iptables -F || true
sudo iptables -X || true
sudo iptables -t nat -F || true
sudo iptables -t nat -X || true
sudo iptables -t mangle -F || true
sudo iptables -t mangle -X || true
sudo iptables -t raw -F || true
sudo iptables -t raw -X || true
if command -v ipvsadm >/dev/null 2>&1; then
sudo ipvsadm --clear || true
fi
}
cleanup_calico_runtime_files() {
local path
for path in /run/calico /var/run/calico; do
if sudo test -e "${path}"; then
sudo find "${path}" -path '*/cgroup*' -prune -o -mindepth 1 -exec rm -rf -- {} + 2>/dev/null || true
sudo rmdir "${path}" 2>/dev/null || true
fi
done
}
restore_node_dns() {
sudo rm -f /etc/systemd/resolved.conf.d/homelab-k8s.conf
if sudo test -e /etc/resolv.conf.homelab-k8s-backup; then
sudo rm -f /etc/resolv.conf
sudo mv /etc/resolv.conf.homelab-k8s-backup /etc/resolv.conf
fi
sudo systemctl restart systemd-resolved 2>/dev/null || true
}
cleanup_mounts() {
if command -v findmnt >/dev/null 2>&1; then
local mount_root
while IFS= read -r mountpoint; do
sudo umount -f "${mountpoint}" 2>/dev/null || sudo umount -l "${mountpoint}" 2>/dev/null || true
done < <(
for mount_root in /var/lib/kubelet /var/lib/containerd /run/calico /run/calico/cgroup /var/run/calico /var/run/calico/cgroup; do
findmnt -Rno TARGET "${mount_root}" 2>/dev/null || true
done | sort -ru
)
fi
while IFS= read -r mountpoint; do
sudo umount -f "${mountpoint}" 2>/dev/null || sudo umount -l "${mountpoint}" 2>/dev/null || true
done < <(find /var/lib/kubelet/pods -mindepth 2 -maxdepth 5 -type d 2>/dev/null || true)
sudo umount -f /var/lib/containerd/srun/* 2>/dev/null || sudo umount -l /var/lib/containerd/srun/* 2>/dev/null || true
}
sudo kubeadm reset --force || true
sudo systemctl stop kubelet 2>/dev/null || true
sudo systemctl stop containerd 2>/dev/null || true
sudo killall containerd-shim-runc-v2 2>/dev/null || true
cleanup_mounts
sudo rm -rf \
/etc/kubernetes/ \
/var/lib/etcd/ \
/var/lib/kubelet/ \
/var/lib/cni/ \
/etc/cni/net.d \
/run/flannel \
/var/lib/calico \
/var/log/calico \
/var/lib/containerd/* \
/run/containerd/* \
/etc/containerd/certs.d \
/etc/containerd/config.toml
cleanup_calico_runtime_files
sudo rm -f /opt/cni/bin/calico /opt/cni/bin/calico-ipam
cleanup_iptables
cleanup_calico_links
restore_node_dns
sudo mkdir -p /etc/containerd/certs.d
sudo systemctl reset-failed kubelet containerd 2>/dev/null || true
sudo systemctl start containerd 2>/dev/null || true
EOF
then
nuke_remote_cleanup_failed "${target}" || exit 1
fi
done
destroy_pimox_worker_vms
docker buildx rm lab-builder 2>/dev/null || true
docker rm -f buildx_buildkit_lab-builder0 2>/dev/null || true
rm -f "${BUILDX_CONFIG}" || true
echo "--> Backing up local OpenTofu tracking state files..."
backup_tofu_state
echo "Profile identities, scoped states, legacy states and shared edge state are retained for reviewed recovery."
rm -f "${REPO_ROOT}/.lab/pimox-workers.tsv" "${REPO_ROOT}/.lab/cluster-workers.auto.tfvars.json"
echo "Destruction complete. Retained data under /data/openebs/local was left intact."
}
ensure_sops_age_tools() {
local missing_packages=()
if ! command -v age-keygen >/dev/null 2>&1; then
missing_packages+=(age)
fi
if ! command -v sops >/dev/null 2>&1; then
missing_packages+=(sops)
fi
if ((${#missing_packages[@]} > 0)); then
echo "Installing missing secret-management tools: ${missing_packages[*]}"
sudo apt-get update
sudo apt-get install -y --no-install-recommends "${missing_packages[@]}"
fi
if ! command -v age-keygen >/dev/null 2>&1; then
echo "age-keygen is still unavailable after package installation." >&2
exit 1
fi
if ! command -v sops >/dev/null 2>&1; then
echo "sops is still unavailable after package installation." >&2
exit 1
fi
}
sops_age_key_file() {
printf '%s\n' "${SOPS_AGE_KEY_FILE:-${HOME}/.config/sops/age/keys.txt}"
}
sops_age_recipient() {
local key_file="$1"
awk -F': ' '/^# public key:/ { print $2; exit }' "${key_file}"
}
secrets_init() {
local key_file
local key_dir
local recipient
local config_file="${SOPS_CONFIG:-${REPO_ROOT}/.sops.yaml}"
local example_file="${REPO_ROOT}/.sops.yaml.example"
require_debian_server "secrets-init"
ensure_sops_age_tools
key_file="$(sops_age_key_file)"
key_dir="$(dirname "${key_file}")"
mkdir -p "${key_dir}"
chmod 700 "${key_dir}"
if [[ ! -s "${key_file}" ]]; then
echo "Generating age identity at ${key_file}..."
age-keygen -o "${key_file}"
chmod 600 "${key_file}"
else
echo "Using existing age identity at ${key_file}."
chmod 600 "${key_file}"
fi
recipient="$(sops_age_recipient "${key_file}")"
if [[ -z "${recipient}" ]]; then
echo "Could not read the public recipient from ${key_file}." >&2
exit 1
fi
if [[ -e "${config_file}" ]]; then
if grep -q 'age1replacewithyourpublicrecipient' "${config_file}"; then
echo "${config_file} still contains the placeholder age recipient." >&2
exit 1
fi
echo "SOPS config already exists: ${config_file}"
else
if [[ ! -s "${example_file}" ]]; then
echo "Missing ${example_file}" >&2
exit 1
fi
sed "s/age1replacewithyourpublicrecipient/${recipient}/g" "${example_file}" >"${config_file}"
echo "Wrote ${config_file} with Debian host age recipient ${recipient}."
fi
echo "Private age key: ${key_file}"
echo "Public age recipient: ${recipient}"
echo "Review and commit ${config_file}; never commit ${key_file}."
}
secrets_check_file() {
local file="$1"
local key_file="$2"
case "${file}" in
*.json)
grep -q '"sops"' "${file}" || {
echo "${file} does not look SOPS-encrypted." >&2
return 1
}
;;
*)
grep -q '^sops:' "${file}" || {
echo "${file} does not look SOPS-encrypted." >&2
return 1
}
;;
esac
if [[ -s "${key_file}" ]]; then
SOPS_AGE_KEY_FILE="${key_file}" sops -d "${file}" >/dev/null
fi
}
secrets_check() {
local config_file="${SOPS_CONFIG:-${REPO_ROOT}/.sops.yaml}"
local key_file
local recipient=""
local failures=0
local found_files=0
local file
key_file="$(sops_age_key_file)"
if [[ ! -s "${config_file}" ]]; then
echo "Missing ${config_file}. Run ./jeannie secrets-init on the Debian host." >&2
failures=$((failures + 1))
elif grep -q 'age1replacewithyourpublicrecipient' "${config_file}"; then
echo "${config_file} still contains the placeholder age recipient." >&2
failures=$((failures + 1))
fi
if [[ -s "${key_file}" ]]; then
recipient="$(sops_age_recipient "${key_file}")"
if [[ -n "${recipient}" && -s "${config_file}" ]] && ! grep -q "${recipient}" "${config_file}"; then
echo "${config_file} does not include this host's age recipient ${recipient}." >&2
failures=$((failures + 1))
fi
else
echo "No local age key found at ${key_file}; encrypted file structure will be checked without decrypting."
fi
if command -v git >/dev/null 2>&1; then
while IFS= read -r file; do
[[ -n "${file}" ]] || continue
found_files=$((found_files + 1))
secrets_check_file "${REPO_ROOT}/${file}" "${key_file}" || failures=$((failures + 1))
done < <(git -C "${REPO_ROOT}" ls-files '*.secret.yaml' '*.secret.yml' '*.secret.json' '*.enc.yaml' '*.enc.yml' '*.enc.json')
fi
if ((failures > 0)); then
echo "Secret checks failed with ${failures} issue(s)." >&2
exit 1
fi
if ((found_files == 0)); then
echo "SOPS config checks passed. No encrypted secret files are committed yet."
else
echo "SOPS config checks passed for ${found_files} encrypted secret file(s)."
fi
}
tailnet_policy_check() {
"${REPO_ROOT}/scripts/validate-tailnet-policy"
}
ai_index() {
local index_dir="${LAB_AI_KNOWLEDGE_INDEX_DIR:-/data/homelab-ai/index}"
require_debian_server "ai-index"
ensure_python3
if [[ "${index_dir}" == /data/* ]]; then
sudo mkdir -p "${index_dir}"
sudo chown "${USER}:$(id -gn)" "${index_dir}"
fi
"${REPO_ROOT}/scripts/build-homelab-ai-index" --index-dir "${index_dir}"
}
ai_check() {
local index_dir="${LAB_AI_KNOWLEDGE_INDEX_DIR:-/data/homelab-ai/index}"
local routes_file="${LAB_AI_STACK_MODEL_ROUTES_FILE:-/data/homelab-ai-stack/models.env}"
local tools_env_file="${LAB_AI_STACK_TOOLS_ENV_FILE:-/data/homelab-ai-stack/ai-tools.env}"
local endpoint="${LAB_AI_GATEWAY_URL:-${LAB_OLLAMA_URL:-http://127.0.0.1:11434}}"
local model="${LAB_AI_GATEWAY_MODEL:-qwen2.5:0.5b}"
local provider="${LAB_AI_GATEWAY_PROVIDER:-ollama}"
local failures=0
local tool
require_debian_server "ai-check"
status_section "AI Knowledge"
if command -v python3 >/dev/null 2>&1; then
printf '%-28s ok\n' "python3"
else
printf '%-28s missing\n' "python3"
failures=$((failures + 1))
fi
if [[ -s "${index_dir}/index.json" ]]; then
printf '%-28s %s\n' "knowledge index" "${index_dir}/index.json"
else
printf '%-28s missing - run ./jeannie ai-index\n' "knowledge index"
failures=$((failures + 1))
fi
if "${REPO_ROOT}/scripts/query-homelab-ai-index" --index-dir "${index_dir}" --context-only --limit 2 "gitea edge traefik" >/dev/null 2>&1; then
printf '%-28s ok\n' "retrieval smoke test"
else
printf '%-28s failed\n' "retrieval smoke test"
failures=$((failures + 1))
fi
if command -v holmes >/dev/null 2>&1; then
printf '%-28s ok - %s\n' "holmes k8s triage" "$(command -v holmes)"
else
printf '%-28s missing - install holmes for Kubernetes triage\n' "holmes k8s triage"
fi
for tool in goose hermes holmes; do
if command -v "jeannie-${tool}" >/dev/null 2>&1; then
printf '%-28s ok - %s\n' "jeannie-${tool}" "$(command -v "jeannie-${tool}")"
else
printf '%-28s missing - run ./jeannie deploy-ai-tools\n' "jeannie-${tool}"
fi
done
if [[ -r "${tools_env_file}" && -s "${tools_env_file}" ]]; then
printf '%-28s ok - %s\n' "ai tools env" "${tools_env_file}"
# shellcheck disable=SC1090
. "${tools_env_file}"
provider="${LAB_AI_GATEWAY_PROVIDER:-omniroute}"
endpoint="${OPENAI_BASE_URL:-${LAB_AI_GATEWAY_URL:-http://127.0.0.1:20128/v1}}"
model="${LAB_AI_GATEWAY_MODEL:-${AI_STACK_AGENT_FAST_MODEL:-agent-fast-free}}"
elif [[ -e "${tools_env_file}" ]]; then
printf '%-28s unreadable - rerun ./jeannie deploy-ai-tools\n' "ai tools env"
failures=$((failures + 1))
else
printf '%-28s missing - run ./jeannie deploy-ai-tools\n' "ai tools env"
fi
if [[ -s "${routes_file}" ]]; then
# shellcheck disable=SC1090
. "${routes_file}"
if [[ "${AI_STACK_MODEL_VALIDATION_STATUS:-ok}" == "ok" ]]; then
printf '%-28s ok - %s\n' "ai stack routes" "${routes_file}"
else
printf '%-28s failed validation - rerun ./jeannie deploy-ai-stack after fixing providers\n' "ai stack routes"
failures=$((failures + 1))
fi
printf '%-28s %s\n' "agent fast model" "${AI_STACK_AGENT_FAST_MODEL:-unset}"
printf '%-28s %s\n' "agent smart model" "${AI_STACK_AGENT_SMART_MODEL:-unset}"
printf '%-28s fast=%s smart=%s\n' "validated routes" "${AI_STACK_VALIDATED_FAST_COUNT:-unknown}" "${AI_STACK_VALIDATED_SMART_COUNT:-unknown}"
if [[ -z "${AI_STACK_AGENT_FAST_MODEL:-}" || -z "${AI_STACK_AGENT_SMART_MODEL:-}" ]]; then
failures=$((failures + 1))
fi
if [[ "${provider}" == "ollama" && -n "${AI_STACK_AGENT_FAST_MODEL:-}" ]]; then
provider="omniroute"
endpoint="${LAB_AI_GATEWAY_URL:-http://127.0.0.1:20128/v1}"
model="${LAB_AI_GATEWAY_MODEL:-${AI_STACK_AGENT_FAST_MODEL}}"
fi
else
printf '%-28s missing - run ./jeannie deploy-ai-stack\n' "ai stack routes"
fi
if backstage_brain_enabled; then
if [[ "${provider,,}" == "omniroute" || "${provider,,}" == "openai" ]]; then
if curl -sS -o /dev/null -w '%{http_code}' --max-time 5 "${endpoint%/}/models" 2>/dev/null | grep -Eq '^(200|401)$'; then
printf '%-28s ok - %s\n' "omniroute endpoint" "${endpoint}"
else
printf '%-28s unreachable - %s\n' "omniroute endpoint" "${endpoint}"
failures=$((failures + 1))
fi
if [[ -n "${model}" ]] && python3 - "${endpoint}" "${model}" "${OPENAI_API_KEY:-${LAB_AI_GATEWAY_API_KEY:-sk_omniroute}}" <<'PY'
import json
import sys
import urllib.error
import urllib.request
endpoint, model, api_key = sys.argv[1:4]
payload = {
"model": model,
"messages": [{"role": "user", "content": "Return only: ok"}],
"stream": False,
"max_tokens": 64,
}
headers = {"Content-Type": "application/json", "Accept": "application/json"}
if api_key:
headers["Authorization"] = f"Bearer {api_key}"
request = urllib.request.Request(
f"{endpoint.rstrip('/')}/chat/completions",
data=json.dumps(payload).encode("utf-8"),
headers=headers,
method="POST",
)
try:
with urllib.request.urlopen(request, timeout=45) as response:
data = json.load(response)
except urllib.error.HTTPError as exc:
print(f"HTTP {exc.code}", file=sys.stderr)
raise SystemExit(1)
except Exception as exc:
print(type(exc).__name__, file=sys.stderr)
raise SystemExit(1)
choices = data.get("choices") or []
content = ""
if choices:
value = (choices[0].get("message") or {}).get("content")
if isinstance(value, str):
content = value.strip()
elif isinstance(value, list):
parts = []
for item in value:
if isinstance(item, str):
parts.append(item)
elif isinstance(item, dict):
text = item.get("text") or item.get("content")
if isinstance(text, str):
parts.append(text)
content = " ".join(parts).strip()
raise SystemExit(0 if content else 1)
PY
then
printf '%-28s ok - %s\n' "omniroute model" "${model}"
else
printf '%-28s failed chat completion - %s\n' "omniroute model" "${model:-unset}"
failures=$((failures + 1))
fi
elif curl -fsS --max-time 5 "${endpoint%/}/api/tags" >/dev/null 2>&1; then
printf '%-28s ok - %s\n' "ollama endpoint" "${endpoint}"
if python3 - "${endpoint}" "${model}" <<'PY'
import json
import sys
import urllib.request
endpoint, model = sys.argv[1:3]
with urllib.request.urlopen(f"{endpoint.rstrip('/')}/api/tags", timeout=5) as response:
tags = json.loads(response.read().decode("utf-8"))
models = {item.get("name", "") for item in tags.get("models", [])}
raise SystemExit(0 if model in models or f"{model}:latest" in models else 1)
PY
then
printf '%-28s ok - %s\n' "ollama model" "${model}"
else
printf '%-28s missing - run: ollama pull %s\n' "ollama model" "${model}"
failures=$((failures + 1))
fi
else
printf '%-28s unreachable - %s\n' "ollama endpoint" "${endpoint}"
failures=$((failures + 1))
fi
else
printf '%-28s disabled\n' "backstage helper"
fi
if ((failures > 0)); then
echo "AI check failed with ${failures} issue(s)." >&2
exit 1
fi
echo "AI check passed."
}
ask_homelab() {
require_debian_server "ask"
"${REPO_ROOT}/scripts/ask" "${@:2}"
}
ai_evals() {
"${REPO_ROOT}/scripts/ai-evals" "${@:2}"
}
impact() {
"${REPO_ROOT}/scripts/impact" "${@:2}"
}
review_last_change() {
"${REPO_ROOT}/scripts/review-last-change" "${@:2}"
}
security_scan() {
require_debian_server "security-scan"
"${REPO_ROOT}/scripts/security-scan" all
}
security_prepare() {
require_debian_server "security-prepare"
"${REPO_ROOT}/scripts/security-scan" prepare
}
security_zap() {
require_debian_server "security-zap"
"${REPO_ROOT}/scripts/security-scan" zap
}
security_k8s() {
require_debian_server "security-k8s"
"${REPO_ROOT}/scripts/security-scan" kube-bench
}
security_host() {
require_debian_server "security-host"
"${REPO_ROOT}/scripts/security-scan" host
}
security_trivy() {
require_debian_server "security-trivy"
"${REPO_ROOT}/scripts/security-scan" trivy
}
security_secrets() {
require_debian_server "security-secrets"
"${REPO_ROOT}/scripts/security-scan" secrets
}
security_nuclei() {
require_debian_server "security-nuclei"
"${REPO_ROOT}/scripts/security-scan" nuclei
}
security_web() {
require_debian_server "security-web"
"${REPO_ROOT}/scripts/security-scan" web
}
security_logs() {
require_debian_server "security-logs"
"${REPO_ROOT}/scripts/security-logs"
}
security_runtime() {
require_debian_server "security-runtime"
if ! command -v kubectl >/dev/null 2>&1; then
echo "kubectl is required for security-runtime." >&2
exit 1
fi
kubectl --kubeconfig "${KUBECONFIG}" -n kube-system rollout status daemonset/tetragon --timeout=30s
kubectl --kubeconfig "${KUBECONFIG}" -n kube-system get pods -l app.kubernetes.io/name=tetragon -o wide
cat <<'EOF'
Watch recent Tetragon events:
kubectl -n kube-system logs -l app.kubernetes.io/name=tetragon -c export-stdout --tail=100 -f
Useful practice trigger:
kubectl -n security-lab exec deploy/juice-shop -- sh -c 'id; uname -a'
EOF
}
security_attack_path() {
require_debian_server "security-attack-path"
"${REPO_ROOT}/scripts/security-attack-path" "${@:2}"
}
prompt_injection_lab() {
"${REPO_ROOT}/scripts/prompt-injection-lab" "${@:2}"
}
incident_commander() {
"${REPO_ROOT}/scripts/incident-commander" "${@:2}"
}
safety_case() {
"${REPO_ROOT}/scripts/safety-case" "${@:2}"
}
agent_sandbox() {
"${REPO_ROOT}/scripts/agent-sandbox" "${@:2}"
}
ai_scheduler() {
"${REPO_ROOT}/scripts/ai-scheduler" "${@:2}"
}
ai_memory() {
"${REPO_ROOT}/scripts/ai-memory" "${@:2}"
}
red_blue_loop() {
"${REPO_ROOT}/scripts/red-blue-loop" "${@:2}"
}
promote() {
"${REPO_ROOT}/scripts/promote" "${@:2}"
}
model_observe() {
"${REPO_ROOT}/scripts/model-observe" "${@:2}"
}
heal() {
require_debian_server "heal"
export LAB_CLUSTER_PROFILE
export KUBECONFIG="${KUBECONFIG_PATH}"
export LAB_KUBECONFIG_PATH="${KUBECONFIG}"
"${REPO_ROOT}/scripts/heal" "${@:2}"
}
self_heal() {
require_debian_server "self-heal"
export LAB_CLUSTER_PROFILE
export KUBECONFIG="${KUBECONFIG_PATH}"
export LAB_KUBECONFIG_PATH="${KUBECONFIG}"
if [ "${2:-}" = "install-service" ]; then
local apply_mode
local service_file
local service_stage
apply_mode="${LAB_SELF_HEAL_APPLY:-false}"
if [ "${3:-}" = "--apply" ]; then
apply_mode="true"
fi
if [[ "${apply_mode}" != true && "${apply_mode}" != false ]]; then
echo "LAB_SELF_HEAL_APPLY must be true or false." >&2
return 2
fi
if [[ "${apply_mode}" == true ]]; then
python3 "${REPO_ROOT}/scripts/cluster-context.py" check \
--profile "${LAB_CLUSTER_PROFILE}" --kubeconfig "${KUBECONFIG}" >/dev/null || return 1
fi
if [[ ! -r "${KUBECONFIG}" ]]; then
echo "Self-heal kubeconfig is not readable: ${KUBECONFIG}" >&2
return 1
fi
service_stage="$(mktemp -d "${TMPDIR:-/tmp}/jeannie-eventd-unit.XXXXXXXX")"
service_file="${service_stage}/jeannie-eventd.service"
if ! python3 - "${REPO_ROOT}/infra/jeannie-eventd/jeannie-eventd.service" \
"${REPO_ROOT}" "${LAB_CLUSTER_PROFILE}" "${KUBECONFIG}" "${apply_mode}" >"${service_file}" <<'PY'
from pathlib import Path
import sys
template, repo, profile, kubeconfig, apply_mode = sys.argv[1:]
def quote_unit(value):
if "\n" in value or "\r" in value:
raise SystemExit("Invalid newline in self-heal service setting")
return '"' + value.replace("\\", "\\\\").replace('"', '\\"').replace("%", "%%") + '"'
replacements = {
# WorkingDirectory takes a literal absolute path, unlike the shell-word
# parsing used by ExecStart and Environment. Quotes become path characters.
"WorkingDirectory": repo.replace("%", "%%"),
"ExecStart": quote_unit(repo + "/scripts/jeannie-eventd") + " serve",
"Environment=LAB_CLUSTER_PROFILE": quote_unit("LAB_CLUSTER_PROFILE=" + profile),
"Environment=KUBECONFIG": quote_unit("KUBECONFIG=" + kubeconfig),
"Environment=LAB_KUBECONFIG_PATH": quote_unit("LAB_KUBECONFIG_PATH=" + kubeconfig),
"Environment=LAB_SELF_HEAL_APPLY": quote_unit("LAB_SELF_HEAL_APPLY=" + apply_mode),
}
for line in Path(template).read_text().splitlines():
for key, value in replacements.items():
if line.startswith(key + "="):
prefix = "Environment" if key.startswith("Environment=") else key
line = prefix + "=" + value
break
print(line)
PY
then
rm -f "${service_file}"
rmdir "${service_stage}"
echo "Self-heal service rendering failed; existing service preserved." >&2
return 1
fi
if ! sudo systemd-analyze verify --man=no "${service_file}"; then
rm -f "${service_file}"
rmdir "${service_stage}"
echo "Self-heal unit validation failed; existing service preserved." >&2
return 1
fi
remember_cluster_profile || return 1
sudo install -m 0644 "${service_file}" /etc/systemd/system/jeannie-eventd.service
rm -f "${service_file}"
rmdir "${service_stage}"
sudo systemctl daemon-reload
sudo systemctl enable jeannie-eventd
sudo systemctl restart jeannie-eventd
sudo systemctl status jeannie-eventd --no-pager
return
fi
"${REPO_ROOT}/scripts/jeannie-eventd" "${@:2}"
}
validate_homelab() {
"${REPO_ROOT}/scripts/validate-homelab"
}
access_audit() {
require_debian_server "access-audit"
"${REPO_ROOT}/scripts/access-audit"
}
drill_restore() {
require_debian_server "drill-restore"
"${REPO_ROOT}/scripts/restore-drill" all
}
drill_pihole_restore() {
"${REPO_ROOT}/scripts/restore-drill" pihole
}
kubeconfig_readonly() {
require_debian_server "kubeconfig-readonly"
"${REPO_ROOT}/scripts/kubeconfig-readonly"
}
capacity_report() {
require_debian_server "capacity"
"${REPO_ROOT}/scripts/capacity-report" "${@:2}"
}
recover_plan() {
require_debian_server "recover-plan"
"${REPO_ROOT}/scripts/recover-plan"
}
gitops_status() {
require_debian_server "gitops-status"
"${REPO_ROOT}/scripts/gitops-status"
}
gitops_manage() {
require_debian_server "gitops"
case "${1:-}" in
diff)
shift
"${REPO_ROOT}/scripts/gitops-diff" "$@"
;;
refresh)
shift
"${REPO_ROOT}/scripts/gitops-refresh" "$@"
;;
*)
echo "Usage: ./jeannie gitops {diff [APP]|refresh APP|--all}" >&2
return 2
;;
esac
}
state_status() {
require_debian_server "state status"
if [[ "${1:-}" == "oci" || "${1:-}" == "bootstrap/oci" ]]; then
oci_foundation_export_inputs
fi
"${REPO_ROOT}/scripts/state-status" "$@"
}
pimox_oob() {
require_debian_server "pimox"
"${REPO_ROOT}/scripts/pimox-oob" "$@"
}
email_vm_manage() {
require_debian_server "email-vm"
if [[ "${1:-}" == setup || "${1:-}" == status-server ]]; then
local email_action="${1}"
shift || true
case "${email_action}" in
setup)
oci_foundation_load_config
while (($# > 0)); do
case "$1" in
--domain) export LAB_EMAIL_DOMAIN="${2:-}"; shift 2 ;;
--open-mail-ports) export LAB_EMAIL_OPEN_MAIL_PORTS=true; shift ;;
*) echo "Usage: ./jeannie email-vm setup [--domain DOMAIN] [--open-mail-ports]" >&2; return 2 ;;
esac
done
LAB_EMAIL_DOMAIN="${LAB_EMAIL_DOMAIN:-}" LAB_EMAIL_OPEN_MAIL_PORTS="${LAB_EMAIL_OPEN_MAIL_PORTS:-false}" "${REPO_ROOT}/scripts/email-server" install
;;
status-server) "${REPO_ROOT}/scripts/email-server" status ;;
esac
return
fi
export_email_vm_tf_vars
local action="${1:-status}"
shift || true
local stack="${REPO_ROOT}/bootstrap/email"
case "${action}" in
status)
tofu -chdir="${stack}" show -no-color 2>/dev/null || echo "OCI email VM has no state yet."
;;
plan|apply)
if [[ "${TF_VAR_enabled:-false}" != "true" ]]; then
echo "OCI email VM is disabled. Set LAB_EMAIL_VM_ENABLED=true and the required LAB_EMAIL_* inputs first." >&2
return 2
fi
tofu -chdir="${stack}" init
if [[ "${action}" == "plan" ]]; then
tofu -chdir="${stack}" plan "$@"
else
record_change_journal "email-vm" "${action}" "$@"
tofu -chdir="${stack}" apply "$@" -auto-approve
fi
;;
destroy)
if [[ "${1:-}" != "--yes" ]]; then
echo "Refusing to destroy the OCI email VM without --yes." >&2
return 2
fi
shift
record_change_journal "email-vm" destroy "$@"
tofu -chdir="${stack}" init
tofu -chdir="${stack}" destroy "$@" -auto-approve
;;
*)
echo "Usage: ./jeannie email-vm {status|plan|apply|setup|status-server|destroy --yes}" >&2
return 2
;;
esac
}
oci_foundation_config_names=(
LAB_OCI_FOUNDATION_ENABLED LAB_OCI_REGION LAB_OCI_TENANCY_ID LAB_OCI_ADMIN_CIDR
LAB_OCI_SSH_PUBLIC_KEY LAB_OCI_SSH_PRIVATE_KEY LAB_EDGE_SSH_KEY_PATH LAB_OCI_CREATE_COMPARTMENT LAB_OCI_COMPARTMENT_ID LAB_OCI_COMPARTMENT_NAME
LAB_OCI_EDGE_ENABLED LAB_OCI_EMAIL_ENABLED LAB_OCI_COMPUTE_ENABLED LAB_OCI_NAT_ENABLED LAB_OCI_EDGE_EXISTING_INSTANCE_ID LAB_OCI_EMAIL_EXISTING_INSTANCE_ID
LAB_OCI_EXISTING_VCN_ID LAB_OCI_EXISTING_PUBLIC_SUBNET_ID LAB_OCI_EXISTING_EMAIL_SUBNET_ID
LAB_OCI_VCN_CIDR LAB_OCI_PUBLIC_SUBNET_CIDR LAB_OCI_PRIVATE_SUBNET_CIDR
LAB_OCI_EDGE_IMAGE_ID LAB_OCI_EMAIL_IMAGE_ID LAB_OCI_EDGE_SHAPE LAB_OCI_EMAIL_SHAPE
LAB_OCI_EDGE_BOOT_VOLUME_SIZE_IN_GBS LAB_OCI_EMAIL_BOOT_VOLUME_SIZE_IN_GBS
LAB_OCI_BACKUP_BUCKET_COMPARTMENT_ID LAB_OCI_MONITORING_TOPIC_COMPARTMENT_ID
LAB_OCI_CONFIG_PROFILE
LAB_EDGE_SSH_TRANSPORT LAB_EDGE_TAILSCALE_HOSTNAME LAB_EDGE_SSH_PREFLIGHT_SECONDS
LAB_OCI_EMAIL_CREATE_COMPARTMENT LAB_OCI_EMAIL_COMPARTMENT_ID LAB_OCI_EMAIL_COMPARTMENT_NAME
LAB_OCI_EMAIL_SUBNET_CIDR LAB_OCI_EDGE_AVAILABILITY_DOMAIN LAB_OCI_EMAIL_AVAILABILITY_DOMAIN
LAB_OCI_OPEN_MAIL_PORTS LAB_OCI_AUTO_CONFIGURE_EDGE LAB_EDGE_HOST LAB_EDGE_TAILSCALE_IP
LAB_OCI_AUTO_CONFIGURE_EMAIL LAB_OCI_AUTO_UPDATE_DUCKDNS LAB_DUCKDNS_DOMAINS
LAB_OCI_FOUNDATION_STATE_FILE
LAB_OCI_MONITORING_ENABLED LAB_OCI_MONITORING_CIDR LAB_OCI_MONITORING_ALARMS_ENABLED LAB_OCI_MONITORING_TOPIC_NAME LAB_OCI_MONITORING_TOPIC_ID LAB_OCI_MONITORING_NOTIFICATION_EMAIL LAB_OCI_EDGE_TAILNET_SSH_CIDR
LAB_OCI_BACKUP_BUCKET_ENABLED LAB_OCI_BACKUP_BUCKET LAB_OCI_BACKUP_BUCKET_NAME LAB_OCI_BACKUP_BUCKET_NAMESPACE LAB_OCI_BACKUP_BUCKET_ID
LAB_OCI_BASTION_ENABLED LAB_OCI_BASTION_NAME LAB_OCI_BASTION_TARGET_SUBNET_ID LAB_OCI_BASTION_SSH_SOURCE_CIDR
LAB_OCI_BASTION_CLIENT_CIDRS_JSON LAB_OCI_BASTION_MAX_SESSION_TTL LAB_OCI_BASTION_ID LAB_OCI_EDGE_COMPARTMENT_ID LAB_OCI_EDGE_INSTANCE_ID LAB_OCI_EMAIL_INSTANCE_ID LAB_OCI_EDGE_INSTANCE_MANAGED
LAB_EMAIL_PUBLIC_IP LAB_OCI_EDGE_METRICS_TARGET LAB_OCI_EMAIL_METRICS_TARGET
)
oci_foundation_config_file() {
printf '%s\n' "${LAB_OCI_FOUNDATION_CONFIG_FILE:-${HOME}/.config/homelab/oci-foundation.env}"
}
oci_foundation_load_config() {
[[ "${LAB_OCI_CONFIG_LOADED:-false}" == "true" ]] && return 0
local resolved
resolved="$(python3 "${REPO_ROOT}/scripts/oci-foundation-resolve.py" load \
--config "$(oci_foundation_config_file)" --repo "${REPO_ROOT}" \
--names "${oci_foundation_config_names[@]}")" || return 1
# The resolver emits quoted assignments, never file-provided code.
eval "${resolved}"
}
oci_foundation_save_config() {
python3 "${REPO_ROOT}/scripts/oci-foundation-resolve.py" save \
--config "$(oci_foundation_config_file)" --repo "${REPO_ROOT}" \
--names "${oci_foundation_config_names[@]}"
}
oci_foundation_reconcile_existing() {
local resolved
resolved="$(python3 "${REPO_ROOT}/scripts/oci-foundation-resolve.py" reconcile \
--repo "${REPO_ROOT}")" || return 1
eval "${resolved}"
}
oci_foundation_export_inputs() {
# Rebuild this stack's TF_VAR set. export_if_unset would otherwise
# retain stale counts/OCIDs from before reconciliation.
local name
while IFS= read -r name; do
unset "TF_VAR_${name}"
done < <(sed -n 's/^variable "\([^"]*\)".*/\1/p' "${REPO_ROOT}/bootstrap/oci/variables.tf")
export_oci_foundation_tf_vars
if [[ "${LAB_OCI_STATE_BASTION_MANAGED:-false}" == "true" ]]; then
export TF_VAR_bastion_existing_id=""
fi
}
oci_wait_for_ssh() {
local target="$1"
local key_path="$2"
local timeout_seconds="${3:-180}"
local elapsed=0
while ((elapsed < timeout_seconds)); do
if ssh -i "${key_path}" -o BatchMode=yes -o ConnectTimeout=5 \
-o StrictHostKeyChecking=accept-new "${target}" true >/dev/null 2>&1; then
return 0
fi
sleep 5
elapsed=$((elapsed + 5))
done
echo "Timed out waiting for SSH on ${target} after ${timeout_seconds}s." >&2
return 1
}
update_duckdns_edge_ip() {
local edge_ip="$1"
local token="${LAB_DUCKDNS_TOKEN:-}"
local domains="${LAB_DUCKDNS_DOMAINS:-}"
local response
if disabled_value "${LAB_OCI_AUTO_UPDATE_DUCKDNS:-true}"; then
echo "DuckDNS update disabled by LAB_OCI_AUTO_UPDATE_DUCKDNS."
return 0
fi
if [[ -z "${token}" ]]; then
echo "DuckDNS update skipped: LAB_DUCKDNS_TOKEN is not set."
return 0
fi
if [[ -z "${domains}" ]]; then
domains="${LAB_DOMAIN%%.*}"
fi
command -v curl >/dev/null 2>&1 || {
echo "curl is required for the DuckDNS update." >&2
return 1
}
echo "Updating DuckDNS domains ${domains} to edge IP ${edge_ip}..."
response="$(curl -fsS --get 'https://www.duckdns.org/update' \
--data-urlencode "domains=${domains}" \
--data-urlencode "token=${token}" \
--data-urlencode "ip=${edge_ip}")" || {
echo "DuckDNS update request failed." >&2
return 1
}
if [[ "${response}" != OK* ]]; then
echo "DuckDNS rejected the update: ${response}" >&2
return 1
fi
echo "DuckDNS update succeeded."
}
oci_foundation_manage() {
require_debian_server "oci-foundation"
oci_foundation_load_config
# A previous invocation in a long-lived API process must not retain stale
# TF_VAR values after the persisted OCI inputs change.
unset TF_VAR_enabled TF_VAR_region TF_VAR_tenancy_id TF_VAR_admin_cidr
unset TF_VAR_compute_enabled
unset TF_VAR_edge_availability_domain TF_VAR_email_availability_domain
unset TF_VAR_existing_vcn_id TF_VAR_existing_public_subnet_id TF_VAR_existing_email_subnet_id
oci_foundation_export_inputs
local action="${1:-status}"
shift || true
local stack="${REPO_ROOT}/bootstrap/oci"
local state_file="${LAB_OCI_FOUNDATION_STATE_FILE:-}"
local -a tofu_state_args=()
if [[ -n "${state_file}" ]]; then
mkdir -p "$(dirname "${state_file}")"
tofu_state_args=("-state=${state_file}")
fi
case "${action}" in
verify)
python3 "${REPO_ROOT}/tests/jeannie/test_oci_foundation_resolve.py"
;;
status)
if [[ -n "${state_file}" ]]; then
if [[ ! -f "${state_file}" ]]; then
echo "OCI foundation state file not found: ${state_file}" >&2
return 1
fi
tofu -chdir="${stack}" show -no-color "${state_file}" || return 1
else
tofu -chdir="${stack}" show -no-color || return 1
fi
;;
review-edge-plan)
if [[ $# -ne 1 || "$1" != /* || ! -f "$1" ]]; then
echo "Usage: ./jeannie oci-foundation review-edge-plan /absolute/path/to/saved-plan" >&2
return 2
fi
local reviewed_state="${state_file:-${stack}/terraform.tfstate}"
if [[ ! -f "${reviewed_state}" ]]; then
echo "OCI foundation state file not found: ${reviewed_state}" >&2
return 1
fi
tofu -chdir="${stack}" show -json "$1" |
python3 "${REPO_ROOT}/scripts/oci-foundation-resolve.py" review-edge-plan --state "${reviewed_state}"
;;
plan|apply)
# Serialize generated import declarations as well as state access.
local foundation_lock
exec {foundation_lock}>"${stack}/.jeannie-foundation.lock"
if ! flock -n "${foundation_lock}"; then
echo "Another OCI foundation run is active; wait for it to finish." >&2
return 1
fi
if [[ "${TF_VAR_enabled:-false}" != "true" ]]; then
echo "OCI foundation is disabled. Set LAB_OCI_FOUNDATION_ENABLED=true and the required LAB_OCI_* inputs first." >&2
return 2
fi
if [[ "${LAB_OCI_CLI_AUTO_INSTALL:-true}" == "true" ]]; then
"${REPO_ROOT}/scripts/oci-auth" install
fi
oci_foundation_reconcile_existing || {
echo "OCI foundation discovery failed; refusing to plan or apply." >&2
return 1
}
unset TF_VAR_enabled TF_VAR_region TF_VAR_tenancy_id TF_VAR_admin_cidr
unset TF_VAR_compute_enabled
unset TF_VAR_edge_availability_domain TF_VAR_email_availability_domain
unset TF_VAR_existing_vcn_id TF_VAR_existing_public_subnet_id TF_VAR_existing_email_subnet_id
oci_foundation_export_inputs
oci_foundation_save_config
tofu -chdir="${stack}" init -input=false
local foundation_plan foundation_json
foundation_plan="$(mktemp "${TMPDIR:-/tmp}/jeannie-oci-plan.XXXXXX")"
foundation_json="${foundation_plan}.json"
if ! tofu -chdir="${stack}" plan "${tofu_state_args[@]}" -input=false -out="${foundation_plan}" "$@"; then
rm -f "${foundation_plan}" "${foundation_json}"
return 1
fi
if ! tofu -chdir="${stack}" show -json "${foundation_plan}" >"${foundation_json}" ||
! python3 "${REPO_ROOT}/scripts/oci-foundation-resolve.py" check-plan --plan "${foundation_json}"; then
rm -f "${foundation_plan}" "${foundation_json}"
return 1
fi
if [[ "${action}" == "apply" ]]; then
record_change_journal "oci-foundation" apply "$@"
if ! tofu -chdir="${stack}" apply "${tofu_state_args[@]}" "${foundation_plan}"; then
rm -f "${foundation_plan}" "${foundation_json}"
return 1
fi
rm -f "${foundation_plan}" "${foundation_json}"
local discovered_edge_ip
local discovered_email_ip
local discovered_bastion_id
local discovered_backup_bucket_name
local discovered_backup_bucket_namespace
local discovered_backup_bucket_id
local discovered_monitoring_topic_id
local discovered_edge_instance_id
local post_apply_failures=0
discovered_edge_ip="$(tofu -chdir="${stack}" output "${tofu_state_args[@]}" -raw edge_public_ip 2>/dev/null || true)"
discovered_email_ip="$(tofu -chdir="${stack}" output "${tofu_state_args[@]}" -raw email_public_ip 2>/dev/null || true)"
discovered_bastion_id="$(tofu -chdir="${stack}" output "${tofu_state_args[@]}" -raw bastion_id 2>/dev/null || true)"
discovered_backup_bucket_name="$(tofu -chdir="${stack}" output "${tofu_state_args[@]}" -raw backup_bucket_name 2>/dev/null || true)"
discovered_backup_bucket_namespace="$(tofu -chdir="${stack}" output "${tofu_state_args[@]}" -raw backup_bucket_namespace 2>/dev/null || true)"
discovered_backup_bucket_id="$(tofu -chdir="${stack}" output "${tofu_state_args[@]}" -raw backup_bucket_id 2>/dev/null || true)"
discovered_monitoring_topic_id="$(tofu -chdir="${stack}" output "${tofu_state_args[@]}" -raw monitoring_topic_id 2>/dev/null || true)"
discovered_edge_instance_id="$(tofu -chdir="${stack}" output "${tofu_state_args[@]}" -raw edge_instance_id 2>/dev/null || true)"
local discovered_email_instance_id
discovered_email_instance_id="$(tofu -chdir="${stack}" output "${tofu_state_args[@]}" -raw email_instance_id 2>/dev/null || true)"
if [[ "${discovered_bastion_id}" == ocid1.bastion.* ]]; then
export LAB_OCI_BASTION_ID="${discovered_bastion_id}"
fi
if [[ "${discovered_edge_instance_id}" == ocid1.instance.* ]]; then
export LAB_OCI_EDGE_INSTANCE_ID="${discovered_edge_instance_id}"
if [[ "${LAB_OCI_COMPUTE_ENABLED:-true}" == "true" && -z "${LAB_OCI_EDGE_EXISTING_INSTANCE_ID:-}" ]]; then
export LAB_OCI_EDGE_INSTANCE_MANAGED=true
else
export LAB_OCI_EDGE_INSTANCE_MANAGED=false
fi
fi
if [[ "${discovered_email_instance_id}" == ocid1.instance.* ]]; then
export LAB_OCI_EMAIL_INSTANCE_ID="${discovered_email_instance_id}"
fi
if [[ -n "${discovered_backup_bucket_name}" && "${discovered_backup_bucket_name}" != "null" ]]; then
export LAB_OCI_BACKUP_BUCKET="${discovered_backup_bucket_name}"
export LAB_OCI_BACKUP_BUCKET_NAME="${discovered_backup_bucket_name}"
fi
if [[ -n "${discovered_backup_bucket_namespace}" && "${discovered_backup_bucket_namespace}" != "null" ]]; then
export LAB_OCI_BACKUP_BUCKET_NAMESPACE="${discovered_backup_bucket_namespace}"
fi
if [[ -n "${discovered_backup_bucket_id}" && "${discovered_backup_bucket_id}" != "null" ]]; then
export LAB_OCI_BACKUP_BUCKET_ID="${discovered_backup_bucket_id}"
fi
if [[ "${discovered_monitoring_topic_id}" == ocid1.onstopic.* ]]; then
export LAB_OCI_MONITORING_TOPIC_ID="${discovered_monitoring_topic_id}"
fi
if truthy "${LAB_OCI_BASTION_ENABLED:-true}"; then
if [[ "${discovered_edge_instance_id}" == ocid1.instance.* ]]; then
printf 'Enabling OCI Bastion plugin on edge instance...\n'
oci_enable_bastion_plugin "${discovered_edge_instance_id}" || post_apply_failures=$((post_apply_failures + 1))
fi
if [[ "${discovered_email_instance_id}" == ocid1.instance.* ]]; then
printf 'Enabling OCI Bastion plugin on email instance...\n'
oci_enable_bastion_plugin "${discovered_email_instance_id}" || post_apply_failures=$((post_apply_failures + 1))
fi
fi
if [[ -n "${discovered_edge_ip}" && "${discovered_edge_ip}" != "null" ]]; then
export LAB_EDGE_HOST="${discovered_edge_ip}"
export TF_VAR_edge_host="${discovered_edge_ip}"
update_duckdns_edge_ip "${discovered_edge_ip}" || post_apply_failures=$((post_apply_failures + 1))
if [[ "${LAB_OCI_AUTO_CONFIGURE_EDGE:-true}" == "true" ]]; then
printf 'Configuring edge services at %s...\n' "${discovered_edge_ip}"
edge_apply || post_apply_failures=$((post_apply_failures + 1))
else
printf 'Edge services not configured automatically. LAB_EDGE_HOST=%s\n' "${discovered_edge_ip}"
fi
fi
if [[ -n "${discovered_email_ip}" && "${discovered_email_ip}" != "null" ]]; then
export LAB_EMAIL_PUBLIC_IP="${discovered_email_ip}"
export LAB_OCI_EMAIL_METRICS_TARGET="${discovered_email_ip}:9100"
if truthy "${LAB_OCI_AUTO_CONFIGURE_EMAIL:-true}"; then
local email_key="${LAB_EMAIL_SSH_PRIVATE_KEY:-${HOME}/.ssh/id_ed25519}"
local email_user="${LAB_EMAIL_SSH_USER:-ubuntu}"
printf 'Waiting for email VM SSH at %s@%s...\n' "${email_user}" "${discovered_email_ip}"
if oci_wait_for_ssh "${email_user}@${discovered_email_ip}" "${email_key}" "${LAB_OCI_EMAIL_SSH_WAIT_SECONDS:-180}"; then
LAB_EMAIL_PUBLIC_IP="${discovered_email_ip}" "${REPO_ROOT}/scripts/email-server" install || post_apply_failures=$((post_apply_failures + 1))
else
post_apply_failures=$((post_apply_failures + 1))
fi
else
echo "Email baseline not configured automatically. Run ./jeannie email-vm setup."
fi
fi
if [[ -n "${discovered_edge_ip}" && "${discovered_edge_ip}" != "null" ]]; then
export LAB_OCI_EDGE_METRICS_TARGET="${discovered_edge_ip}:9100"
export LAB_OCI_EDGE_CONTAINER_METRICS_TARGET="${discovered_edge_ip}:9101"
fi
oci_foundation_save_config
if ((post_apply_failures > 0)); then
echo "OCI foundation was created, but ${post_apply_failures} post-apply configuration step(s) failed." >&2
return 1
fi
fi
rm -f "${foundation_plan}" "${foundation_json}"
flock -u "${foundation_lock}"
exec {foundation_lock}>&-
;;
destroy)
if [[ "${1:-}" != "--yes" ]]; then
echo "Refusing to destroy OCI foundation without --yes." >&2
return 2
fi
shift
record_change_journal "oci-foundation" destroy "$@"
tofu -chdir="${stack}" init
tofu -chdir="${stack}" destroy "${tofu_state_args[@]}" "$@" -auto-approve
;;
*)
echo "Usage: ./jeannie oci-foundation {verify|status|plan|review-edge-plan PLAN|apply|destroy --yes}" >&2
return 2
;;
esac
}
oci_auth_manage() {
require_debian_server "oci-auth"
"${REPO_ROOT}/scripts/oci-auth" "$@"
}
oci_bastion_ssh() {
require_debian_server "oci bastion ssh"
oci_foundation_load_config
local target_id=""
local -a bastion_args=("$@")
[[ "${bastion_args[0]:-}" == "ssh" ]] && bastion_args=("${bastion_args[@]:1}")
[[ "${bastion_args[0]:-}" == "--print-command" ]] && bastion_args=("${bastion_args[@]:1}")
target_id="${bastion_args[1]:-${LAB_OCI_TARGET_INSTANCE_ID:-${LAB_OCI_EDGE_INSTANCE_ID:-${LAB_OCI_EDGE_EXISTING_INSTANCE_ID:-}}}}"
if [[ -n "${target_id}" ]]; then
printf 'Ensuring OCI Bastion plugin is enabled on %s...\n' "${target_id}" >&2
oci_enable_bastion_plugin "${target_id}" || return 1
fi
"${REPO_ROOT}/scripts/oci-bastion-ssh" "$@"
}
oci_enable_bastion_plugin() {
local instance_id="${1:-}" oci_bin agent_config instance_json
[[ -n "${instance_id}" ]] || return 0
oci_bin="$(oci_cli_resolve)" || return 1
instance_json="$("${oci_bin}" compute instance get --instance-id "${instance_id}" --output json)" || return 1
agent_config="$(mktemp)"
if ! printf '%s' "${instance_json}" | python3 -c '
import json, sys
config = json.load(sys.stdin).get("data", {}).get("agent-config") or {}
plugins = config.get("plugins-config") or []
if any(p.get("name") == "Bastion" and p.get("desired-state") == "ENABLED" for p in plugins):
sys.exit(0)
updated = [{"name": p["name"], "desiredState": p.get("desired-state", "DISABLED")}
for p in plugins if p.get("name") != "Bastion"]
updated.append({"name": "Bastion", "desiredState": "ENABLED"})
result = {"pluginsConfig": updated}
for source, target in (("is-management-disabled", "isManagementDisabled"),
("is-monitoring-disabled", "isMonitoringDisabled"),
("are-all-plugins-disabled", "areAllPluginsDisabled")):
if config.get(source) is not None:
result[target] = config[source]
print(json.dumps(result))
' >"${agent_config}"; then
rm -f "${agent_config}"
return 1
fi
if [[ ! -s "${agent_config}" ]]; then
rm -f "${agent_config}"
return 0
fi
if ! "${oci_bin}" compute instance update --instance-id "${instance_id}" \
--agent-config "file://${agent_config}" --force >/dev/null; then
rm -f "${agent_config}"
return 1
fi
rm -f "${agent_config}"
}
oci_cli_resolve() {
if command -v oci >/dev/null 2>&1; then
command -v oci
elif [[ -x "${HOME}/.local/share/homelab/venvs/oci-cli/bin/oci" ]]; then
printf '%s\n' "${HOME}/.local/share/homelab/venvs/oci-cli/bin/oci"
else
return 1
fi
}
oci_discover_active_instance_id() {
python3 "${REPO_ROOT}/scripts/oci-foundation-resolve.py" discover \
--kind instance --name "$1" --root "$2"
}
oci_discover_vcn_id() {
python3 "${REPO_ROOT}/scripts/oci-foundation-resolve.py" discover \
--kind vcn --name "$2" --root "$1"
}
oci_discover_active_bastion_id() {
python3 "${REPO_ROOT}/scripts/oci-foundation-resolve.py" discover \
--kind bastion --name "$2" --root "$1"
}
oci_managed_edge_id() {
local state_file="${LAB_OCI_FOUNDATION_STATE_FILE:-${REPO_ROOT}/bootstrap/oci/terraform.tfstate}"
python3 -c 'import json,sys
with open(sys.argv[1]) as f: state=json.load(f)
ids=[i.get("attributes",{}).get("id") for r in state.get("resources",[]) if r.get("mode")=="managed" and r.get("type")=="oci_core_instance" and r.get("name")=="edge" for i in r.get("instances",[]) if not i.get("deposed")]
if len(ids)!=1 or not ids[0] or not ids[0].startswith("ocid1.instance."): raise SystemExit("Expected one managed edge instance in state")
print(ids[0])' "${state_file}"
}
oci_restart_edge() {
require_debian_server "oci restart-edge"
oci_foundation_load_config || return 1
if [[ $# -ne 0 ]]; then
echo "Usage: ./jeannie oci restart-edge" >&2
return 2
fi
local oci_bin edge_id instance_json lifecycle observed_id
local -a oci_options=()
oci_bin="$(oci_cli_resolve)" || { echo "OCI CLI is not installed." >&2; return 1; }
[[ -z "${LAB_OCI_CONFIG_PROFILE:-${OCI_CLI_PROFILE:-}}" ]] || oci_options+=(--profile "${LAB_OCI_CONFIG_PROFILE:-${OCI_CLI_PROFILE}}")
[[ -z "${LAB_OCI_REGION:-}" ]] || oci_options+=(--region "${LAB_OCI_REGION}")
edge_id="$(oci_managed_edge_id)" || return 1
instance_json="$("${oci_bin}" "${oci_options[@]}" compute instance get --instance-id "${edge_id}" --output json)" || return 1
observed_id="$(printf '%s' "${instance_json}" | python3 -c 'import json,sys; print(json.load(sys.stdin)["data"]["id"])')" || return 1
lifecycle="$(printf '%s' "${instance_json}" | python3 -c 'import json,sys; print(json.load(sys.stdin)["data"]["lifecycle-state"])')" || return 1
if [[ "${observed_id}" != "${edge_id}" || "${lifecycle}" != RUNNING ]]; then
echo "Refusing restart: managed edge identity or RUNNING state does not match OCI." >&2
return 1
fi
printf 'Requesting OCI SOFTRESET for managed edge %s. Public edge services will be unavailable during reboot.\n' "${edge_id}"
"${oci_bin}" "${oci_options[@]}" compute instance action --instance-id "${edge_id}" \
--action SOFTRESET --no-retry --query 'data."lifecycle-state"' --raw-output || return 1
echo "Restart request accepted. OCI RUNNING alone does not confirm a reboot or service recovery."
echo "After the edge returns, run ./jeannie oci agent-status and check the public services."
}
oci_agent_status() {
require_debian_server "oci agent-status"
oci_foundation_load_config || return 1
if [[ $# -ne 0 ]]; then
echo "Usage: ./jeannie oci agent-status" >&2
return 2
fi
local oci_bin edge_id instance_json compartment_id
local -a oci_options=()
oci_bin="$(oci_cli_resolve)" || { echo "OCI CLI is not installed." >&2; return 1; }
[[ -z "${LAB_OCI_CONFIG_PROFILE:-${OCI_CLI_PROFILE:-}}" ]] || oci_options+=(--profile "${LAB_OCI_CONFIG_PROFILE:-${OCI_CLI_PROFILE}}")
[[ -z "${LAB_OCI_REGION:-}" ]] || oci_options+=(--region "${LAB_OCI_REGION}")
edge_id="$(oci_managed_edge_id)" || return 1
instance_json="$("${oci_bin}" "${oci_options[@]}" compute instance get --instance-id "${edge_id}" --output json)" || return 1
compartment_id="$(printf '%s' "${instance_json}" | python3 -c 'import json,sys; print(json.load(sys.stdin)["data"]["compartment-id"])')" || return 1
printf 'Edge instance: %s\n' "${edge_id}"
printf '%s' "${instance_json}" | python3 -c 'import json,sys
c=json.load(sys.stdin)["data"].get("agent-config") or {}
print("All plugins disabled:", c.get("are-all-plugins-disabled"))
print("Management plugins disabled:", c.get("is-management-disabled"))
for p in c.get("plugins-config") or []:
if p.get("name") in ("Bastion", "Compute Instance Run Command"):
print("Configured:", p.get("name"), p.get("desired-state"))' || return 1
"${oci_bin}" "${oci_options[@]}" instance-agent plugin list \
--compartment-id "${compartment_id}" --instanceagent-id "${edge_id}" --output json |
python3 -c 'import json,sys
items=json.load(sys.stdin).get("data",[])
for p in items:
if p.get("name") in ("Compute Instance Run Command", "Compute Instance Monitoring", "Bastion"):
print("Observed:", p.get("name"), p.get("status"), p.get("time-last-updated-utc"))
if not any(p.get("name")=="Compute Instance Run Command" and p.get("status")=="RUNNING" for p in items):
print("Run Command is not confirmed running; guest watchdog cannot repair a missing agent or OCI connectivity.")
sys.exit(1)'
}
oci_status() {
require_debian_server "oci status"
oci_foundation_load_config
local oci_bin tenancy compartment region
oci_bin="$(oci_cli_resolve)" || {
echo "OCI CLI is not installed. Run ./jeannie oci-auth install." >&2
return 2
}
tenancy="${LAB_OCI_TENANCY_ID:-}"
compartment="${LAB_OCI_COMPARTMENT_ID:-${tenancy}}"
region="${LAB_OCI_REGION:-${OCI_CLI_REGION:-unknown}}"
[[ -n "${tenancy}" ]] || {
echo "OCI tenancy is not configured. Run ./jeannie oci-auth init or set LAB_OCI_TENANCY_ID." >&2
return 2
}
printf '%s\n' '== OCI status =='
printf 'region=%s profile=%s config=%s\n' "${region}" "${OCI_CLI_PROFILE:-DEFAULT}" "${OCI_CLI_CONFIG_FILE:-${HOME}/.oci/config}"
printf '%s\n' '-- compartments'
"${oci_bin}" iam compartment list --compartment-id "${tenancy}" \
--compartment-id-in-subtree true --all \
--query 'data[].{NAME:name,ID:id,STATE:"lifecycle-state"}' --output table 2>/dev/null || echo 'unavailable'
local compartment_ids resource_compartments current_compartment
compartment_ids="$("${oci_bin}" iam compartment list --compartment-id "${tenancy}" \
--compartment-id-in-subtree true --all --output json 2>/dev/null \
| python3 -c 'import json,sys; print("\n".join(x["id"] for x in json.load(sys.stdin).get("data", [])))' 2>/dev/null || true)"
resource_compartments="${tenancy}"$'\n'"${compartment_ids}"
printf '%s\n' '-- compute instances (all compartments)'
while IFS= read -r current_compartment; do
[[ -n "${current_compartment}" ]] || continue
printf 'compartment=%s\n' "${current_compartment}"
"${oci_bin}" compute instance list --compartment-id "${current_compartment}" --all \
--query 'data[].{NAME:"display-name",SHAPE:shape,STATE:"lifecycle-state",AD:"availability-domain",ID:id}' \
--output table 2>/dev/null || echo 'unavailable'
done <<<"${resource_compartments}"
printf '%s\n' '-- networking (all compartments)'
while IFS= read -r current_compartment; do
[[ -n "${current_compartment}" ]] || continue
printf 'compartment=%s\n' "${current_compartment}"
"${oci_bin}" network vcn list --compartment-id "${current_compartment}" --all \
--query 'data[].{NAME:"display-name",CIDR:"cidr-block",STATE:"lifecycle-state",ID:id}' \
--output table 2>/dev/null || echo 'unavailable'
"${oci_bin}" network subnet list --compartment-id "${current_compartment}" --all \
--query 'data[].{NAME:"display-name",CIDR:"cidr-block",NO_PUBLIC_IP:"prohibit-public-ip-on-vnic",STATE:"lifecycle-state",ID:id}' \
--output table 2>/dev/null || echo 'unavailable'
done <<<"${resource_compartments}"
printf '%s\n' '-- boot volumes (all compartments)'
while IFS= read -r current_compartment; do
[[ -n "${current_compartment}" ]] || continue
printf 'compartment=%s\n' "${current_compartment}"
"${oci_bin}" bv boot-volume list --compartment-id "${current_compartment}" --all \
--query 'data[].{NAME:"display-name",SIZE_GB:"size-in-gbs",STATE:"lifecycle-state",AD:"availability-domain",ID:id}' \
--output table 2>/dev/null || echo 'unavailable'
done <<<"${resource_compartments}"
printf '%s\n' '-- bastions (all compartments)'
while IFS= read -r current_compartment; do
[[ -n "${current_compartment}" ]] || continue
printf 'compartment=%s\n' "${current_compartment}"
"${oci_bin}" bastion bastion list --compartment-id "${current_compartment}" --all \
--query 'data[].{NAME:name,TYPE:"bastion-type",STATE:"lifecycle-state",TARGET_SUBNET:"target-subnet-id",ID:id}' \
--output table 2>/dev/null || echo 'unavailable'
done <<<"${resource_compartments}"
printf '%s\n' '-- service limits'
"${oci_bin}" limits service list --compartment-id "${tenancy}" --all \
--query 'data[].{NAME:name,DESCRIPTION:description}' --output table 2>/dev/null || echo 'unavailable'
printf '%s\n' '-- quotas'
while IFS= read -r current_compartment; do
[[ -n "${current_compartment}" ]] || continue
printf 'compartment=%s\n' "${current_compartment}"
"${oci_bin}" limits quota list --compartment-id "${current_compartment}" --all \
--query 'data[].{NAME:name,STATE:"lifecycle-state",STATEMENTS:statements}' --output table 2>/dev/null || echo 'unavailable'
done <<<"${resource_compartments}"
}
oci_doctor() {
require_debian_server "oci doctor"
oci_foundation_load_config
local oci_bin tenancy compartment region failures=0 states bad_state
oci_bin="$(oci_cli_resolve)" || {
echo 'FAIL OCI CLI is not installed; run ./jeannie oci-auth install.'
return 1
}
tenancy="${LAB_OCI_TENANCY_ID:-}"
compartment="${LAB_OCI_COMPARTMENT_ID:-${tenancy}}"
region="${LAB_OCI_REGION:-${OCI_CLI_REGION:-}}"
if [[ -z "${tenancy}" || -z "${region}" ]]; then
echo 'FAIL OCI tenancy/region is not configured.'
return 1
fi
if "${oci_bin}" iam region list --region "${region}" >/dev/null 2>&1; then
printf 'PASS OCI authentication and region: %s\n' "${region}"
else
echo 'FAIL OCI authentication or region access'
failures=$((failures + 1))
fi
if "${oci_bin}" iam compartment get --compartment-id "${compartment}" >/dev/null 2>&1; then
printf 'PASS compartment accessible: %s\n' "${compartment}"
else
echo 'FAIL configured compartment is not accessible'
failures=$((failures + 1))
fi
states="$("${oci_bin}" compute instance list --compartment-id "${compartment}" --all \
--output json 2>/dev/null \
| python3 -c 'import json,sys; print("\n".join(x["lifecycle-state"] for x in json.load(sys.stdin).get("data", [])))' 2>/dev/null || true)"
if [[ -n "${states}" ]]; then
bad_state="$(printf '%s\n' "${states}" | grep -Ev '^(RUNNING|STOPPED|STOPPING|STARTING|TERMINATED|TERMINATING|PROVISIONING)$' || true)"
if [[ -n "${bad_state}" ]]; then
printf 'FAIL instance lifecycle states: %s\n' "${bad_state//$'\n'/, }"
failures=$((failures + 1))
else
printf 'PASS compute instances have known lifecycle states (%s listed)\n' "$(printf '%s\n' "${states}" | sed '/^$/d' | wc -l | tr -d ' ')"
fi
else
echo 'WARN no compute instances found or instance listing unavailable'
fi
local id label
for label in edge_instance vcn public_subnet email_subnet; do
case "${label}" in
edge_instance) id="${LAB_OCI_EDGE_EXISTING_INSTANCE_ID:-}"; [[ -n "${id}" ]] && "${oci_bin}" compute instance get --instance-id "${id}" >/dev/null 2>&1 && printf 'PASS %s exists\n' "${label}" || [[ -z "${id}" ]] || { printf 'FAIL %s is missing\n' "${label}"; failures=$((failures + 1)); } ;;
vcn) id="${LAB_OCI_EXISTING_VCN_ID:-}"; [[ -n "${id}" ]] && "${oci_bin}" network vcn get --vcn-id "${id}" >/dev/null 2>&1 && printf 'PASS %s exists\n' "${label}" || [[ -z "${id}" ]] || { printf 'FAIL %s is missing\n' "${label}"; failures=$((failures + 1)); } ;;
public_subnet) id="${LAB_OCI_EXISTING_PUBLIC_SUBNET_ID:-}"; [[ -n "${id}" ]] && "${oci_bin}" network subnet get --subnet-id "${id}" >/dev/null 2>&1 && printf 'PASS %s exists\n' "${label}" || [[ -z "${id}" ]] || { printf 'FAIL %s is missing\n' "${label}"; failures=$((failures + 1)); } ;;
email_subnet) id="${LAB_OCI_EXISTING_EMAIL_SUBNET_ID:-}"; [[ -n "${id}" ]] && "${oci_bin}" network subnet get --subnet-id "${id}" >/dev/null 2>&1 && printf 'PASS %s exists\n' "${label}" || [[ -z "${id}" ]] || { printf 'FAIL %s is missing\n' "${label}"; failures=$((failures + 1)); } ;;
esac
done
if "${oci_bin}" limits service list --compartment-id "${tenancy}" --all >/dev/null 2>&1; then
echo 'PASS OCI service limits are readable'
else
echo 'FAIL OCI service limits are not readable'
failures=$((failures + 1))
fi
if "${oci_bin}" limits quota list --compartment-id "${tenancy}" --all >/dev/null 2>&1; then
echo 'PASS OCI quotas are readable'
else
echo 'WARN OCI quota listing is unavailable or unsupported for this tenancy'
fi
if ((failures > 0)); then
printf 'OCI doctor: FAIL (%d check(s))\n' "${failures}"
return 1
fi
echo 'OCI doctor: PASS'
}
oci_cleanup() {
require_debian_server "oci cleanup"
oci_foundation_load_config
if [[ "${1:-}" == apply ]]; then
record_change_journal "oci-cleanup" "$@"
fi
"${REPO_ROOT}/scripts/oci-cleanup" "$@"
}
repo_sync() {
require_debian_server "repo-sync"
record_change_journal "repo-sync" "$@"
"${REPO_ROOT}/scripts/repo-sync" "$@"
}
storage_status() {
require_debian_server "storage"
local kubeconfig="${KUBECONFIG_PATH}"
printf '%s\n' '== Kubernetes storage =='
printf '%s\n' '-- node pressure and capacity'
kubectl --kubeconfig "${kubeconfig}" get nodes \
-o custom-columns='NAME:.metadata.name,READY:.status.conditions[?(@.type=="Ready")].status,DISK_PRESSURE:.status.conditions[?(@.type=="DiskPressure")].status,EPHEMERAL:.status.capacity.ephemeral-storage' \
2>/dev/null || true
printf '%s\n' '-- persistent volume claims'
kubectl --kubeconfig "${kubeconfig}" get pvc -A \
-o custom-columns='NAMESPACE:.metadata.namespace,NAME:.metadata.name,STATUS:.status.phase,REQUEST:.spec.resources.requests.storage,CAPACITY:.status.capacity.storage,STORAGECLASS:.spec.storageClassName,VOLUME:.spec.volumeName' \
2>/dev/null || true
printf '%s\n' '-- PVC capacity conditions'
kubectl --kubeconfig "${kubeconfig}" get pvc -A \
-o custom-columns='NAMESPACE:.metadata.namespace,NAME:.metadata.name,PHASE:.status.phase,REQUEST:.spec.resources.requests.storage,CAPACITY:.status.capacity.storage,RESIZE:.status.conditions[?(@.type=="Resizing")].status,EXPAND:.status.conditions[?(@.type=="FileSystemResizePending")].status' \
2>/dev/null || true
printf '%s\n' '-- persistent volumes'
kubectl --kubeconfig "${kubeconfig}" get pv \
-o custom-columns='NAME:.metadata.name,STATUS:.status.phase,CAPACITY:.spec.capacity.storage,CLAIM:.spec.claimRef.namespace/.spec.claimRef.name,STORAGECLASS:.spec.storageClassName,RECLAIM:.spec.persistentVolumeReclaimPolicy' \
2>/dev/null || true
printf '%s\n' '-- storage classes'
kubectl --kubeconfig "${kubeconfig}" get storageclass \
-o custom-columns='NAME:.metadata.name,PROVISIONER:.provisioner,DEFAULT:.metadata.annotations.storageclass\.kubernetes\.io/is-default-class,RECLAIM:.reclaimPolicy,VOLUME_BINDING:.volumeBindingMode' \
2>/dev/null || true
if kubectl --kubeconfig "${kubeconfig}" get namespace openebs >/dev/null 2>&1; then
printf '%s\n' '-- OpenEBS'
kubectl --kubeconfig "${kubeconfig}" -n openebs get pods -o wide 2>/dev/null || true
kubectl --kubeconfig "${kubeconfig}" -n openebs get storagepoolcluster 2>/dev/null || true
kubectl --kubeconfig "${kubeconfig}" get blockdevice -A \
-o custom-columns='NAMESPACE:.metadata.namespace,NAME:.metadata.name,NODE:.spec.nodeAttributes.nodeName,CLAIMED:.status.claimState,SIZE:.spec.capacity.storage,STATE:.status.state' \
2>/dev/null || true
else
printf '%s\n' '-- OpenEBS: namespace not present'
fi
printf '%s\n' '-- Pimox storage'
check_pimox_storage || printf '%s\n' 'Pimox storage check failed or is unavailable.'
}
storage_size_bytes() {
local value="${1:-}"
local number unit multiplier
if [[ ! "${value}" =~ ^([0-9]+)(Mi|Gi|Ti)$ ]]; then
return 1
fi
number="${BASH_REMATCH[1]}"
unit="${BASH_REMATCH[2]}"
case "${unit}" in
Mi) multiplier=$((1024 ** 2)) ;;
Gi) multiplier=$((1024 ** 3)) ;;
Ti) multiplier=$((1024 ** 4)) ;;
esac
printf '%s\n' $((number * multiplier))
}
storage_manage() {
local action="${1:-status}"
shift || true
local kubeconfig="${KUBECONFIG_PATH}"
local pvc_ref=""
local size=""
local snapshot_name=""
local yes=false
local namespace
local pvc
local current
local current_bytes
local requested_bytes
case "${action}" in
status)
storage_status
;;
cleanup)
require_debian_server "storage cleanup"
echo "Running the existing worker disk cleanup tool..."
"${REPO_ROOT}/scripts/workers" disk-cleanup
;;
snapshot)
local snapshot_action="create"
local snapshot_ref=""
local storage_class=""
local restore_size=""
if [[ "${1:-}" == "create" || "${1:-}" == "delete" || "${1:-}" == "restore" ]]; then
snapshot_action="$1"
shift
fi
while (($# > 0)); do
case "$1" in
--pvc) pvc_ref="${2:-}"; shift 2 ;;
--name) snapshot_name="${2:-}"; shift 2 ;;
--snapshot) snapshot_ref="${2:-}"; shift 2 ;;
--size) restore_size="${2:-}"; shift 2 ;;
--storage-class) storage_class="${2:-}"; shift 2 ;;
--yes) yes=true; shift ;;
*) echo "Usage: ./jeannie storage snapshot {create|delete|restore} ..." >&2; return 2 ;;
esac
done
if ! kubectl --kubeconfig "${kubeconfig}" get crd volumesnapshots.snapshot.storage.k8s.io >/dev/null 2>&1; then
echo "VolumeSnapshot CRD is not installed; no snapshot was created." >&2
return 1
fi
case "${snapshot_action}" in
create)
if [[ ! "${pvc_ref}" =~ ^([a-z0-9-]+)/([a-z0-9-]+)$ || ! "${snapshot_name}" =~ ^[a-z0-9]([-a-z0-9]*[a-z0-9])?$ ]]; then
echo "Usage: ./jeannie storage snapshot create --pvc NAMESPACE/PVC --name SNAPSHOT [--yes]" >&2
return 2
fi
namespace="${pvc_ref%%/*}"
pvc="${pvc_ref#*/}"
kubectl --kubeconfig "${kubeconfig}" -n "${namespace}" get pvc "${pvc}" >/dev/null
if [[ "${yes}" != true ]]; then
echo "Would snapshot ${namespace}/${pvc} as ${snapshot_name}. Re-run with --yes to apply."
return 0
fi
kubectl --kubeconfig "${kubeconfig}" -n "${namespace}" apply -f - <<EOF
apiVersion: snapshot.storage.k8s.io/v1
kind: VolumeSnapshot
metadata:
name: ${snapshot_name}
spec:
source:
persistentVolumeClaimName: ${pvc}
EOF
;;
delete)
if [[ ! "${snapshot_ref}" =~ ^([a-z0-9-]+)/([a-z0-9-]+)$ ]]; then
echo "Usage: ./jeannie storage snapshot delete --snapshot NAMESPACE/SNAPSHOT [--yes]" >&2
return 2
fi
namespace="${snapshot_ref%%/*}"
snapshot_name="${snapshot_ref#*/}"
kubectl --kubeconfig "${kubeconfig}" -n "${namespace}" get volumesnapshot "${snapshot_name}" >/dev/null
if [[ "${yes}" != true ]]; then
echo "Would delete VolumeSnapshot ${namespace}/${snapshot_name}. Re-run with --yes to apply."
return 0
fi
kubectl --kubeconfig "${kubeconfig}" -n "${namespace}" delete volumesnapshot "${snapshot_name}"
;;
restore)
if [[ ! "${snapshot_ref}" =~ ^([a-z0-9-]+)/([a-z0-9-]+)$ || ! "${pvc_ref}" =~ ^([a-z0-9-]+)/([a-z0-9-]+)$ || ! "${restore_size}" =~ ^[0-9]+(Mi|Gi|Ti)$ ]]; then
echo "Usage: ./jeannie storage snapshot restore --snapshot NAMESPACE/SNAPSHOT --pvc NAMESPACE/PVC --size SIZE [--storage-class CLASS] [--yes]" >&2
return 2
fi
local snapshot_namespace="${snapshot_ref%%/*}"
local snapshot_resource="${snapshot_ref#*/}"
namespace="${pvc_ref%%/*}"
pvc="${pvc_ref#*/}"
if [[ "${snapshot_namespace}" != "${namespace}" ]]; then
echo "Snapshot and restored PVC must be in the same namespace (${snapshot_namespace} != ${namespace})." >&2
return 1
fi
kubectl --kubeconfig "${kubeconfig}" -n "${snapshot_namespace}" get volumesnapshot "${snapshot_resource}" >/dev/null
if [[ "$(kubectl --kubeconfig "${kubeconfig}" -n "${snapshot_namespace}" get volumesnapshot "${snapshot_resource}" -o jsonpath='{.status.readyToUse}' 2>/dev/null)" != "true" ]]; then
echo "VolumeSnapshot ${snapshot_namespace}/${snapshot_resource} is not ready to use." >&2
return 1
fi
if kubectl --kubeconfig "${kubeconfig}" -n "${namespace}" get pvc "${pvc}" >/dev/null 2>&1; then
echo "Target PVC ${namespace}/${pvc} already exists." >&2
return 1
fi
if [[ "${yes}" != true ]]; then
echo "Would restore ${snapshot_namespace}/${snapshot_resource} to PVC ${namespace}/${pvc} (${restore_size}). Re-run with --yes to apply."
return 0
fi
kubectl --kubeconfig "${kubeconfig}" -n "${namespace}" apply -f - <<EOF
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: ${pvc}
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: ${restore_size}
dataSource:
name: ${snapshot_resource}
kind: VolumeSnapshot
apiGroup: snapshot.storage.k8s.io
$(if [[ -n "${storage_class}" ]]; then printf ' storageClassName: %s\n' "${storage_class}"; fi)
EOF
;;
esac
;;
expand)
local storage_class_name
local allow_expansion
while (($# > 0)); do
case "$1" in
--pvc) pvc_ref="${2:-}"; shift 2 ;;
--size) size="${2:-}"; shift 2 ;;
--yes) yes=true; shift ;;
*) echo "Usage: ./jeannie storage expand --pvc NAMESPACE/PVC --size SIZE [--yes]" >&2; return 2 ;;
esac
done
if [[ ! "${pvc_ref}" =~ ^([^/]+)/([^/]+)$ ]]; then
echo "Usage: ./jeannie storage expand --pvc NAMESPACE/PVC --size SIZE [--yes]" >&2
return 2
fi
namespace="${BASH_REMATCH[1]}"
pvc="${BASH_REMATCH[2]}"
if [[ ! "${size}" =~ ^[0-9]+(Mi|Gi|Ti)$ ]]; then
echo "Usage: ./jeannie storage expand --pvc NAMESPACE/PVC --size SIZE [--yes]" >&2
return 2
fi
current="$(kubectl --kubeconfig "${kubeconfig}" -n "${namespace}" get pvc "${pvc}" -o jsonpath='{.spec.resources.requests.storage}')"
if [[ -z "${current}" ]]; then
echo "PVC ${namespace}/${pvc} was not found or has no storage request." >&2
return 1
fi
storage_class_name="$(kubectl --kubeconfig "${kubeconfig}" -n "${namespace}" get pvc "${pvc}" -o jsonpath='{.spec.storageClassName}')"
if [[ -z "${storage_class_name}" ]]; then
echo "PVC ${namespace}/${pvc} has no StorageClass; expansion is unsafe." >&2
return 1
fi
allow_expansion="$(kubectl --kubeconfig "${kubeconfig}" get storageclass "${storage_class_name}" -o jsonpath='{.allowVolumeExpansion}')"
if [[ "${allow_expansion}" != true ]]; then
echo "StorageClass ${storage_class_name} does not allow volume expansion." >&2
return 1
fi
current_bytes="$(storage_size_bytes "${current}")" || {
echo "Current PVC size ${current} is not supported for safe comparison." >&2
return 1
}
requested_bytes="$(storage_size_bytes "${size}")" || return 1
if (( requested_bytes <= current_bytes )); then
echo "Requested size ${size} must be larger than current size ${current}." >&2
return 1
fi
if [[ "${yes}" != true ]]; then
echo "Would request expansion of ${namespace}/${pvc}: ${current} -> ${size} (StorageClass ${storage_class_name}, expansion enabled). Re-run with --yes to apply."
return 0
fi
kubectl --kubeconfig "${kubeconfig}" -n "${namespace}" patch pvc "${pvc}" --type merge -p "{\"spec\":{\"resources\":{\"requests\":{\"storage\":\"${size}\"}}}}"
;;
rebalance)
if (($# > 0)); then
echo "Storage rebalance accepts no mutation flags; it is intentionally plan-only." >&2
return 2
fi
echo "Storage rebalance is plan-only: OpenEBS LocalPV volumes are node-local and cannot be moved safely by a generic command."
kubectl --kubeconfig "${kubeconfig}" get pv -o wide 2>/dev/null || true
kubectl --kubeconfig "${kubeconfig}" get blockdevice -A \
-o custom-columns='NAMESPACE:.metadata.namespace,NAME:.metadata.name,NODE:.spec.nodeAttributes.nodeName,CLAIMED:.status.claimState,SIZE:.spec.capacity.storage,STATE:.status.state' \
2>/dev/null || true
echo "Use an explicit migration plan after identifying the owning workload and a target node."
;;
*)
echo "Usage: ./jeannie storage {status|cleanup|snapshot|expand|rebalance}" >&2
return 2
;;
esac
}
mesh_doctor() {
require_debian_server "mesh doctor"
local format=""
if [[ "${1:-}" == "doctor" ]]; then
shift
fi
if [[ "${1:-}" == "--json" ]]; then
format="--json"
shift
fi
if [[ $# -gt 0 ]]; then
echo "Usage: ./jeannie mesh doctor [--json]" >&2
return 2
fi
"${REPO_ROOT}/scripts/mesh-doctor" ${format}
}
cert_check() {
"${REPO_ROOT}/scripts/cert-check"
}
release_snapshot() {
require_debian_server "release-snapshot"
"${REPO_ROOT}/scripts/release-snapshot"
}
backup_status() {
require_debian_server "backup-status"
"${REPO_ROOT}/scripts/backup-status"
}
backup_oci() {
require_debian_server "backup oci"
oci_foundation_load_config
"${REPO_ROOT}/scripts/oci-backup" "${1:-status}"
}
install_homelab_backup_timer() {
local service_file="/etc/systemd/system/homelab-profile-backup.service"
local timer_file="/etc/systemd/system/homelab-profile-backup.timer"
local env_file="/etc/default/homelab-profile-backup"
local kubeconfig="${KUBECONFIG_PATH:-/home/jv/.kube/pimox-config}"
local offsite_uri="${HOMELAB_BACKUP_OFFSITE_URI:-}"
local tmp_env
if [[ "${HOMELAB_BACKUP_SKIP_OFFSITE:-false}" != "true" && -z "${offsite_uri}" && -e "${env_file}" ]]; then
offsite_uri="$(sudo awk -F= '$1 == "HOMELAB_BACKUP_OFFSITE_URI" { print substr($0, index($0, "=") + 1); exit }' "${env_file}" 2>/dev/null || true)"
fi
if [[ "${HOMELAB_BACKUP_SKIP_OFFSITE:-false}" == "true" ]]; then
offsite_uri=""
fi
tmp_env="$(mktemp)"
{
cat <<ENV_EOT
# Optional offsite target examples:
# HOMELAB_BACKUP_OFFSITE_URI=file:///mnt/git-backups/homelab-profile
# HOMELAB_BACKUP_OFFSITE_URI=ssh://ubuntu@100.118.255.19/mnt/git-backups/homelab-profile
KUBECONFIG_PATH=${kubeconfig}
ENV_EOT
if [[ -n "${offsite_uri}" ]]; then
printf 'HOMELAB_BACKUP_OFFSITE_URI=%s\n' "${offsite_uri}"
fi
} >"${tmp_env}"
sudo install -m 0640 -o root -g root "${tmp_env}" "${env_file}"
rm -f "${tmp_env}"
if [[ -n "${offsite_uri}" && "${HOMELAB_BACKUP_SKIP_OFFSITE:-false}" != "true" ]]; then
export HOMELAB_BACKUP_OFFSITE_URI="${offsite_uri}"
fi
sudo tee "${service_file}" >/dev/null <<SERVICE_EOT
[Unit]
Description=Run Homelab Pimox-aware encrypted profile backup
After=network-online.target
Wants=network-online.target
[Service]
Type=oneshot
User=$(id -un)
Environment=JEANNIE_SERVICE_CONTEXT=true
EnvironmentFile=-${env_file}
WorkingDirectory=${REPO_ROOT}
ExecStart=${REPO_ROOT}/jeannie backup
SERVICE_EOT
sudo tee "${timer_file}" >/dev/null <<'TIMER_EOT'
[Unit]
Description=Run daily Homelab encrypted profile backups
[Timer]
OnCalendar=*-*-* 03:20:00
RandomizedDelaySec=25m
Persistent=true
[Install]
WantedBy=timers.target
TIMER_EOT
sudo systemctl daemon-reload
sudo systemctl enable --now homelab-profile-backup.timer >/dev/null
}
homelab_backup() {
require_debian_server "backup"
ensure_sops_age_tools
install_homelab_backup_timer
install_gitea_backup_timer
sudo /usr/local/sbin/homelab-gitea-backup.sh
sudo /usr/local/sbin/homelab-gitea-restore-drill.sh
backup_tofu_state
"${REPO_ROOT}/scripts/homelab-backup" pimox-profile
}
synthetic_checks() {
require_debian_server "synthetic-checks"
"${REPO_ROOT}/scripts/synthetic-checks"
}
resource_budget() {
require_debian_server "resource-budget"
"${REPO_ROOT}/scripts/resource-budget" "${@:2}"
}
capacity_advisor() {
require_debian_server "capacity-advisor"
"${REPO_ROOT}/scripts/capacity-advisor" "${@:2}"
}
capacity_limits() {
require_debian_server "capacity-limits"
"${REPO_ROOT}/scripts/capacity-limits" "${@:2}"
}
control_plane() {
require_debian_server "control-plane"
"${REPO_ROOT}/scripts/control-plane" "${@:2}"
}
artifact_cache() {
require_debian_server "artifact-cache"
"${REPO_ROOT}/scripts/artifact-cache" "${@:2}"
}
blockchain_devnet() {
require_debian_server "blockchain-devnet"
"${REPO_ROOT}/scripts/blockchain-devnet" "${@:2}"
}
blockchain_test() {
"${REPO_ROOT}/scripts/blockchain-test" "${@:2}"
}
blockchain_wallet() {
"${REPO_ROOT}/scripts/blockchain-wallet" "${@:2}"
}
golden_ledger() {
"${REPO_ROOT}/scripts/golden-ledger" "${@:2}"
}
route_inventory() {
require_debian_server "route-inventory"
"${REPO_ROOT}/scripts/route-inventory"
}
explain() {
if [ "${2:-}" != "output" ]; then
require_debian_server "explain"
fi
"${REPO_ROOT}/scripts/explain" "${@:2}"
}
recover_power() {
require_debian_server "recover-power"
record_change_journal "recover-power" "$@"
"${REPO_ROOT}/scripts/recover-power" "${@:2}"
}
scorecard() {
require_debian_server "scorecard"
"${REPO_ROOT}/scripts/scorecard"
}
grafana_dashboards() {
require_debian_server "grafana-dashboards"
"${REPO_ROOT}/scripts/grafana-dashboards" "${@:2}"
}
workers_manage() {
require_debian_server "workers"
"${REPO_ROOT}/scripts/workers" "${@:2}"
}
record_change_journal() {
local command_name="$1"
shift || true
"${REPO_ROOT}/scripts/change-journal" append "${command_name}" "$*" || true
}
change_journal() {
"${REPO_ROOT}/scripts/change-journal" "${@:2}"
}
homelab_map() {
"${REPO_ROOT}/scripts/homelab-map" "${@:2}"
}