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

9638 lines
383 KiB
Bash

#!/usr/bin/env bash
# shellcheck disable=SC2034,SC2043,SC2140
# Keep one inventory loader and Terraform variable exporter for every caller.
# shellcheck source=lib/jeannie/env.sh
source "${BASH_SOURCE[0]%/*}/env.sh"
configure_platform_grafana_sso() {
local namespace="${TF_VAR_grafana_namespace:-monitoring}"
local secret_name="${TF_VAR_grafana_oauth_secret_name:-grafana-dex-oauth}"
if command -v kubectl >/dev/null 2>&1 &&
kubectl --kubeconfig "${KUBECONFIG_PATH}" -n "${namespace}" get secret "${secret_name}" >/dev/null 2>&1; then
export TF_VAR_grafana_sso_enabled=true
else
export TF_VAR_grafana_sso_enabled=false
fi
}
monitoring_exporter_install() {
local root="$1"
install -m 755 "${REPO_ROOT}/scripts/monitoring-exporter-access.py" "${root}/monitoring-exporter-access.py" || return 1
install -m 755 "${REPO_ROOT}/scripts/monitoring-host-exporter.sh" "${root}/monitoring-host-exporter.sh" || return 1
install -m 644 "${REPO_ROOT}/scripts/oci-foundation-resolve.py" "${root}/oci-foundation-resolve.py" || return 1
# The canonical name allowlist is declared in commands.sh before dispatch.
# shellcheck disable=SC2154
MONITORING_OCI_CLI="${OCI_CLI_BIN:-${HOME}/.local/share/homelab/venvs/oci-cli/bin/oci}" \
MONITORING_EMAIL_KEY="${LAB_EMAIL_SSH_PRIVATE_KEY:-${HOME}/.ssh/id_ed25519}" \
MONITORING_EMAIL_USER="${LAB_EMAIL_SSH_USER:-ubuntu}" \
python3 - "${root}" "$(oci_foundation_config_file)" "${oci_foundation_config_names[@]}" <<'PYEXPORT'
import json, os, pathlib, sys
path = pathlib.Path(sys.argv[1]) / 'exporter-settings.json'
settings = dict(config=sys.argv[2], names=sys.argv[3:], cli=os.environ['MONITORING_OCI_CLI'],
ssh_key=os.environ['MONITORING_EMAIL_KEY'], ssh_user=os.environ['MONITORING_EMAIL_USER'])
path.write_text(json.dumps(settings, indent=2))
path.chmod(0o600)
PYEXPORT
}
monitoring_exporters() {
require_debian_server "monitoring exporters"
record_change_journal monitoring-exporters
local root="${LAB_MONITORING_INSTALL_DIR:-/data/homelab-monitoring}"
sudo -n install -d -m 750 -o "$(id -un)" -g "$(id -gn)" "${root}" || return 1
monitoring_exporter_install "${root}" || return 1
flock -n "${root}/.lock" python3 "${root}/monitoring-exporter-access.py" reconcile --root "${root}"
}
monitoring_debian() {
local action="${1:-status}" root="${LAB_MONITORING_INSTALL_DIR:-/data/homelab-monitoring}"
require_debian_server "monitoring"
case "${action}" in
exporters) monitoring_exporters; return $? ;;
plan)
echo "Move Prometheus, Alertmanager, Grafana and enabled Loki to ${root} on Debian; preserve PVCs, database, dashboards and Dex."
echo "Keep the Operator and exporters in K3s; refresh rules, discovery credentials and dashboards every five minutes."
return 0 ;;
status|validate)
python3 "${REPO_ROOT}/scripts/monitoring-debian.py" "${action}" --root "${root}"
return $? ;;
migrate|apply|refresh) ;;
*) echo 'Usage: ./jeannie monitoring {plan|migrate|apply|refresh|exporters|status|validate}' >&2; return 2 ;;
esac
cluster_context_require || return 1
record_change_journal "monitoring-${action}" "$@"
sudo -n install -d -m 750 -o "$(id -un)" -g "$(id -gn)" "${root}" || return 1
install -m 644 "${REPO_ROOT}/scripts/monitoring-loki.py" "${root}/monitoring-loki.py" || return 1
install -m 755 "${REPO_ROOT}/scripts/monitoring-debian.py" "${root}/manager.py" || return 1
install -m 755 "${REPO_ROOT}/scripts/monitoring-helm-postrender.py" "${root}/postrender.py" || return 1
install -m 640 "${REPO_ROOT}/infra/monitoring-debian/compose.yaml" "${root}/compose.yaml" || return 1
install -m 644 "${REPO_ROOT}/infra/monitoring-debian/loki.Dockerfile" "${root}/loki.Dockerfile" || return 1
monitoring_exporter_install "${root}" || return 1
LAB_MONITORING_EXTERNAL_LOKI="${LAB_MONITORING_EXTERNAL_LOKI:-false}" \
MONITORING_ROOT="${root}" LAB_DEBIAN_LAN_IP="${LAB_DEBIAN_LAN_IP}" \
LAB_PIMOX_HOST="${LAB_PIMOX_HOST}" LAB_PIMOX_USER="${LAB_PIMOX_USER}" \
LAB_MONITORING_SERVICE_CIDR="${LAB_MONITORING_SERVICE_CIDR:-10.43.0.0/16}" python3 - <<'PY' || return 1
import base64, ipaddress, json, os, pathlib, subprocess
root = pathlib.Path(os.environ['MONITORING_ROOT'])
if not (root / 'settings.json').exists():
kubeconfig = os.environ['KUBECONFIG_PATH']
base = ['kubectl', '--kubeconfig', kubeconfig, '--request-timeout=15s']
def get(args): return json.loads(subprocess.check_output(base + args))
config = get(['config', 'view', '--raw', '--minify', '-o', 'json'])['clusters'][0]['cluster']
ca = config.get('certificate-authority-data')
if not ca:
ca = base64.b64encode(pathlib.Path(config['certificate-authority']).read_bytes()).decode()
pools = get(['get', 'ippools.crd.projectcalico.org', '-o', 'json'])['items']
networks = [p['spec']['cidr'] for p in pools if ':' not in p['spec']['cidr']]
service_cidr = os.environ.get('LAB_MONITORING_SERVICE_CIDR', '10.43.0.0/16')
dns = get(['-n', 'kube-system', 'get', 'service', 'kube-dns', '-o', 'json'])['spec']['clusterIP']
if ipaddress.ip_address(dns) not in ipaddress.ip_network(service_cidr):
raise SystemExit('Declared service CIDR does not contain the cluster DNS address')
settings = dict(kubeconfig=kubeconfig, api=config['server'], ca=ca,
cluster_uid=get(['get', 'namespace', 'kube-system', '-o', 'json'])['metadata']['uid'],
debian_ip=os.environ['LAB_DEBIAN_LAN_IP'], node_ip=os.environ['LAB_PIMOX_HOST'],
node_ssh=os.environ['LAB_PIMOX_USER'] + '@' + os.environ['LAB_PIMOX_HOST'],
networks=networks + [service_cidr], user=os.environ['USER'], home=os.environ['HOME'])
(root / 'settings.json').write_text(json.dumps(settings, indent=2))
(root / 'settings.json').chmod(0o600)
settings = json.loads((root / 'settings.json').read_text())
settings['loki_enabled'] = os.environ['LAB_MONITORING_EXTERNAL_LOKI'].lower() in ('true', '1', 'yes')
(root / 'settings.json').write_text(json.dumps(settings, indent=2))
PY
python3 "${root}/manager.py" "${action}" --root "${root}" || return 1
if [[ "${action}" == migrate ]]; then
local TF_VAR_edge_config_only=true
export TF_VAR_edge_config_only
edge_apply || return 1
curl -fsS --max-time 20 "https://grafana.${LAB_DOMAIN}/api/health" || return 1
fi
}
configure_platform_argocd_sso() {
export TF_VAR_argocd_public_url="${LAB_ARGOCD_PUBLIC_URL:-https://argocd.${LAB_DOMAIN:-lab2025.duckdns.org}}"
if command -v kubectl >/dev/null 2>&1 &&
kubectl --kubeconfig "${KUBECONFIG_PATH}" -n "${LAB_ARGOCD_NAMESPACE:-argocd}" get secret argocd-dex-oauth >/dev/null 2>&1; then
export TF_VAR_argocd_sso_enabled=true
else
export TF_VAR_argocd_sso_enabled=false
fi
}
configure_platform_tetragon_capabilities() {
local enabled
enabled="$(python3 "${REPO_ROOT}/scripts/tetragon-capabilities.py" "$@")" || return 1
export TF_VAR_tetragon_agent_enabled="${enabled}"
}
require_debian_server() {
local command_name="$1"
local os_id=""
if [[ "$(uname -s)" != "Linux" ]]; then
echo "Refusing to run '${command_name}' from this machine. Run it on the Debian homelab server." >&2
exit 1
fi
if [[ -r /etc/os-release ]]; then
os_id="$(awk -F= '$1 == "ID" {gsub(/"/, "", $2); print $2; exit}' /etc/os-release)"
fi
if [[ "${os_id}" != "debian" ]]; then
echo "Refusing to run '${command_name}' on ${os_id:-unknown OS}. Run it on the Debian homelab server." >&2
exit 1
fi
}
tofu_state_has_resource() {
local stack="$1"
local resource_address="$2"
tofu -chdir="${REPO_ROOT}/${stack}" state show "${resource_address}" >/dev/null 2>&1
}
cleanup_stale_helm_release_secrets() {
local namespace="$1"
local release_name="$2"
local status
for status in pending-install pending-upgrade pending-rollback failed uninstalling uninstalled; do
kubectl --kubeconfig "${KUBECONFIG_PATH}" -n "${namespace}" get secret \
-l "owner=helm,name=${release_name},status=${status}" \
-o name 2>/dev/null |
while read -r secret_ref; do
[[ -z "${secret_ref}" ]] && continue
echo "Deleting stale Helm release ${namespace}/${release_name} secret ${secret_ref#secret/} with status=${status}..."
kubectl --kubeconfig "${KUBECONFIG_PATH}" -n "${namespace}" delete "${secret_ref}"
done
done
}
helm_release_deployed_secret_exists() {
local namespace="$1"
local release_name="$2"
local secret_name
secret_name="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" -n "${namespace}" get secrets \
-l "owner=helm,name=${release_name},status=deployed" \
-o jsonpath='{.items[0].metadata.name}' 2>/dev/null || true)"
[[ -n "${secret_name}" ]]
}
helm_release_exists_for_adoption() {
local namespace="$1"
local release_name="$2"
if helm_release_deployed_secret_exists "${namespace}" "${release_name}"; then
return 0
fi
if command -v helm >/dev/null 2>&1 &&
helm --kubeconfig "${KUBECONFIG_PATH}" -n "${namespace}" status "${release_name}" >/dev/null 2>&1; then
return 0
fi
return 1
}
kubernetes_resource_exists() {
local namespace="$1"
local resource_kind="$2"
local resource_name="$3"
if [[ -n "${namespace}" ]]; then
kubectl --kubeconfig "${KUBECONFIG_PATH}" -n "${namespace}" get "${resource_kind}" "${resource_name}" >/dev/null 2>&1
return $?
fi
kubectl --kubeconfig "${KUBECONFIG_PATH}" get "${resource_kind}" "${resource_name}" >/dev/null 2>&1
}
adopt_tofu_helm_release() {
local stack="$1"
local resource_address="$2"
local namespace="$3"
local release_name="$4"
local has_state=false
local has_existing_release=false
if tofu_state_has_resource "${stack}" "${resource_address}"; then
has_state=true
fi
cleanup_stale_helm_release_secrets "${namespace}" "${release_name}"
if helm_release_exists_for_adoption "${namespace}" "${release_name}"; then
has_existing_release=true
fi
if [[ "${has_state}" == "true" && "${has_existing_release}" == "false" ]]; then
echo "Removing stale Helm release state for ${namespace}/${release_name} from ${stack} (${resource_address}) because no deployed Helm release exists..."
tofu -chdir="${REPO_ROOT}/${stack}" state rm "${resource_address}"
return 0
fi
if [[ "${has_state}" == "true" ]]; then
return 0
fi
if [[ "${has_existing_release}" == "false" ]]; then
return 0
fi
echo "Importing existing Helm release ${namespace}/${release_name} into ${stack} state (${resource_address})..."
platform_import_with_retry "${resource_address}" "${namespace}/${release_name}"
}
untaint_existing_helm_release() {
local stack="$1"
local resource_address="$2"
local state_output
if ! tofu_state_has_resource "${stack}" "${resource_address}"; then
return 0
fi
state_output="$(tofu -chdir="${REPO_ROOT}/${stack}" state show "${resource_address}")" || return 1
if grep -Fq '(tainted)' <<<"${state_output}"; then
echo "Clearing stale taint from existing Helm release ${resource_address}..."
tofu -chdir="${REPO_ROOT}/${stack}" untaint "${resource_address}"
fi
}
adopt_tofu_kubernetes_resource() {
local stack="$1"
local resource_address="$2"
local namespace="$3"
local resource_kind="$4"
local resource_name="$5"
local import_id="$6"
if tofu_state_has_resource "${stack}" "${resource_address}"; then
return 0
fi
if ! kubernetes_resource_exists "${namespace}" "${resource_kind}" "${resource_name}"; then
return 0
fi
echo "Importing existing Kubernetes ${resource_kind} ${resource_name} into ${stack} state (${resource_address})..."
tofu -chdir="${REPO_ROOT}/${stack}" import -input=false "${resource_address}" "${import_id}"
}
adopt_tofu_kubernetes_manifest() {
local stack="$1"
local resource_address="$2"
local namespace="$3"
local kubectl_kind="$4"
local api_version="$5"
local manifest_kind="$6"
local resource_name="$7"
local import_id
if tofu_state_has_resource "${stack}" "${resource_address}"; then
return 0
fi
if ! kubernetes_resource_exists "${namespace}" "${kubectl_kind}" "${resource_name}"; then
return 0
fi
import_id="apiVersion=${api_version},kind=${manifest_kind},namespace=${namespace},name=${resource_name}"
echo "Importing existing Kubernetes ${manifest_kind} ${namespace}/${resource_name} into ${stack} state (${resource_address})..."
tofu -chdir="${REPO_ROOT}/${stack}" import -input=false "${resource_address}" "${import_id}"
}
platform_read_state_addresses() {
tofu -chdir="${REPO_ROOT}/bootstrap/platform" show -json |
python3 -c '
import json, sys
def walk(module):
for resource in module.get("resources", []):
print(resource["address"])
for child in module.get("child_modules", []):
walk(child)
walk((json.load(sys.stdin).get("values") or {}).get("root_module") or {})
'
}
platform_import_with_retry() {
local address="$1" import_id="$2"
local max_attempts="${LAB_TOFU_K8S_IMPORT_RETRIES:-3}"
local attempt=1 status output_file current_addresses
local transport_errors='tls: bad record MAC|tls: received record with version|tls: first record does not look like a TLS handshake|TLS handshake timeout|unexpected EOF|unexpected error when reading response body|connection reset by peer|context deadline exceeded|i/o timeout|connection refused|server is currently unable'
if ! [[ "${max_attempts}" =~ ^[1-9][0-9]*$ ]]; then
echo "LAB_TOFU_K8S_IMPORT_RETRIES must be a positive integer." >&2
return 2
fi
while ((attempt <= max_attempts)); do
# A failed response can follow a committed state write. Recheck before
# retrying rather than deleting state or importing an already-owned object.
current_addresses="$(platform_read_state_addresses)" || return 1
if grep -Fxq -- "${address}" <<<"${current_addresses}"; then
echo "Platform resource ${address} is already recorded; import skipped."
return 0
fi
output_file="$(mktemp "${TMPDIR:-/tmp}/homelab-platform-import.XXXXXX")" || return 1
if tofu -chdir="${REPO_ROOT}/bootstrap/platform" import -input=false \
"${address}" "${import_id}" >"${output_file}" 2>&1; then
cat "${output_file}"
rm -f "${output_file}"
return 0
else
status=$?
fi
cat "${output_file}"
if ((attempt >= max_attempts)) || ! grep -Eiq "${transport_errors}" "${output_file}"; then
rm -f "${output_file}"
return "${status}"
fi
rm -f "${output_file}"
attempt=$((attempt + 1))
echo "Platform import hit a Kubernetes transport error; retrying ${address} (${attempt}/${max_attempts}) in 5s..." >&2
sleep 5
done
}
adopt_monitoring_resource_if_missing() {
local address="$1" namespace="$2" kind="$3" name="$4" import_id="$5"
local existing
if grep -Fxq -- "${address}" <<<"${monitoring_state_addresses}"; then
return 0
fi
if [[ -n "${namespace}" ]]; then
existing="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" --request-timeout=10s \
-n "${namespace}" get "${kind}" "${name}" --ignore-not-found -o name)" || return 1
else
existing="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" --request-timeout=10s \
get "${kind}" "${name}" --ignore-not-found -o name)" || return 1
fi
[[ -n "${existing}" ]] || return 0
echo "Adopting existing monitoring resource ${address}: ${import_id}"
platform_import_with_retry "${address}" "${import_id}" || return 1
}
adopt_platform_monitoring_resources() {
local monitoring_state_addresses resolved namespace mimir_enabled namespace_exists
local expected_node="${LAB_CLUSTER_CONTROL_PLANE_NODE_NAME:-}"
local observed_node release address revisions dashboard_file dashboard_key dashboard_name
# Do not silently treat an API, authorization, or state read failure as an
# empty cluster. Only namespace/name matches in the selected cluster count.
if [[ -n "${expected_node}" ]]; then
observed_node="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" --request-timeout=10s \
get node "${expected_node}" --ignore-not-found -o name)" || return 1
if [[ -z "${observed_node}" ]]; then
echo "Expected control plane ${expected_node} was not found; refusing monitoring adoption in this cluster." >&2
return 1
fi
fi
resolved="$(printf '%s\n' 'jsonencode({namespace = var.observability.namespace, mimir_enabled = var.observability.mimir.enabled})' |
tofu -chdir="${REPO_ROOT}/bootstrap/platform" console |
python3 -c 'import json,sys; v=json.loads(json.loads(sys.stdin.read())); print(v["namespace"]); print(str(v["mimir_enabled"]).lower())')" || return 1
namespace="${resolved%%$'\n'*}"
mimir_enabled="${resolved##*$'\n'}"
monitoring_state_addresses="$(platform_read_state_addresses)" || return 1
adopt_monitoring_resource_if_missing kubernetes_priority_class_v1.monitoring \
"" priorityclass homelab-monitoring homelab-monitoring || return 1
namespace_exists="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" --request-timeout=10s \
get namespace "${namespace}" --ignore-not-found -o name)" || return 1
[[ -n "${namespace_exists}" ]] || return 0
adopt_monitoring_resource_if_missing kubernetes_namespace_v1.monitoring \
"" namespace "${namespace}" "${namespace}" || return 1
for release in prometheus-stack mimir; do
if [[ "${release}" == mimir ]]; then
[[ "${mimir_enabled}" == true ]] || continue
address='helm_release.mimir[0]'
else
address=helm_release.prometheus_stack
fi
if grep -Fxq -- "${address}" <<<"${monitoring_state_addresses}"; then
continue
fi
revisions="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" --request-timeout=10s \
-n "${namespace}" get secrets -l "owner=helm,name=${release}" -o name)" || return 1
[[ -n "${revisions}" ]] || continue
echo "Adopting existing monitoring Helm release ${namespace}/${release} into ${address}"
platform_import_with_retry "${address}" "${namespace}/${release}" || return 1
done
for dashboard_file in "${REPO_ROOT}/bootstrap/platform/grafana-dashboards/"*.json; do
[[ -e "${dashboard_file}" ]] || continue
dashboard_key="$(basename "${dashboard_file}")"
dashboard_name="homelab-grafana-${dashboard_key%.json}"
adopt_monitoring_resource_if_missing "kubernetes_config_map.grafana_dashboards[\"${dashboard_key}\"]" \
"${namespace}" configmap "${dashboard_name}" "${namespace}/${dashboard_name}" || return 1
done
}
adopt_platform_calico_resources() {
local resolved namespace operator_node node_exists namespace_exists state_addresses
local expected_node="${LAB_CLUSTER_CONTROL_PLANE_NODE_NAME:-}"
local release address revisions
if [[ -n "${expected_node}" ]]; then
node_exists="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" --request-timeout=10s \
get node "${expected_node}" --ignore-not-found -o name)" || return 1
if [[ -z "${node_exists}" ]]; then
echo "Expected control plane ${expected_node} was not found; refusing Calico adoption in this cluster." >&2
return 1
fi
fi
resolved="$(printf '%s\n' 'jsonencode({namespace = var.calico.namespace, operator_node = var.calico_operator_node_name})' |
tofu -chdir="${REPO_ROOT}/bootstrap/platform" console |
python3 -c 'import json,sys; v=json.loads(json.loads(sys.stdin.read())); print(v["namespace"]); print(v["operator_node"])')" || return 1
namespace="${resolved%%$'\n'*}"
operator_node="${resolved##*$'\n'}"
node_exists="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" --request-timeout=10s \
get node "${operator_node}" --ignore-not-found -o name)" || return 1
if [[ -z "${node_exists}" ]]; then
echo "Configured Calico operator node ${operator_node} does not exist; refusing an unschedulable rollout." >&2
return 1
fi
state_addresses="$(platform_read_state_addresses)" || return 1
namespace_exists="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" --request-timeout=10s \
get namespace "${namespace}" --ignore-not-found -o name)" || return 1
[[ -n "${namespace_exists}" ]] || return 0
for release in calico-crds calico; do
if [[ "${release}" == calico-crds ]]; then
address=helm_release.calico_crds
else
address=helm_release.calico
fi
if grep -Fxq -- "${address}" <<<"${state_addresses}"; then
continue
fi
revisions="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" --request-timeout=10s \
-n "${namespace}" get secrets -l "owner=helm,name=${release}" -o name)" || return 1
[[ -n "${revisions}" ]] || continue
echo "Adopting existing Calico Helm release ${namespace}/${release} into ${address}"
platform_import_with_retry "${address}" "${namespace}/${release}" || return 1
done
}
adopt_platform_argocd_resources() {
local namespace node_exists namespace_exists state_addresses revisions
local expected_node="${LAB_CLUSTER_CONTROL_PLANE_NODE_NAME:-}"
local address="helm_release.argocd"
if [[ -n "${expected_node}" ]]; then
node_exists="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" --request-timeout=10s \
get node "${expected_node}" --ignore-not-found -o name)" || return 1
if [[ -z "${node_exists}" ]]; then
echo "Expected control plane ${expected_node} was not found; refusing Argo CD adoption in this cluster." >&2
return 1
fi
fi
namespace="$(printf '%s\n' 'jsonencode(var.argocd.namespace)' |
tofu -chdir="${REPO_ROOT}/bootstrap/platform" console |
python3 -c 'import json,sys; print(json.loads(json.loads(sys.stdin.read())))')" || return 1
state_addresses="$(platform_read_state_addresses)" || return 1
if grep -Fxq -- "${address}" <<<"${state_addresses}"; then
return 0
fi
namespace_exists="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" --request-timeout=10s \
get namespace "${namespace}" --ignore-not-found -o name)" || return 1
[[ -n "${namespace_exists}" ]] || return 0
revisions="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" --request-timeout=10s \
-n "${namespace}" get secrets -l 'owner=helm,name=argocd' -o name)" || return 1
[[ -n "${revisions}" ]] || return 0
echo "Adopting existing Argo CD Helm release ${namespace}/argocd into ${address}"
platform_import_with_retry "${address}" "${namespace}/argocd" || return 1
}
configure_platform_metrics_server_ownership() {
local resolved namespace enabled account owner
resolved="$(printf '%s\n' 'jsonencode({enabled = var.metrics_server.enabled, namespace = var.metrics_server.namespace})' |
tofu -chdir="${REPO_ROOT}/bootstrap/platform" console |
python3 -c 'import json,sys; v=json.loads(json.loads(sys.stdin.read())); print(str(v["enabled"]).lower()); print(v["namespace"])')" || return 1
enabled="${resolved%%$'\n'*}"
namespace="${resolved##*$'\n'}"
[[ "${enabled}" == true ]] || return 0
account="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" --request-timeout=10s -n "${namespace}" \
get serviceaccount metrics-server --ignore-not-found -o json)" || return 1
[[ -n "${account}" ]] || return 0
owner="$(printf '%s' "${account}" | python3 -c 'import json,sys; print((json.load(sys.stdin).get("metadata", {}).get("annotations") or {}).get("meta.helm.sh/release-name", ""))')" || return 1
if [[ -z "${owner}" ]]; then
if tofu_state_has_resource bootstrap/platform 'helm_release.metrics_server["enabled"]'; then
echo "metrics-server has external ownership but a Helm resource is tracked; refusing an ownership change. Review the selected platform state." >&2
return 1
fi
echo "Reusing externally managed ${namespace}/metrics-server; Helm installation skipped, live readiness remains required."
export TF_VAR_metrics_server_manage_release=false
elif [[ "${owner}" != metrics-server ]]; then
echo "metrics-server belongs to Helm release ${owner}; refusing to take over its resources." >&2
return 1
fi
}
adopt_platform_existing_resources() {
local stack="bootstrap/platform"
local dashboard_file
local dashboard_key
local dashboard_name
configure_platform_metrics_server_ownership || return 1
adopt_platform_monitoring_resources || return 1
adopt_tofu_helm_release "${stack}" "helm_release.calico_crds" "tigera-operator" "calico-crds" || return 1
adopt_tofu_helm_release "${stack}" "helm_release.calico" "tigera-operator" "calico" || return 1
adopt_tofu_helm_release "${stack}" "helm_release.openebs" "openebs" "openebs" || return 1
if [[ "${TF_VAR_metrics_server_manage_release:-true}" != false ]]; then
adopt_tofu_helm_release "${stack}" "helm_release.metrics_server[\"enabled\"]" "kube-system" "metrics-server" || return 1
fi
adopt_tofu_helm_release "${stack}" "helm_release.metallb[\"enabled\"]" "metallb-system" "metallb" || return 1
adopt_tofu_helm_release "${stack}" "helm_release.traefik[\"enabled\"]" "traefik" "traefik" || return 1
adopt_tofu_helm_release "${stack}" "helm_release.argocd" "argocd" "argocd" || return 1
adopt_tofu_helm_release "${stack}" "helm_release.kyverno" "kyverno" "kyverno" || return 1
adopt_tofu_helm_release "${stack}" "helm_release.kyverno_policies" "kyverno" "kyverno-policies" || return 1
adopt_tofu_helm_release "${stack}" "helm_release.loki" "monitoring" "loki" || return 1
adopt_tofu_helm_release "${stack}" "helm_release.promtail" "monitoring" "promtail" || return 1
adopt_tofu_helm_release "${stack}" "helm_release.prometheus_stack" "monitoring" "prometheus-stack" || return 1
local extra_releases release_name release_namespace
extra_releases="$(printf '%s\n' 'jsonencode({for name, release in var.extra_helm_releases : name => release.namespace})' |
tofu -chdir="${REPO_ROOT}/${stack}" console |
python3 -c 'import json,sys; v=json.loads(json.loads(sys.stdin.read())); [print(name + "\t" + namespace) for name,namespace in v.items()]')" || return 1
while IFS=$'\t' read -r release_name release_namespace; do
[[ -n "${release_name}" ]] || continue
adopt_tofu_helm_release "${stack}" "helm_release.extra_tools[\"${release_name}\"]" "${release_namespace}" "${release_name}" || return 1
done <<< "${extra_releases}"
adopt_tofu_kubernetes_resource \
"${stack}" \
"kubernetes_storage_class_v1.openebs_hostpath_retain" \
"" \
"storageclass" \
"openebs-hostpath-retain" \
"openebs-hostpath-retain" || return 1
adopt_tofu_kubernetes_resource \
"${stack}" \
"kubernetes_namespace_v1.monitoring" \
"" \
"namespace" \
"monitoring" \
"monitoring" || return 1
for dashboard_file in "${REPO_ROOT}/${stack}/grafana-dashboards/"*.json; do
[[ -e "${dashboard_file}" ]] || continue
dashboard_key="$(basename "${dashboard_file}")"
dashboard_name="homelab-grafana-${dashboard_key%.json}"
adopt_tofu_kubernetes_resource \
"${stack}" \
"kubernetes_config_map.grafana_dashboards[\"${dashboard_key}\"]" \
"monitoring" \
"configmap" \
"${dashboard_name}" \
"monitoring/${dashboard_name}" || return 1
done
}
adopt_apps_existing_resources() {
local stack="bootstrap/apps"
local namespace="${TF_VAR_argocd_namespace:-argocd}"
adopt_tofu_kubernetes_manifest \
"${stack}" \
'kubernetes_manifest.argocd_application["container-registry"]' \
"${namespace}" \
"applications.argoproj.io" \
"argoproj.io/v1alpha1" \
"Application" \
"container-registry"
adopt_tofu_kubernetes_manifest \
"${stack}" \
'kubernetes_manifest.argocd_application["website-production"]' \
"${namespace}" \
"applications.argoproj.io" \
"argoproj.io/v1alpha1" \
"Application" \
"website-production"
adopt_tofu_kubernetes_manifest \
"${stack}" \
'kubernetes_manifest.argocd_application["demos-static"]' \
"${namespace}" \
"applications.argoproj.io" \
"argoproj.io/v1alpha1" \
"Application" \
"demos-static"
adopt_tofu_kubernetes_manifest \
"${stack}" \
'kubernetes_manifest.argocd_application["heimdall"]' \
"${namespace}" \
"applications.argoproj.io" \
"argoproj.io/v1alpha1" \
"Application" \
"heimdall"
adopt_tofu_kubernetes_manifest \
"${stack}" \
'kubernetes_manifest.argocd_application["n8n"]' \
"${namespace}" \
"applications.argoproj.io" \
"argoproj.io/v1alpha1" \
"Application" \
"n8n"
adopt_tofu_kubernetes_manifest \
"${stack}" \
'kubernetes_manifest.argocd_application["supply-chain-policy"]' \
"${namespace}" \
"applications.argoproj.io" \
"argoproj.io/v1alpha1" \
"Application" \
"supply-chain-policy"
}
tofu_apply_has_targets() {
local arg
for arg in "$@"; do
[[ "${arg}" == -target=* ]] && return 0
done
return 1
}
ensure_homelab_node_labels() {
local control_plane_node="${LAB_CLUSTER_CONTROL_PLANE_NODE_NAME:-${LAB_CONTROL_PLANE_NODE_NAME:-debian}}"
local raspberry_node="${LAB_RASPBERRY_NODE_NAME:-raspberry}"
local prometheus_selector="homelab.dev/node-role=app,homelab.dev/storage=ssd"
local node
local target_nodes
echo "Applying homelab labels to existing Kubernetes nodes..."
while IFS= read -r node; do
[[ -n "${node}" ]] || continue
if [[ "${node}" == "${control_plane_node}" ]]; then
kubectl --kubeconfig "${KUBECONFIG_PATH}" label node "${node}" \
homelab.dev/node-role=control-plane \
homelab.dev/storage=local \
homelab.dev/workload-class=control-plane \
--overwrite
continue
fi
kubectl --kubeconfig "${KUBECONFIG_PATH}" label node "${node}" \
node-role.kubernetes.io/worker=worker \
--overwrite
if [[ "${node}" == pimox-worker-* ]]; then
kubectl --kubeconfig "${KUBECONFIG_PATH}" label node "${node}" \
homelab.dev/node-role=app \
homelab.dev/storage=ssd \
homelab.dev/workload-class=platform \
--overwrite
elif [[ "${node}" == "${raspberry_node}" ]]; then
kubectl --kubeconfig "${KUBECONFIG_PATH}" label node "${node}" \
homelab.dev/node-role=edge-app \
homelab.dev/storage=local \
homelab.dev/workload-class=edge \
--overwrite
fi
done < <(kubectl --kubeconfig "${KUBECONFIG_PATH}" get nodes -o jsonpath='{range .items[*]}{.metadata.name}{"\n"}{end}')
target_nodes="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" get nodes -l "${prometheus_selector}" -o name)"
if [[ -z "${target_nodes}" ]]; then
echo "No nodes match ${prometheus_selector}; refusing to move prometheus-stack." >&2
exit 1
fi
}
delete_prometheus_stack_storage() {
local namespace="${1:-monitoring}"
local pattern='(^|-)prometheus-stack-(prometheus|alertmanager|grafana)(-|$)|^prometheus-prometheus-stack|^alertmanager-prometheus-stack|^storage-prometheus-stack-grafana'
local pvc_names
local pv_names
pvc_names="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" -n "${namespace}" get pvc -o name 2>/dev/null |
awk -F/ -v pattern="${pattern}" '$2 ~ pattern {print $2}')"
pv_names="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" get pv \
-o jsonpath='{range .items[?(@.spec.claimRef.namespace=="'"${namespace}"'")]}{.metadata.name}{"\t"}{.spec.claimRef.name}{"\n"}{end}' 2>/dev/null |
awk -v pattern="${pattern}" '$2 ~ pattern {print $1}')"
if [[ -n "${pvc_names}" ]]; then
echo "Deleting old prometheus-stack PVCs in ${namespace}; saved Prometheus, Alertmanager, and Grafana data will be discarded..."
printf '%s\n' "${pvc_names}" |
xargs -r kubectl --kubeconfig "${KUBECONFIG_PATH}" -n "${namespace}" delete pvc --wait=true --timeout=180s
fi
if [[ -n "${pv_names}" ]]; then
echo "Deleting old prometheus-stack retained PV objects..."
printf '%s\n' "${pv_names}" |
xargs -r kubectl --kubeconfig "${KUBECONFIG_PATH}" delete pv --wait=false
fi
}
ensure_platform_scheduling_labels() {
local nodes control_plane_node
control_plane_node="${LAB_CLUSTER_CONTROL_PLANE_NODE_NAME:-}"
cluster_context_require || return 1
nodes="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" --request-timeout=15s get nodes \
-o jsonpath='{range .items[*]}{.metadata.name}{"\n"}{end}')" || return 1
# A single-node cluster must run platform services on its control plane,
# regardless of runtime/profile. Multi-node placement keeps its labels.
if [[ -n "${control_plane_node}" && "${nodes}" == "${control_plane_node}" ]]; then
kubectl --kubeconfig "${KUBECONFIG_PATH}" --request-timeout=15s \
label node "${control_plane_node}" homelab.dev/workload-class=platform --overwrite || return 1
fi
}
kubernetes_scheduling_preflight() {
local stack="$1"
shift
local directory status arg plan_output retry_pattern
local -a plan_args=()
[[ "${stack}" == "bootstrap/platform" || "${stack}" == "bootstrap/apps" ]] || return 0
if [[ -z "${LAB_CLUSTER_CONTROL_PLANE_NODE_NAME:-}" ]]; then
echo "Scheduling preflight requires the selected control-plane node name." >&2
return 1
fi
for arg in "$@"; do
[[ "${arg}" == "-auto-approve" ]] || plan_args+=("${arg}")
done
directory="$(mktemp -d "${TMPDIR:-/tmp}/jeannie-scheduling.XXXXXX")" || return 1
echo "Checking scheduling feasibility for ${stack} before deployment..."
retry_pattern='bad record MAC|received record with version|first record does not look like a TLS handshake|TLS handshake timeout|unexpected EOF|unexpected error when reading response body|connection reset by peer|context deadline exceeded|failed to query with labels|connection refused|server is currently unable'
if ! tofu -chdir="${REPO_ROOT}/${stack}" plan -input=false -out="${directory}/plan" \
"${plan_args[@]}" >"${directory}/plan.log" 2>&1; then
if ! grep -Eiq "${retry_pattern}" "${directory}/plan.log"; then
cat "${directory}/plan.log" >&2
rm -rf -- "${directory}"
return 1
fi
echo "Scheduling preflight hit a Kubernetes transport error; retrying with guarded -refresh=false plan..." >&2
plan_args+=("-refresh=false")
if ! tofu -chdir="${REPO_ROOT}/${stack}" plan -input=false -out="${directory}/plan" \
"${plan_args[@]}" >"${directory}/plan.log" 2>&1; then
cat "${directory}/plan.log" >&2
rm -rf -- "${directory}"
return 1
fi
fi
if ! tofu -chdir="${REPO_ROOT}/${stack}" show -json "${directory}/plan" >"${directory}/plan.json"; then
rm -rf -- "${directory}"
return 1
fi
status=0
python3 "${REPO_ROOT}/scripts/scheduling-preflight.py" \
--plan "${directory}/plan.json" --kubeconfig "${KUBECONFIG_PATH}" \
--repo-root "${REPO_ROOT}" --expected-node "${LAB_CLUSTER_CONTROL_PLANE_NODE_NAME}" || status=$?
# The private directory can contain sensitive planned chart values.
rm -rf -- "${directory}"
return "${status}"
}
tofu_apply_with_kubernetes_retry() {
local stack="$1"
shift
local max_attempts="${LAB_TOFU_K8S_APPLY_RETRIES:-3}"
local retry_sleep="${LAB_TOFU_K8S_APPLY_RETRY_SLEEP_SECONDS:-30}"
local refresh_fallback="${LAB_TOFU_K8S_REFRESH_FALSE_FALLBACK:-true}"
local refresh_fallback_attempts="${LAB_TOFU_K8S_REFRESH_FALSE_RETRIES:-${LAB_TOFU_K8S_APPLY_RETRIES:-3}}"
local retry_error_pattern='cannot get OpenAPI|failed get OpenAPI spec|context deadline exceeded|TLS handshake timeout|connection refused|unexpected EOF|server is currently unable|bad record MAC|received record with version|first record does not look like a TLS handshake|failed to query with labels|unexpected error when reading response body|unable to build kubernetes objects from release manifest|another operation .* is in progress|already exists'
local attempt=1
local status=0
local output_file
while true; do
kubernetes_scheduling_preflight "${stack}" "$@" || return 1
output_file="$(mktemp "${TMPDIR:-/tmp}/homelab-tofu-apply.XXXXXX")"
set +e
tofu -chdir="${REPO_ROOT}/${stack}" apply "$@" 2>&1 | tee "${output_file}"
status="${PIPESTATUS[0]}"
set -e
if ((status == 0)); then
rm -f "${output_file}"
return 0
fi
if [[ "${stack}" != "bootstrap/platform" && "${stack}" != "bootstrap/apps" ]]; then
rm -f "${output_file}"
return "${status}"
fi
if grep -Eiq 'invalid ownership metadata|cannot be imported into the current release|cannot re-use a name that is still in use|Error:.*already exists' "${output_file}"; then
echo "OpenTofu found a resource ownership conflict; refusing transport retries or refresh=false fallback." >&2
rm -f "${output_file}"
return "${status}"
fi
if ! grep -Eiq "${retry_error_pattern}" "${output_file}"; then
rm -f "${output_file}"
return "${status}"
fi
if ((attempt >= max_attempts)); then
if truthy "${refresh_fallback}"; then
rm -f "${output_file}"
local refresh_attempt=1
while true; do
echo "OpenTofu ${stack} apply still hit Kubernetes API/OpenAPI read errors after ${attempt} attempt(s); trying guarded -refresh=false apply ${refresh_attempt}/${refresh_fallback_attempts}." >&2
ensure_kubernetes_api_ready_for_tofu_stack "${stack}"
if [[ "${stack}" == "bootstrap/platform" ]] && ! tofu_apply_has_targets "$@"; then
adopt_platform_existing_resources
elif [[ "${stack}" == "bootstrap/apps" ]]; then
adopt_apps_existing_resources
fi
kubernetes_scheduling_preflight "${stack}" "$@" || return 1
output_file="$(mktemp "${TMPDIR:-/tmp}/homelab-tofu-refresh-false-apply.XXXXXX")"
set +e
tofu -chdir="${REPO_ROOT}/${stack}" apply -refresh=false "$@" 2>&1 | tee "${output_file}"
status="${PIPESTATUS[0]}"
set -e
if ((status == 0)); then
rm -f "${output_file}"
return 0
fi
if grep -Eiq 'invalid ownership metadata|cannot be imported into the current release|cannot re-use a name that is still in use|Error:.*already exists' "${output_file}"; then
echo "OpenTofu found a resource ownership conflict; refusing further refresh=false attempts." >&2
rm -f "${output_file}"
return "${status}"
fi
if ! grep -Eiq "${retry_error_pattern}" "${output_file}" || ((refresh_attempt >= refresh_fallback_attempts)); then
rm -f "${output_file}"
return "${status}"
fi
refresh_attempt=$((refresh_attempt + 1))
rm -f "${output_file}"
sleep "${retry_sleep}"
done
fi
echo "OpenTofu ${stack} apply still hit Kubernetes API/OpenAPI errors after ${attempt} attempt(s)." >&2
rm -f "${output_file}"
return "${status}"
fi
attempt=$((attempt + 1))
echo "OpenTofu ${stack} apply hit a transient Kubernetes API/OpenAPI error; waiting for API stability before retry ${attempt}/${max_attempts}..." >&2
rm -f "${output_file}"
ensure_kubernetes_api_ready_for_tofu_stack "${stack}"
if [[ "${stack}" == "bootstrap/platform" ]] && ! tofu_apply_has_targets "$@"; then
adopt_platform_existing_resources
elif [[ "${stack}" == "bootstrap/apps" ]]; then
adopt_apps_existing_resources
fi
sleep "${retry_sleep}"
done
}
run_tofu_stack() {
local stack="$1"
shift
local auto_approve="${LAB_AUTO_APPROVE:-true}"
local -a apply_args=()
local target
if [[ "${stack}" == bootstrap/cluster || "${stack}" == bootstrap/platform || "${stack}" == bootstrap/apps ]]; then
cluster_runtime_require || return 1
fi
# A new profile has no pinned identity until its control plane bootstrap
# completes. Platform/apps remain guarded by cluster-context as usual.
if [[ "${stack}" == "bootstrap/platform" || "${stack}" == "bootstrap/apps" ]] ||
[[ "${stack}" == "bootstrap/cluster" && -f "${HOMELAB_STATE_DIR}/clusters/${LAB_CLUSTER_PROFILE}/identity.json" ]]; then
cluster_context_require || return 1
retire_debian_service_hooks || return 1
fi
# Component applies use OpenTofu targets. Dependencies inside the selected
# component are included; cross-component prerequisites must already exist.
while (($#)); do
target="$1"
apply_args+=("-target=${target}")
shift
done
if [[ "${stack}" == "bootstrap/cluster" && "${LAB_CLUSTER_RUNTIME:-kubeadm}" != "k3s" ]]; then
ensure_cluster_worker_var_file
fi
if [[ "${stack}" == "bootstrap/edge" ]]; then
if [[ "${LAB_EDGE_DEFER_TAILSCALE_ROUTES:-false}" != true ]]; then
ensure_edge_tailscale_routes || return 1
fi
ensure_edge_haproxy_stats_password
fi
if truthy "${auto_approve}"; then
apply_args+=("-auto-approve")
elif ! disabled_value "${auto_approve}"; then
echo "LAB_AUTO_APPROVE must be true or false." >&2
exit 1
fi
if [[ "${stack}" == "bootstrap/cluster" && -n "${LAB_CLUSTER_VAR_FILE:-}" ]]; then
apply_args+=("-var-file=${LAB_CLUSTER_VAR_FILE}")
fi
if [[ "${stack}" == "bootstrap/platform" || "${stack}" == "bootstrap/apps" ]]; then
local k8s_tofu_parallelism="${LAB_TOFU_K8S_PARALLELISM:-1}"
if ! [[ "${k8s_tofu_parallelism}" =~ ^[0-9]+$ ]] || ((k8s_tofu_parallelism < 1)); then
echo "LAB_TOFU_K8S_PARALLELISM must be a positive integer." >&2
exit 1
fi
apply_args+=("-parallelism=${k8s_tofu_parallelism}")
fi
if [[ "${stack}" == "bootstrap/platform" ]]; then
configure_platform_grafana_sso
configure_platform_argocd_sso
ensure_platform_scheduling_labels || return 1
configure_platform_tetragon_capabilities --label-nodes || return 1
fi
tofu -chdir="${REPO_ROOT}/${stack}" init || return 1
ensure_kubernetes_api_ready_for_tofu_stack "${stack}" || return 1
if [[ "${stack}" == "bootstrap/platform" ]]; then
configure_platform_metrics_server_ownership || return 1
fi
if [[ "${stack}" == "bootstrap/platform" ]] && ! tofu_apply_has_targets "${apply_args[@]}"; then
adopt_platform_existing_resources || return 1
elif [[ "${stack}" == "bootstrap/platform" ]]; then
for target in "${apply_args[@]}"; do
if [[ "${target}" == "-target=helm_release.prometheus_stack" ]]; then
adopt_platform_monitoring_resources || return 1
break
elif [[ "${target}" == "-target=helm_release.calico_crds" || "${target}" == "-target=helm_release.calico" ]]; then
adopt_platform_calico_resources || return 1
break
elif [[ "${target}" == "-target=helm_release.argocd" ]]; then
adopt_platform_argocd_resources || return 1
break
fi
done
fi
if [[ "${stack}" == "bootstrap/platform" ]]; then
untaint_existing_helm_release "${stack}" 'helm_release.metrics_server["enabled"]'
fi
if [[ "${stack}" == "bootstrap/apps" ]] && ! tofu_apply_has_targets "${apply_args[@]}"; then
adopt_apps_existing_resources
fi
ensure_kubernetes_api_ready_for_tofu_stack "${stack}"
if ! tofu_apply_with_kubernetes_retry "${stack}" "${apply_args[@]}"; then
if [[ "${stack}" == "bootstrap/edge" ]]; then
edge_remote_failure_report || true
fi
return 1
fi
}
run_tofu_plan_stack() {
local stack="$1"
local -a plan_args=()
if [[ "${stack}" == "bootstrap/cluster" && "${LAB_CLUSTER_RUNTIME:-kubeadm}" != "k3s" ]]; then
ensure_cluster_worker_var_file
fi
if [[ "${stack}" == "bootstrap/edge" ]]; then
ensure_edge_haproxy_stats_password
fi
if [[ "${stack}" == "bootstrap/cluster" && -n "${LAB_CLUSTER_VAR_FILE:-}" ]]; then
plan_args+=("-var-file=${LAB_CLUSTER_VAR_FILE}")
fi
# Use the same API concurrency as applies, including standalone refreshes
# of Helm releases. Otherwise plan silently uses OpenTofu's default of 10.
if [[ "${stack}" == "bootstrap/platform" || "${stack}" == "bootstrap/apps" ]]; then
local k8s_tofu_parallelism="${LAB_TOFU_K8S_PARALLELISM:-1}"
if ! [[ "${k8s_tofu_parallelism}" =~ ^[0-9]+$ ]] || ((k8s_tofu_parallelism < 1)); then
echo "LAB_TOFU_K8S_PARALLELISM must be a positive integer." >&2
return 2
fi
plan_args+=("-parallelism=${k8s_tofu_parallelism}")
fi
if [[ "${stack}" == "bootstrap/platform" ]]; then
configure_platform_grafana_sso
configure_platform_argocd_sso
configure_platform_tetragon_capabilities || return 1
fi
tofu -chdir="${REPO_ROOT}/${stack}" init
if [[ "${stack}" == "bootstrap/platform" ]]; then
adopt_platform_existing_resources
untaint_existing_helm_release "${stack}" 'helm_release.metrics_server["enabled"]'
fi
tofu_plan_with_kubernetes_retry "${stack}" "${plan_args[@]}"
}
tofu_plan_with_kubernetes_retry() {
local stack="$1"
shift
local max_attempts="${LAB_TOFU_K8S_PLAN_RETRIES:-3}"
local attempt=1 status output_file
local retry_error_pattern='tls: bad record MAC|tls: received record with version|tls: first record does not look like a TLS handshake|TLS handshake timeout|unexpected EOF|unexpected error when reading response body|connection reset by peer|context deadline exceeded|i/o timeout|connection refused|server is currently unable|failed to query with labels'
if ! [[ "${max_attempts}" =~ ^[1-9][0-9]*$ ]]; then
echo "LAB_TOFU_K8S_PLAN_RETRIES must be a positive integer." >&2
return 2
fi
while ((attempt <= max_attempts)); do
output_file="$(mktemp "${TMPDIR:-/tmp}/homelab-tofu-plan.XXXXXX")" || return 1
if tofu -chdir="${REPO_ROOT}/${stack}" plan "$@" >"${output_file}" 2>&1; then
cat "${output_file}"
rm -f "${output_file}"
return 0
else
status=$?
fi
cat "${output_file}"
if ((attempt >= max_attempts)) || ! grep -Eiq "${retry_error_pattern}" "${output_file}"; then
rm -f "${output_file}"
return "${status}"
fi
rm -f "${output_file}"
attempt=$((attempt + 1))
echo "OpenTofu ${stack} plan hit a Kubernetes transport error; retrying (${attempt}/${max_attempts}) in 5s..." >&2
sleep 5
done
}
dex_public_url() {
printf '%s\n' "${LAB_DEX_PUBLIC_URL:-https://auth.${LAB_DOMAIN:-lab2025.duckdns.org}/}"
}
dex_bcrypt_hash() {
local password="$1"
local helper_image="${DEX_HTPASSWD_IMAGE:-httpd:2.4-alpine}"
local output
if command -v htpasswd >/dev/null 2>&1; then
output="$(printf '%s\n' "${password}" | htpasswd -BinC 10 dex)"
else
sudo docker pull "${helper_image}" >/dev/null
output="$(printf '%s\n' "${password}" | sudo docker run --rm -i "${helper_image}" htpasswd -BinC 10 dex)"
fi
printf '%s\n' "${output}" | awk -F: '/^dex:/ { print $2; exit }'
}
render_dex_config() {
local public_url="${1%/}"
local grafana_public_url="${2%/}"
local gitea_public_url="${3%/}"
local gitea_source_name="$4"
local grafana_client_secret="$5"
local gitea_client_secret="$6"
local user_email="$7"
local user_name="$8"
local user_id="$9"
local user_password_hash="${10}"
local office_public_url="${11:-}"
local office_client_secret="${12:-}"
local argocd_public_url="${13:-}"
local argocd_client_secret="${14:-}"
local opsproof_public_url="${15:-}"
local opsproof_client_secret="${16:-}"
local office_client_block=""
local argocd_client_block=""
local opsproof_client_block=""
if [[ -n "${opsproof_public_url}" && -n "${opsproof_client_secret}" ]]; then
opsproof_client_block="$(cat <<OPSPROOF_CLIENT_EOF
- id: opsproof
name: OpsProof
secret: "${opsproof_client_secret}"
redirectURIs:
- ${opsproof_public_url%/}/auth/dex/callback
OPSPROOF_CLIENT_EOF
)"
fi
if [[ -n "${argocd_public_url}" && -n "${argocd_client_secret}" ]]; then
argocd_client_block="$(cat <<ARGOCD_CLIENT_EOF
- id: argocd
name: Argo CD
secret: "${argocd_client_secret}"
redirectURIs:
- ${argocd_public_url%/}/auth/callback
ARGOCD_CLIENT_EOF
)"
fi
if [[ -n "${office_public_url}" && -n "${office_client_secret}" ]]; then
office_client_block="$(cat <<OFFICE_CLIENT_EOF
- id: nextcloud
name: Nextcloud
secret: "${office_client_secret}"
redirectURIs:
- ${office_public_url%/}/apps/user_oidc/code
OFFICE_CLIENT_EOF
)"
fi
cat <<CONFIG_EOF
issuer: ${public_url}
storage:
type: sqlite3
config:
file: /var/dex/dex.db
web:
http: 0.0.0.0:5556
telemetry:
http: 0.0.0.0:5558
oauth2:
skipApprovalScreen: true
responseTypes:
- code
enablePasswordDB: true
staticClients:
- id: grafana
name: Grafana
secret: "${grafana_client_secret}"
redirectURIs:
- ${grafana_public_url}/login/generic_oauth
- id: gitea
name: Gitea
secret: "${gitea_client_secret}"
redirectURIs:
- ${gitea_public_url}/user/oauth2/${gitea_source_name}/callback
${office_client_block}
${argocd_client_block}
${opsproof_client_block}
staticPasswords:
- email: "${user_email}"
username: "${user_name}"
userID: "${user_id}"
hash: "${user_password_hash}"
CONFIG_EOF
}
# The coordinated rotation call passes "rotation" from security.sh, which is
# analyzed separately by ShellCheck.
# shellcheck disable=SC2120
deploy_dex() {
local mode="${LAB_DEX_DEPLOY:-true}"
local install_dir="${LAB_DEX_INSTALL_DIR:-/data/homelab-dex}"
local data_dir="${LAB_DEX_DATA_DIR:-${install_dir}/data}"
local http_port="${LAB_DEX_HTTP_PORT:-5556}"
local telemetry_port="${LAB_DEX_TELEMETRY_PORT:-5558}"
local bind_ip="${LAB_DEX_BIND_IP:-0.0.0.0}"
local public_url
local image="${DEX_IMAGE:-ghcr.io/dexidp/dex:v2.45.1-alpine}"
local source_dir="${REPO_ROOT}/infra/dex"
local gitea_url="${LAB_GITEA_ROOT_URL:-}"
local grafana_url="https://grafana.${LAB_DOMAIN:-lab2025.duckdns.org}"
local gitea_source_name="${LAB_GITEA_DEX_SOURCE_NAME:-dex}"
local office_public_url="${LAB_OFFICE_PUBLIC_URL:-https://office.${LAB_DOMAIN:-lab2025.duckdns.org}}"
local office_client_secret="${LAB_OFFICE_OIDC_CLIENT_SECRET:-}"
local dex_env
local dex_user_password_hash
local dex_uid="${LAB_DEX_CONTAINER_UID:-1001}"
local dex_gid="${LAB_DEX_CONTAINER_GID:-1001}"
local elapsed=0
local opsproof_oidc_env="${LAB_OPSPROOF_INSTALL_DIR:-/data/homelab-opsproof}/.oidc.env"
local opsproof_public_url=""
local opsproof_client_secret=""
require_debian_server "deploy-dex"
if disabled_value "${mode}"; then
return 0
fi
public_url="$(dex_public_url)"
public_url="${public_url%/}"
gitea_url="${gitea_url%/}"
if [[ "${public_url}" != https://* ]]; then
echo "LAB_DEX_PUBLIC_URL must be an HTTPS URL." >&2
exit 1
fi
if [[ "${gitea_url}" != https://* ]]; then
echo "LAB_GITEA_ROOT_URL must be set to an HTTPS URL from homelab.yml." >&2
exit 1
fi
if [[ ! -s "${source_dir}/docker-compose.yml" ]]; then
echo "Missing Dex source files in ${source_dir}" >&2
exit 1
fi
if [[ "${1:-}" != rotation ]] && ! dex_drift_check; then
echo "Dex deployment refused: inspect ./jeannie doctor-dex and reconcile the encrypted source first." >&2
return 1
fi
dex_env="$(dex_secret_values)" || exit 1
eval "${dex_env}"
office_client_secret="${office_client_secret:-${DEX_OFFICE_CLIENT_SECRET:-}}"
if [[ -r "${opsproof_oidc_env}" ]]; then
opsproof_public_url="$(sed -n 's/^OPSPROOF_PUBLIC_URL=//p' "${opsproof_oidc_env}" | head -n 1)"
opsproof_client_secret="$(sed -n 's/^OPSPROOF_DEX_CLIENT_SECRET=//p' "${opsproof_oidc_env}" | head -n 1)"
fi
echo "Deploying Dex on the Debian host at ${install_dir}..."
ensure_local_docker_compose "DEX" "${LAB_DEX_INSTALL_DOCKER:-false}"
repair_local_docker_iptables
sudo docker pull "${image}"
dex_user_password_hash="$(dex_bcrypt_hash "${DEX_USER_PASSWORD}")"
if [[ -z "${dex_user_password_hash}" ]]; then
echo "Could not generate Dex bcrypt password hash with htpasswd." >&2
exit 1
fi
sudo mkdir -p "${install_dir}" "${data_dir}"
sudo cp "${source_dir}/docker-compose.yml" "${install_dir}/docker-compose.yml"
render_dex_config \
"${public_url}" \
"${grafana_url}" \
"${gitea_url}" \
"${gitea_source_name}" \
"${DEX_GRAFANA_CLIENT_SECRET}" \
"${DEX_GITEA_CLIENT_SECRET}" \
"${DEX_USER_EMAIL}" \
"${DEX_USER_NAME}" \
"${DEX_USER_ID}" \
"${dex_user_password_hash}" \
"${office_public_url}" \
"${office_client_secret}" \
"${LAB_ARGOCD_PUBLIC_URL:-https://argocd.${LAB_DOMAIN:-lab2025.duckdns.org}}" \
"${DEX_ARGOCD_CLIENT_SECRET:-}" \
"${opsproof_public_url}" \
"${opsproof_client_secret}" |
sudo tee "${install_dir}/config.yaml" >/dev/null
sudo chown "${dex_uid}:${dex_gid}" "${install_dir}/config.yaml"
sudo chown -R "${dex_uid}:${dex_gid}" "${data_dir}"
sudo chmod 600 "${install_dir}/config.yaml"
sudo chmod 700 "${data_dir}"
sudo tee "${install_dir}/.env" >/dev/null <<ENV_EOF
DEX_IMAGE=${image}
DEX_CONTAINER_NAME=${DEX_CONTAINER_NAME:-homelab-dex}
DEX_HTTP_PORT=${http_port}
DEX_TELEMETRY_PORT=${telemetry_port}
DEX_BIND_IP=${bind_ip}
DEX_DATA_DIR=${data_dir}
ENV_EOF
sudo chmod 600 "${install_dir}/.env"
(
cd "${install_dir}"
sudo docker compose --env-file "${install_dir}/.env" pull
sudo docker compose --env-file "${install_dir}/.env" up -d --remove-orphans --force-recreate dex
sudo docker compose --env-file "${install_dir}/.env" ps
)
until curl -fsS --connect-timeout 5 "http://127.0.0.1:${http_port}/.well-known/openid-configuration" >/dev/null ||
curl -fsS --connect-timeout 5 "http://127.0.0.1:${telemetry_port}/healthz" >/dev/null; do
if ((elapsed >= 180)); then
echo "Timed out waiting for Dex on http://127.0.0.1:${http_port}/.well-known/openid-configuration or http://127.0.0.1:${telemetry_port}/healthz" >&2
(cd "${install_dir}" && sudo docker compose --env-file "${install_dir}/.env" ps && sudo docker compose --env-file "${install_dir}/.env" logs --tail=160) >&2 || true
exit 1
fi
sleep 5
elapsed=$((elapsed + 5))
done
echo "Dex is reachable at http://127.0.0.1:${http_port}/ and ${public_url}/."
echo "Initial Dex user: ${DEX_USER_EMAIL}"
}
deploy_office() {
local mode="${LAB_OFFICE_DEPLOY:-true}"
local install_dir="${LAB_OFFICE_INSTALL_DIR:-/data/homelab-office}"
local source_dir="${REPO_ROOT}/infra/office"
local public_host="${LAB_OFFICE_PUBLIC_HOST:-office.${LAB_DOMAIN:-lab2025.duckdns.org}}"
local onlyoffice_host="${LAB_OFFICE_ONLYOFFICE_HOST:-docs.${LAB_DOMAIN:-lab2025.duckdns.org}}"
local bind_ip="${LAB_OFFICE_BIND_IP:-0.0.0.0}"
local http_port="${LAB_OFFICE_HTTP_PORT:-8090}"
local onlyoffice_port="${LAB_OFFICE_ONLYOFFICE_PORT:-9981}"
local env_file="${install_dir}/.env"
local nextcloud_data_dir="${install_dir}/nextcloud"
local postgres_data_dir="${install_dir}/postgres"
local redis_data_dir="${install_dir}/redis"
local onlyoffice_data_dir="${install_dir}/onlyoffice"
local onlyoffice_log_dir="${install_dir}/onlyoffice-logs"
local random_value
local dex_env
local office_oidc_secret="${LAB_OFFICE_OIDC_CLIENT_SECRET:-}"
local office_oidc_issuer="${LAB_DEX_PUBLIC_URL:-https://auth.${LAB_DOMAIN:-lab2025.duckdns.org}}"
local onlyoffice_jwt_secret=""
office_oidc_issuer="${office_oidc_issuer%/}"
require_debian_server "deploy-office"
if disabled_value "${mode}"; then
return 0
fi
if [[ ! -s "${source_dir}/docker-compose.yml" ]]; then
echo "Missing office stack source files in ${source_dir}." >&2
exit 1
fi
ensure_local_docker_compose "OFFICE" "${LAB_OFFICE_INSTALL_DOCKER:-false}"
repair_local_docker_iptables
if [[ -z "${office_oidc_secret}" ]]; then
dex_env="$(dex_secret_values)" || exit 1
eval "${dex_env}"
office_oidc_secret="${DEX_OFFICE_CLIENT_SECRET:-}"
fi
if [[ -z "${office_oidc_secret}" ]]; then
echo "Office SSO secret is missing. Run ./jeannie dex-secret ensure or set LAB_OFFICE_OIDC_CLIENT_SECRET." >&2
exit 1
fi
sudo mkdir -p "${install_dir}" "${nextcloud_data_dir}" "${postgres_data_dir}" "${redis_data_dir}" "${onlyoffice_data_dir}" "${onlyoffice_log_dir}"
sudo cp "${source_dir}/docker-compose.yml" "${install_dir}/docker-compose.yml"
if ! sudo test -s "${env_file}"; then
random_value() {
if command -v openssl >/dev/null 2>&1; then
openssl rand -hex 32
else
python3 - <<'PY'
import secrets
print(secrets.token_hex(32))
PY
fi
}
random_value="$(random_value)"
sudo tee "${env_file}" >/dev/null <<ENV_EOF
OFFICE_PUBLIC_HOST=${public_host}
OFFICE_ONLYOFFICE_HOST=${onlyoffice_host}
OFFICE_BIND_IP=${bind_ip}
OFFICE_HTTP_PORT=${http_port}
OFFICE_ONLYOFFICE_PORT=${onlyoffice_port}
OFFICE_ONLYOFFICE_JWT_SECRET=$(random_value)
OFFICE_POSTGRES_PASSWORD=${random_value}
OFFICE_REDIS_PASSWORD=$(random_value)
OFFICE_ADMIN_USER=${LAB_OFFICE_ADMIN_USER:-jv}
OFFICE_ADMIN_PASSWORD=$(random_value)
OFFICE_OIDC_CLIENT_ID=nextcloud
OFFICE_OIDC_CLIENT_SECRET=${office_oidc_secret}
OFFICE_OIDC_ISSUER_URL=${office_oidc_issuer}
OFFICE_NEXTCLOUD_DATA_DIR=${nextcloud_data_dir}
OFFICE_POSTGRES_DATA_DIR=${postgres_data_dir}
OFFICE_REDIS_DATA_DIR=${redis_data_dir}
ENV_EOF
sudo chmod 600 "${env_file}"
elif ! sudo grep -q '^OFFICE_ADMIN_PASSWORD=' "${env_file}"; then
random_value="$(openssl rand -hex 32 2>/dev/null || python3 -c 'import secrets; print(secrets.token_hex(32))')"
printf 'OFFICE_ADMIN_USER=%s\nOFFICE_ADMIN_PASSWORD=%s\n' \
"${LAB_OFFICE_ADMIN_USER:-jv}" "${random_value}" | sudo tee -a "${env_file}" >/dev/null
sudo chmod 600 "${env_file}"
fi
if ! sudo grep -q '^OFFICE_ONLYOFFICE_JWT_SECRET=' "${env_file}"; then
random_value="$(openssl rand -hex 32 2>/dev/null || python3 -c 'import secrets; print(secrets.token_hex(32))')"
printf 'OFFICE_ONLYOFFICE_HOST=%s\nOFFICE_ONLYOFFICE_PORT=%s\nOFFICE_ONLYOFFICE_JWT_SECRET=%s\n' \
"${onlyoffice_host}" "${onlyoffice_port}" "${random_value}" | sudo tee -a "${env_file}" >/dev/null
sudo chmod 600 "${env_file}"
fi
onlyoffice_jwt_secret="$(sudo sed -n 's/^OFFICE_ONLYOFFICE_JWT_SECRET=//p' "${env_file}" | tail -1)"
if [[ -z "${onlyoffice_jwt_secret}" ]]; then
echo "ONLYOFFICE JWT secret is missing from ${env_file}." >&2
exit 1
fi
(
cd "${install_dir}"
sudo docker compose --env-file "${env_file}" pull
sudo docker compose --env-file "${env_file}" up -d --remove-orphans
sudo docker compose --env-file "${env_file}" ps
)
if ! curl -fsS --connect-timeout 5 "http://127.0.0.1:${http_port}/status.php" >/dev/null; then
echo "Nextcloud did not become reachable at http://127.0.0.1:${http_port}/status.php." >&2
(cd "${install_dir}" && sudo docker compose --env-file "${env_file}" logs --tail=120) >&2 || true
exit 1
fi
if ! curl -fsS --connect-timeout 5 "http://127.0.0.1:${onlyoffice_port}/healthcheck" >/dev/null; then
echo "ONLYOFFICE did not become reachable at http://127.0.0.1:${onlyoffice_port}/healthcheck." >&2
(cd "${install_dir}" && sudo docker compose --env-file "${env_file}" logs --tail=160 onlyoffice) >&2 || true
exit 1
fi
sudo docker exec "${OFFICE_NEXTCLOUD_CONTAINER_NAME:-homelab-office-nextcloud}" \
sh -lc 'su -s /bin/sh www-data -c "php occ app:install user_oidc 2>/dev/null || true; php occ app:enable user_oidc 2>/dev/null || true"' || true
sudo docker exec -i \
-e "ONLYOFFICE_JWT_SECRET=${onlyoffice_jwt_secret}" \
-e "ONLYOFFICE_PUBLIC_URL=https://${onlyoffice_host}/" \
"${OFFICE_NEXTCLOUD_CONTAINER_NAME:-homelab-office-nextcloud}" \
sh -s <<'OFFICE_ONLYOFFICE_EOF'
set -eu
su -s /bin/sh www-data -c "php occ app:install onlyoffice 2>/dev/null || true; php occ app:enable onlyoffice"
su -s /bin/sh www-data -c "php occ config:app:set onlyoffice DocumentServerUrl --value=\"${ONLYOFFICE_PUBLIC_URL}\""
su -s /bin/sh www-data -c "php occ config:app:set onlyoffice DocumentServerInternalUrl --value=http://onlyoffice/"
su -s /bin/sh www-data -c "php occ config:app:set onlyoffice StorageUrl --value=http://nextcloud/"
su -s /bin/sh www-data -c "php occ config:app:set onlyoffice jwt_secret --value=\"${ONLYOFFICE_JWT_SECRET}\""
su -s /bin/sh www-data -c "php occ app:disable richdocuments 2>/dev/null || true"
OFFICE_ONLYOFFICE_EOF
sudo docker exec -i \
-e "OIDC_CLIENT_SECRET=${office_oidc_secret}" \
-e "OIDC_ISSUER=${office_oidc_issuer}" \
"${OFFICE_NEXTCLOUD_CONTAINER_NAME:-homelab-office-nextcloud}" \
sh -s <<'OFFICE_OIDC_EOF'
set -eu
su -s /bin/sh www-data -c "php occ user_oidc:provider nextcloud --clientid=nextcloud --clientsecret=\"${OIDC_CLIENT_SECRET}\" --discoveryuri=\"${OIDC_ISSUER}/.well-known/openid-configuration\" --scope=\"openid profile email\""
OFFICE_OIDC_EOF
local oidc_provider_state
oidc_provider_state="$(sudo docker exec "${OFFICE_NEXTCLOUD_CONTAINER_NAME:-homelab-office-nextcloud}" \
sh -lc 'su -s /bin/sh www-data -c "php occ user_oidc:provider nextcloud"')"
if ! grep -Fq 'openid profile email' <<<"${oidc_provider_state}"; then
echo "Nextcloud OIDC provider was not configured with the required openid scope." >&2
exit 1
fi
echo "Office stack is running at https://${public_host}/ with Dex SSO."
echo "Nextcloud data: ${nextcloud_data_dir}; ONLYOFFICE endpoint: https://${onlyoffice_host}."
}
ensure_argocd_dex_client() {
local dex_env secret_file client_secret
dex_env="$(dex_secret_values)" || return 1
eval "${dex_env}"
if [[ -z "${DEX_ARGOCD_CLIENT_SECRET:-}" ]]; then
secret_file="$(dex_secret_file)"
client_secret="$(generate_dex_secret_value)" || return 1
SOPS_AGE_KEY_FILE="$(sops_age_key_file)" sops set "${secret_file}" \
'["stringData"]["DEX_ARGOCD_CLIENT_SECRET"]' "\"${client_secret}\"" || return 1
echo "Added encrypted Argo CD client secret to ${secret_file}; back up and commit the encrypted file."
fi
}
configure_argocd_dex_secret() {
local dex_env
dex_env="$(dex_secret_values)" || return 1
eval "${dex_env}"
[[ -n "${DEX_ARGOCD_CLIENT_SECRET:-}" ]] || return 1
kubectl --kubeconfig "${KUBECONFIG_PATH}" -n "${LAB_ARGOCD_NAMESPACE:-argocd}" create secret generic argocd-dex-oauth \
--from-literal=clientSecret="${DEX_ARGOCD_CLIENT_SECRET}" --dry-run=client -o yaml |
kubectl --kubeconfig "${KUBECONFIG_PATH}" apply -f - || return 1
kubectl --kubeconfig "${KUBECONFIG_PATH}" -n "${LAB_ARGOCD_NAMESPACE:-argocd}" label secret argocd-dex-oauth app.kubernetes.io/part-of=argocd --overwrite
}
configure_grafana_dex_secret() {
local namespace="${TF_VAR_grafana_namespace:-monitoring}"
local secret_name="${TF_VAR_grafana_oauth_secret_name:-grafana-dex-oauth}"
local legacy_secret_name="${LAB_GRAFANA_LEGACY_OAUTH_SECRET_NAME:-grafana-authentik-oauth}"
local dex_env
require_debian_server "sso-grafana"
if ! command -v kubectl >/dev/null 2>&1; then
echo "kubectl is required to configure Grafana SSO." >&2
exit 1
fi
dex_env="$(dex_secret_values)" || exit 1
eval "${dex_env}"
kubectl --kubeconfig "${KUBECONFIG_PATH}" -n "${namespace}" create secret generic "${secret_name}" \
--from-literal=GF_AUTH_GENERIC_OAUTH_CLIENT_SECRET="${DEX_GRAFANA_CLIENT_SECRET}" \
--dry-run=client -o yaml |
kubectl --kubeconfig "${KUBECONFIG_PATH}" apply -f -
if [[ "${legacy_secret_name}" != "${secret_name}" ]]; then
kubectl --kubeconfig "${KUBECONFIG_PATH}" -n "${namespace}" delete secret "${legacy_secret_name}" --ignore-not-found
fi
}
grafana_sso() {
local action="${1:-plan}"
local grafana_oidc_url
require_debian_server "sso-grafana"
grafana_oidc_url="$(dex_public_url)"
export TF_VAR_grafana_oidc_url="${grafana_oidc_url}"
case "${action}" in
plan)
configure_platform_grafana_sso
run_tofu_plan_stack "bootstrap/platform"
;;
apply)
deploy_dex
configure_grafana_dex_secret
run_tofu_stack "bootstrap/platform" || return 1
if truthy "${LAB_MONITORING_EXTERNAL:-false}"; then monitoring_debian apply || return 1; fi
;;
*)
echo "Usage: ./jeannie sso-grafana {plan|apply}" >&2
return 2
;;
esac
}
configure_gitea_sso_source() {
local container_name="${LAB_GITEA_CONTAINER_NAME:-homelab-gitea}"
local source_name="${TF_VAR_gitea_auth_source_name:-${LAB_GITEA_DEX_SOURCE_NAME:-dex}}"
local legacy_source_name="${LAB_GITEA_LEGACY_AUTH_SOURCE_NAME:-authentik}"
local client_id="gitea"
local client_secret
local discovery_url
local public_url
local dex_env
local auth_id
local legacy_auth_id
local -a auth_base
dex_env="$(dex_secret_values)" || exit 1
eval "${dex_env}"
client_secret="${DEX_GITEA_CLIENT_SECRET}"
public_url="$(dex_public_url)"
discovery_url="${public_url%/}/.well-known/openid-configuration"
if ! sudo docker inspect "${container_name}" >/dev/null 2>&1; then
echo "Gitea container ${container_name} was not found. Run ./jeannie deploy-gitea first." >&2
exit 1
fi
if ! sudo docker ps --format '{{.Names}}' | grep -Fxq "${container_name}"; then
echo "Gitea container ${container_name} is not running. Run ./jeannie deploy-gitea first." >&2
exit 1
fi
auth_base=(sudo docker exec -u git "${container_name}" gitea -c /data/gitea/conf/app.ini admin auth)
auth_id="$("${auth_base[@]}" list | awk -v name="${source_name}" 'NR > 1 && $2 == name { print $1; exit }')"
legacy_auth_id="$("${auth_base[@]}" list | awk -v name="${legacy_source_name}" 'NR > 1 && $2 == name { print $1; exit }')"
if [[ -n "${legacy_auth_id}" && "${legacy_source_name}" != "${source_name}" ]]; then
echo "Removing legacy Gitea auth source ${legacy_source_name} (id ${legacy_auth_id})..."
"${auth_base[@]}" delete --id "${legacy_auth_id}"
fi
if [[ -n "${auth_id}" ]]; then
echo "Updating existing Gitea Dex auth source ${source_name} (id ${auth_id})..."
"${auth_base[@]}" update-oauth \
--id "${auth_id}" \
--name "${source_name}" \
--provider openidConnect \
--key "${client_id}" \
--secret "${client_secret}" \
--auto-discover-url "${discovery_url}" \
--scopes "openid email profile"
else
echo "Creating Gitea Dex auth source ${source_name}..."
"${auth_base[@]}" add-oauth \
--name "${source_name}" \
--provider openidConnect \
--key "${client_id}" \
--secret "${client_secret}" \
--auto-discover-url "${discovery_url}" \
--scopes "openid email profile"
fi
}
gitea_sso() {
local action="${1:-plan}"
local gitea_url="${LAB_GITEA_ROOT_URL:-}"
require_debian_server "sso-gitea"
if [[ "${gitea_url}" != https://* ]]; then
echo "LAB_GITEA_ROOT_URL must be set to an HTTPS URL from homelab.yml." >&2
exit 1
fi
export TF_VAR_gitea_public_url="${gitea_url}"
export TF_VAR_gitea_auth_source_name="${LAB_GITEA_DEX_SOURCE_NAME:-dex}"
case "${action}" in
plan)
echo "Dex Gitea SSO is configured by ./jeannie sso-gitea apply."
echo "Provider: openidConnect"
echo "Discovery URL: $(dex_public_url | sed 's:/*$::')/.well-known/openid-configuration"
echo "Callback URL: ${gitea_url%/}/user/oauth2/${TF_VAR_gitea_auth_source_name}/callback"
;;
apply)
deploy_dex
configure_gitea_sso_source
;;
*)
echo "Usage: ./jeannie sso-gitea {plan|apply}" >&2
exit 1
;;
esac
}
sso() {
local action="${1:-plan}"
local grafana_oidc_url
require_debian_server "sso"
grafana_oidc_url="$(dex_public_url)"
export TF_VAR_grafana_oidc_url="${grafana_oidc_url}"
export TF_VAR_gitea_auth_source_name="${LAB_GITEA_DEX_SOURCE_NAME:-dex}"
case "${action}" in
plan)
grafana_sso plan
gitea_sso plan
echo "Argo CD: Dex OIDC will be configured with read-only default access."
;;
apply)
ensure_argocd_dex_client || return 1
deploy_dex
edge_apply
configure_grafana_dex_secret
configure_argocd_dex_secret || return 1
run_tofu_stack "bootstrap/platform"
configure_gitea_sso_source
edge_flush_caches
;;
*)
echo "Usage: ./jeannie sso {plan|apply}" >&2
exit 1
;;
esac
}
backup_tofu_state() {
local backup_dir="${HOMELAB_TOFU_STATE_BACKUP_DIR:-${HOMELAB_STATE_DIR}/tofu-state-backups}"
local timestamp
local archive
local -a paths=()
local -a scoped_paths=()
local path
timestamp="$(date +%Y%m%d-%H%M%S)"
archive="${backup_dir}/tofu-state-${timestamp}.tgz"
mkdir -p "${backup_dir}"
for path in \
bootstrap/provisioning/terraform.tfstate \
bootstrap/provisioning/terraform.tfstate.backup \
bootstrap/cluster/terraform.tfstate \
bootstrap/cluster/terraform.tfstate.backup \
bootstrap/platform/terraform.tfstate \
bootstrap/platform/terraform.tfstate.backup \
bootstrap/sso-grafana/terraform.tfstate \
bootstrap/sso-grafana/terraform.tfstate.backup \
bootstrap/sso-gitea/terraform.tfstate \
bootstrap/sso-gitea/terraform.tfstate.backup \
bootstrap/apps/terraform.tfstate \
bootstrap/apps/terraform.tfstate.backup \
bootstrap/edge/terraform.tfstate \
bootstrap/edge/terraform.tfstate.backup \
.lab/cluster-workers.auto.tfvars.json \
.lab/pimox-workers.tsv \
.lab/manual-workers.tsv; do
if [[ -e "${REPO_ROOT}/${path}" ]]; then
paths+=("${path}")
fi
done
if [[ -d "${HOMELAB_STATE_DIR}/clusters" ]]; then
scoped_paths=(-C "${HOMELAB_STATE_DIR}" clusters)
fi
if ((${#paths[@]} == 0 && ${#scoped_paths[@]} == 0)); then
echo "No local OpenTofu state files found to back up."
return 0
fi
tar --exclude='clusters/*/.terraform' --exclude='*.operation.lock' --exclude='.enrollment.lock' --exclude='.migration.lock' \
-C "${REPO_ROOT}" -czf "${archive}" "${paths[@]}" "${scoped_paths[@]}"
chmod 0600 "${archive}"
echo "Backed up local OpenTofu state to ${archive}."
}
move_prometheus_stack_workers() {
local stack="bootstrap/platform"
local namespace="${LAB_MONITORING_NAMESPACE:-monitoring}"
local auto_approve="${LAB_AUTO_APPROVE:-true}"
local -a approve_args=()
require_debian_server "move-prometheus-stack-workers"
if [[ "${LAB_CONFIRM_DELETE_PROMETHEUS_DATA:-}" != "true" ]]; then
cat >&2 <<'EOF'
move-prometheus-stack-workers deletes existing prometheus-stack PVC/PV data.
Rerun with LAB_CONFIRM_DELETE_PROMETHEUS_DATA=true when that data loss is intended.
EOF
exit 1
fi
if truthy "${auto_approve}"; then
approve_args+=("-auto-approve")
elif ! disabled_value "${auto_approve}"; then
echo "LAB_AUTO_APPROVE must be true or false." >&2
exit 1
fi
export TF_VAR_kubeconfig_path="${TF_VAR_kubeconfig_path:-${KUBECONFIG_PATH}}"
export KUBECONFIG_PATH="${TF_VAR_kubeconfig_path}"
echo "Moving prometheus-stack off the control plane. Existing prometheus-stack PVC data will be deleted."
ensure_homelab_node_labels
tofu -chdir="${REPO_ROOT}/${stack}" init
adopt_platform_existing_resources
tofu -chdir="${REPO_ROOT}/${stack}" destroy -target=helm_release.prometheus_stack "${approve_args[@]}"
delete_prometheus_stack_storage "${namespace}"
tofu -chdir="${REPO_ROOT}/${stack}" apply "${approve_args[@]}"
kubectl --kubeconfig "${KUBECONFIG_PATH}" -n "${namespace}" get pods -o wide
}
doctor_versions_report() {
local api_version
local api_minor
local containerd_major_count
local kubelet_minor_count
local node_rows
local status=0
require_debian_server "doctor-versions"
ensure_python3
api_version="$(
kubectl --kubeconfig "${KUBECONFIG_PATH}" version -o json |
python3 -c 'import json, sys; print(json.load(sys.stdin)["serverVersion"]["gitVersion"])'
)"
api_minor="$(printf '%s\n' "${api_version}" | awk -F. '{gsub(/^v/, "", $1); print $1 "." $2}')"
node_rows="$(
kubectl --kubeconfig "${KUBECONFIG_PATH}" get nodes \
-o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.nodeInfo.kubeletVersion}{"\t"}{.status.nodeInfo.containerRuntimeVersion}{"\n"}{end}'
)"
if [[ -z "${node_rows}" ]]; then
echo "No Kubernetes nodes found." >&2
return 1
fi
printf 'API server: %s\n\n' "${api_version}"
printf '%-22s %-12s %-18s %s\n' "NODE" "KUBELET" "KUBELET_MINOR" "RUNTIME"
printf '%s\n' "${node_rows}" |
awk -F '\t' '{
version = $2
gsub(/^v/, "", version)
split(version, parts, ".")
printf "%-22s %-12s %-18s %s\n", $1, $2, parts[1] "." parts[2], $3
}'
kubelet_minor_count="$(
printf '%s\n' "${node_rows}" |
awk -F '\t' '{ version = $2; gsub(/^v/, "", version); split(version, parts, "."); print parts[1] "." parts[2] }' |
sort -u |
wc -l |
tr -d ' '
)"
containerd_major_count="$(
printf '%s\n' "${node_rows}" |
awk -F '\t' '$3 ~ /^containerd:\/\// { runtime = $3; sub(/^containerd:\/\//, "", runtime); split(runtime, parts, "."); print parts[1] }' |
sort -u |
wc -l |
tr -d ' '
)"
if [[ "${kubelet_minor_count}" != "1" ]]; then
echo
echo "Kubernetes kubelet minors are mixed. Rebuild or upgrade workers until every node matches the API server minor (${api_minor})." >&2
status=1
fi
if printf '%s\n' "${node_rows}" |
awk -F '\t' -v expected="${api_minor}" '{ version = $2; gsub(/^v/, "", version); split(version, parts, "."); if (parts[1] "." parts[2] != expected) found = 1 } END { exit found ? 0 : 1 }'; then
echo
echo "At least one kubelet does not match the API server minor (${api_minor})." >&2
status=1
fi
if [[ "${containerd_major_count}" -gt 1 ]]; then
echo
echo "Containerd major versions are mixed. Standardize the node image/runtime path before relying on destructive rebuilds." >&2
status=1
fi
if [[ "${status}" -eq 0 ]]; then
echo
echo "Node Kubernetes and containerd versions are aligned."
fi
return "${status}"
}
doctor_versions_compact() {
local api_version
local api_minor
local node_rows
local kubelet_minor_count
local containerd_major_count
local mismatch_count
local failures=0
ensure_python3
report_ui_begin
if ! status_kubernetes_api_ok; then
report_ui_emit fail "Kubernetes" "API" "not reachable" "kubectl readyz failed" "./jeannie start-cluster"
report_ui_render "Doctor Versions"
report_ui_cleanup
return 1
fi
api_version="$(
kubectl --kubeconfig "${KUBECONFIG_PATH}" version -o json |
python3 -c 'import json, sys; print(json.load(sys.stdin)["serverVersion"]["gitVersion"])'
)"
api_minor="$(printf '%s\n' "${api_version}" | awk -F. '{gsub(/^v/, "", $1); print $1 "." $2}')"
node_rows="$(
kubectl --kubeconfig "${KUBECONFIG_PATH}" get nodes \
-o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.nodeInfo.kubeletVersion}{"\t"}{.status.nodeInfo.containerRuntimeVersion}{"\n"}{end}'
)"
if [[ -z "${node_rows}" ]]; then
report_ui_emit fail "Kubernetes" "Nodes" "none found" "kubectl returned no node rows" "./jeannie doctor-cluster"
report_ui_render "Doctor Versions"
report_ui_cleanup
return 1
fi
kubelet_minor_count="$(
printf '%s\n' "${node_rows}" |
awk -F '\t' '{ version = $2; gsub(/^v/, "", version); split(version, parts, "."); print parts[1] "." parts[2] }' |
sort -u |
wc -l |
tr -d ' '
)"
mismatch_count="$(
printf '%s\n' "${node_rows}" |
awk -F '\t' -v expected="${api_minor}" '{ version = $2; gsub(/^v/, "", version); split(version, parts, "."); if (parts[1] "." parts[2] != expected) count++ } END { print count + 0 }'
)"
containerd_major_count="$(
printf '%s\n' "${node_rows}" |
awk -F '\t' '$3 ~ /^containerd:\/\// { runtime = $3; sub(/^containerd:\/\//, "", runtime); split(runtime, parts, "."); print parts[1] }' |
sort -u |
wc -l |
tr -d ' '
)"
report_ui_emit ok "Kubernetes" "API version" "${api_version}"
if [[ "${kubelet_minor_count}" != "1" || "${mismatch_count}" != "0" ]]; then
report_ui_emit fail "Kubernetes" "Kubelet versions" "${mismatch_count} node(s) differ from ${api_minor}" "unique kubelet minors=${kubelet_minor_count}" "./jeannie doctor-versions --verbose"
failures=$((failures + 1))
else
report_ui_emit ok "Kubernetes" "Kubelet versions" "aligned to ${api_minor}"
fi
if [[ "${containerd_major_count}" -gt 1 ]]; then
report_ui_emit warn "Runtime" "Containerd versions" "mixed major versions" "unique majors=${containerd_major_count}" "./jeannie doctor-versions --verbose"
else
report_ui_emit ok "Runtime" "Containerd versions" "single major version"
fi
report_ui_render "Doctor Versions"
report_ui_cleanup
return "${failures}"
}
doctor_versions() {
require_debian_server "doctor-versions"
if ! report_ui_parse_args "$@"; then
return 1
fi
if [[ "${REPORT_UI_VERBOSE}" == "true" ]]; then
doctor_versions_report
exit "$?"
fi
doctor_versions_compact
exit "$?"
}
worker_index_is_skipped() {
local index="$1"
local skip_indexes="$2"
local skip_index
skip_indexes="${skip_indexes//,/ }"
for skip_index in ${skip_indexes}; do
[[ -z "${skip_index}" ]] && continue
if ! [[ "${skip_index}" =~ ^[0-9]+$ ]]; then
echo "LAB_PIMOX_SKIP_WORKER_INDEXES must contain only comma or space separated positive integers." >&2
exit 1
fi
if ((skip_index == index)); then
return 0
fi
done
return 1
}
ensure_python3() {
if command -v python3 >/dev/null 2>&1; then
return 0
fi
sudo apt-get update
sudo apt-get install -y --no-install-recommends python3
}
ensure_go_toolchain() {
require_debian_server "go toolchain"
if command -v go >/dev/null 2>&1; then
return 0
fi
echo "Installing Go toolchain for Jeannie core helpers..."
sudo apt-get update
sudo apt-get install -y --no-install-recommends golang-go
if ! command -v go >/dev/null 2>&1; then
echo "go is still unavailable after installing golang-go." >&2
exit 1
fi
}
detect_route_interface() {
local target="$1"
ip route get "${target}" 2>/dev/null | awk '
{
for (i = 1; i <= NF; i++) {
if ($i == "dev") {
print $(i + 1)
exit
}
}
}
'
}
pimox_ssh() {
local host="$1"
local user="$2"
local key_path="$3"
shift 3
ssh -i "${key_path}" -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new "${user}@${host}" "$@"
}
pimox_scp() {
local key_path="$1"
local source_path="$2"
local target="$3"
scp -i "${key_path}" -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new "${source_path}" "${target}"
}
refresh_lab_ssh_known_host() {
local host="$1"
local enabled="${LAB_REFRESH_REBUILT_VM_HOST_KEYS:-true}"
local known_hosts_file="${LAB_SSH_KNOWN_HOSTS_FILE:-${HOME}/.ssh/known_hosts}"
local scan_output
if disabled_value "${enabled}"; then
return 0
fi
if ! truthy "${enabled}"; then
echo "LAB_REFRESH_REBUILT_VM_HOST_KEYS must be true or false." >&2
exit 1
fi
if [[ -z "${host}" || ! "${host}" =~ ^[A-Za-z0-9_.:-]+$ ]]; then
echo "Invalid SSH known-host target '${host}'." >&2
exit 1
fi
mkdir -p "$(dirname "${known_hosts_file}")"
touch "${known_hosts_file}"
chmod 0600 "${known_hosts_file}"
if ! scan_output="$(ssh-keyscan -T 5 -t ed25519 "${host}" 2>/dev/null)"; then
echo "Could not scan SSH host key for ${host}." >&2
exit 1
fi
if [[ -z "${scan_output}" ]]; then
echo "ssh-keyscan returned no host key for ${host}." >&2
exit 1
fi
ssh-keygen -R "${host}" -f "${known_hosts_file}" >/dev/null 2>&1 || true
printf '%s\n' "${scan_output}" >>"${known_hosts_file}"
}
pimox_guest_ipv4() {
local guest_json
local host="$1"
local user="$2"
local key_path="$3"
local vmid="$4"
local ip_prefix="$5"
local qm_bin="${6:-${LAB_PIMOX_QM_BIN:-/usr/sbin/qm}}"
guest_json="$(pimox_ssh "${host}" "${user}" "${key_path}" "sudo '${qm_bin}' guest cmd '${vmid}' network-get-interfaces" 2>/dev/null || true)"
if [[ -z "${guest_json}" ]]; then
return 1
fi
GUEST_JSON="${guest_json}" python3 - "${ip_prefix}" <<'PY'
import json
import os
import sys
prefix = sys.argv[1]
try:
interfaces = json.loads(os.environ.get("GUEST_JSON", ""))
except Exception:
sys.exit(1)
for iface in interfaces or []:
for address in iface.get("ip-addresses") or []:
if address.get("ip-address-type") != "ipv4":
continue
ip = address.get("ip-address", "")
if not ip or ip.startswith(("127.", "169.254.")):
continue
if prefix and not ip.startswith(prefix):
continue
print(ip)
sys.exit(0)
sys.exit(1)
PY
}
pimox_worker_vm_debug() {
local host="$1"
local user="$2"
local key_path="$3"
local vmid="$4"
local qm_bin="$5"
local script
local encoded_script
script="$(cat <<'EOF'
set +e
echo "-- addresses --"
ip -br addr
echo "-- routes --"
ip route
echo "-- units --"
systemctl is-active ssh sshd 2>/dev/null || true
echo "-- listeners --"
ss -ltnp 2>/dev/null | grep :22 || ss -ltn 2>/dev/null | grep :22 || true
echo "-- sshd config test --"
sudo sshd -t 2>&1 || true
echo "-- recent ssh logs --"
journalctl -u ssh -u sshd --no-pager -n 40 2>/dev/null || true
EOF
)"
encoded_script="$(printf '%s' "${script}" | base64 | tr -d '\n')"
pimox_ssh "${host}" "${user}" "${key_path}" "set +e
echo 'Pimox VM ${vmid} status:'
sudo '${qm_bin}' status '${vmid}'
echo 'Pimox VM ${vmid} config summary:'
sudo '${qm_bin}' config '${vmid}' | grep -E '^(agent|boot|net0|scsi0|virtio0|sata0|ide0|ide2|efidisk0):' || true
echo 'Pimox VM ${vmid} guest-agent network-get-interfaces:'
sudo '${qm_bin}' guest cmd '${vmid}' network-get-interfaces || true
echo 'Pimox VM ${vmid} guest SSH diagnostics:'
sudo '${qm_bin}' guest exec '${vmid}' -- bash -lc \"printf '%s' '${encoded_script}' | base64 -d | sudo bash\" || true" >&2 || true
}
pimox_worker_guest_agent_recovery_hint() {
local host="$1"
local user="$2"
local vmid="$3"
local qm_bin="$4"
cat >&2 <<EOF
QEMU guest agent did not become available for Pimox VM ${vmid}.
Fast checks:
ssh ${user}@${host} 'sudo ${qm_bin} status ${vmid}; sudo ${qm_bin} config ${vmid}; sudo ${qm_bin} guest cmd ${vmid} network-get-interfaces'
Recovery options:
1. If the clone is still booting slowly, rerun the Pimox stage with a longer agent wait:
LAB_RPI_SERVICES_DEPLOY=false LAB_PIMOX_GUEST_AGENT_CONFIG_TIMEOUT_SECONDS=600 ./jeannie up
2. If the same VM still reports "QEMU guest agent is not running", recreate the worker clone:
LAB_RPI_SERVICES_DEPLOY=false LAB_PIMOX_WORKER_REPLACE_EXISTING=true ./jeannie up
3. If a recreated worker still has no guest agent, rebuild the template and worker:
LAB_RPI_SERVICES_DEPLOY=false LAB_PIMOX_TEMPLATE_REPLACE_EXISTING=true LAB_PIMOX_WORKER_REPLACE_EXISTING=true ./jeannie up
EOF
}
pimox_guest_exec_exitcode() {
local guest_exec_json="$1"
GUEST_EXEC_JSON="${guest_exec_json}" python3 - <<'PY'
import json
import os
import sys
try:
document = json.loads(os.environ.get("GUEST_EXEC_JSON", ""))
except Exception:
sys.exit(2)
try:
print(int(document.get("exitcode", 1)))
except Exception:
sys.exit(2)
PY
}
pimox_worker_guest_ssh_repair() {
local host="$1"
local user="$2"
local key_path="$3"
local vmid="$4"
local qm_bin="$5"
local script
local encoded_script
local repair_output
local repair_exitcode
script="$(cat <<'EOF'
set -eu
ssh_unit=""
if systemctl list-unit-files ssh.service 2>/dev/null | grep -q '^ssh[.]service'; then
ssh_unit=ssh.service
elif systemctl list-unit-files sshd.service 2>/dev/null | grep -q '^sshd[.]service'; then
ssh_unit=sshd.service
else
echo "Neither ssh.service nor sshd.service exists in the guest" >&2
exit 1
fi
sudo ssh-keygen -A
sudo install -d -m 0755 /run/sshd
sudo mkdir -p /etc/ssh/sshd_config.d
sudo tee /etc/ssh/sshd_config.d/99-homelab-worker-listen.conf >/dev/null <<'SSHD_CONFIG'
Port 22
ListenAddress 0.0.0.0
PubkeyAuthentication yes
PasswordAuthentication no
KbdInteractiveAuthentication no
PermitRootLogin no
UsePAM yes
SSHD_CONFIG
sudo sshd -t
sudo systemctl unmask ssh.service ssh.socket sshd.service sshd.socket >/dev/null 2>&1 || true
sudo systemctl disable --now ssh.socket sshd.socket >/dev/null 2>&1 || true
sudo systemctl enable "$ssh_unit" >/dev/null
sudo systemctl restart "$ssh_unit"
sleep 2
sudo systemctl is-active "$ssh_unit"
if command -v ss >/dev/null 2>&1; then
ss -ltnp 2>/dev/null || ss -ltn
ss -ltn | awk '$4 == "0.0.0.0:22" { found = 1 } END { exit found ? 0 : 1 }'
fi
EOF
)"
encoded_script="$(printf '%s' "${script}" | base64 | tr -d '\n')"
if ! repair_output="$(pimox_ssh "${host}" "${user}" "${key_path}" "sudo '${qm_bin}' guest exec '${vmid}' -- bash -lc \"printf '%s' '${encoded_script}' | base64 -d | sudo bash\"" 2>&1)"; then
echo "Could not run guest SSH repair through qemu-guest-agent for VM ${vmid}." >&2
printf '%s\n' "${repair_output}" | sed 's/^/ guest-ssh-repair: /' >&2
return 1
fi
printf '%s\n' "${repair_output}" | sed 's/^/ guest-ssh-repair: /' >&2
if repair_exitcode="$(pimox_guest_exec_exitcode "${repair_output}")" && [[ "${repair_exitcode}" == "0" ]]; then
return 0
fi
echo "Guest SSH repair failed inside Pimox VM ${vmid}." >&2
if [[ -n "${repair_exitcode:-}" ]]; then
echo "Guest exit code: ${repair_exitcode}" >&2
fi
return 1
}
wait_for_pimox_guest_ssh() {
local host="$1"
local user="$2"
local key_path="$3"
local vmid="$4"
local guest_user="$5"
local guest_key_path="$6"
local ip_prefix="$7"
local timeout_seconds="$8"
local qm_bin="${9:-${LAB_PIMOX_QM_BIN:-/usr/sbin/qm}}"
local deadline
local elapsed
local guest_ip
local ip_filter_description
local known_hosts_file="${REPO_ROOT}/.lab/pimox-worker-known_hosts"
local last_guest_ip=""
local last_known_hosts_ip=""
local last_ssh_output=""
local last_host_probe_output=""
local host_probe_failures=0
local require_host_probe="${LAB_PIMOX_WORKER_REQUIRE_HOST_PROBE:-false}"
local next_log
local ssh_deadline=0
local ssh_output
local ssh_timeout_seconds="${LAB_PIMOX_GUEST_SSH_TIMEOUT_SECONDS:-600}"
local ssh_refused_since=0
local ssh_refused_timeout_seconds="${LAB_PIMOX_GUEST_SSH_REFUSED_TIMEOUT_SECONDS:-120}"
local ssh_repair_attempted=false
ip_filter_description="matching prefix ${ip_prefix}"
if [[ -z "${ip_prefix}" ]]; then
ip_filter_description="that is not loopback or link-local"
fi
if ! [[ "${ssh_timeout_seconds}" =~ ^[0-9]+$ ]] || ((ssh_timeout_seconds == 0)); then
echo "LAB_PIMOX_GUEST_SSH_TIMEOUT_SECONDS must be a positive integer." >&2
return 1
fi
if ! [[ "${ssh_refused_timeout_seconds}" =~ ^[0-9]+$ ]] || ((ssh_refused_timeout_seconds == 0)); then
echo "LAB_PIMOX_GUEST_SSH_REFUSED_TIMEOUT_SECONDS must be a positive integer." >&2
return 1
fi
if ! truthy "${require_host_probe}" && ! disabled_value "${require_host_probe}"; then
echo "LAB_PIMOX_WORKER_REQUIRE_HOST_PROBE must be true or false." >&2
return 1
fi
mkdir -p "$(dirname "${known_hosts_file}")"
touch "${known_hosts_file}"
chmod 0600 "${known_hosts_file}"
deadline=$((SECONDS + timeout_seconds))
next_log="${SECONDS}"
while ((SECONDS < deadline)); do
guest_ip="$(pimox_guest_ipv4 "${host}" "${user}" "${key_path}" "${vmid}" "${ip_prefix}" "${qm_bin}" || true)"
if [[ -n "${guest_ip}" ]]; then
if ((ssh_deadline == 0)); then
ssh_deadline=$((SECONDS + ssh_timeout_seconds))
elif ((SECONDS >= ssh_deadline)); then
break
fi
last_guest_ip="${guest_ip}"
if [[ "${last_known_hosts_ip}" != "${guest_ip}" ]]; then
ssh-keygen -R "${guest_ip}" -f "${known_hosts_file}" >/dev/null 2>&1 || true
last_known_hosts_ip="${guest_ip}"
fi
if truthy "${require_host_probe}"; then
if last_host_probe_output="$(ping -c 1 -W 2 "${guest_ip}" 2>&1)"; then
host_probe_failures=0
else
host_probe_failures=$((host_probe_failures + 1))
last_ssh_output="Debian host cannot ping ${guest_ip}; latest probe: ${last_host_probe_output}"
if ((host_probe_failures >= 3)); then
echo "Worker VM ${vmid} reported guest IP ${guest_ip}, but the Debian host cannot reach it on the LAN." >&2
echo "Latest host probe: ${last_host_probe_output}" >&2
echo "Fast checks:" >&2
echo " ssh ${user}@${host} 'ip -br link show; bridge link; sudo qm config ${vmid}; sudo qm guest cmd ${vmid} network-get-interfaces'" >&2
echo " arping -c 3 ${guest_ip} || ping -c 3 ${guest_ip}" >&2
echo " Check bridge ${LAB_PIMOX_BRIDGE:-vmbr0}, switch/VLAN, duplicate IP, and firewall rules between Debian and Pimox workers." >&2
pimox_worker_vm_debug "${host}" "${user}" "${key_path}" "${vmid}" "${qm_bin}"
return 1
fi
sleep 10
continue
fi
fi
if ssh_output="$(ssh -i "${guest_key_path}" -o BatchMode=yes -o ConnectTimeout=8 -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile="${known_hosts_file}" "${guest_user}@${guest_ip}" true 2>&1)"; then
printf '%s\n' "${guest_ip}"
return 0
fi
last_ssh_output="${ssh_output}"
if [[ "${ssh_output}" == *"Connection refused"* ]]; then
if ((ssh_refused_since == 0)); then
ssh_refused_since="${SECONDS}"
fi
if [[ "${ssh_repair_attempted}" == "false" ]]; then
echo "SSH on worker VM ${vmid} at ${guest_ip} is refusing connections; attempting qemu-guest-agent SSH repair..." >&2
pimox_worker_guest_ssh_repair "${host}" "${user}" "${key_path}" "${vmid}" "${qm_bin}" || true
ssh_repair_attempted=true
elif ((SECONDS - ssh_refused_since >= ssh_refused_timeout_seconds)); then
echo "Worker VM ${vmid} at ${guest_ip} is reachable but still refuses SSH after ${ssh_refused_timeout_seconds}s." >&2
echo "This usually means sshd is missing, broken, or not listening on IPv4 inside the worker template." >&2
pimox_worker_vm_debug "${host}" "${user}" "${key_path}" "${vmid}" "${qm_bin}"
return 1
fi
else
ssh_refused_since=0
fi
fi
if ((SECONDS >= next_log)); then
elapsed=$((timeout_seconds - (deadline - SECONDS)))
if [[ -n "${last_guest_ip}" ]]; then
echo "Waiting for SSH to worker VM ${vmid} at ${last_guest_ip} as ${guest_user} (${elapsed}s elapsed)..." >&2
if [[ -n "${last_ssh_output}" ]]; then
echo "Last SSH failure: ${last_ssh_output}" >&2
fi
else
echo "Waiting for worker VM ${vmid} to report an IPv4 address ${ip_filter_description} through qemu-guest-agent (${elapsed}s elapsed)..." >&2
fi
next_log=$((SECONDS + 60))
fi
sleep 10
done
if [[ -n "${last_guest_ip}" ]]; then
echo "Worker VM ${vmid} reported guest IP ${last_guest_ip}, but SSH as ${guest_user} never became reachable." >&2
if [[ -n "${last_ssh_output}" ]]; then
echo "Last SSH failure: ${last_ssh_output}" >&2
fi
if [[ -n "${last_host_probe_output}" ]]; then
echo "Last Debian-to-worker probe: ${last_host_probe_output}" >&2
fi
else
echo "Worker VM ${vmid} did not report an IPv4 address ${ip_filter_description} through qemu-guest-agent." >&2
fi
pimox_worker_vm_debug "${host}" "${user}" "${key_path}" "${vmid}" "${qm_bin}"
return 1
}
pimox_generated_mac() {
local vmid="$1"
printf '02:68:10:%02x:%02x:%02x\n' \
$(((vmid >> 16) & 255)) \
$(((vmid >> 8) & 255)) \
$((vmid & 255))
}
pimox_worker_static_ip() {
local index="$1"
local static_ips="$2"
local current_index=1
local ip
static_ips="${static_ips//,/ }"
for ip in ${static_ips}; do
if ((current_index == index)); then
printf '%s\n' "${ip}"
return 0
fi
current_index=$((current_index + 1))
done
return 1
}
pimox_worker_net0_config() {
local vmid="$1"
local bridge="$2"
local mac_mode="${LAB_PIMOX_WORKER_MAC_MODE:-deterministic}"
local mac
case "${mac_mode}" in
auto)
printf 'virtio,bridge=%s\n' "${bridge}"
;;
deterministic)
mac="$(pimox_generated_mac "${vmid}")"
printf 'virtio=%s,bridge=%s\n' "${mac}" "${bridge}"
;;
*)
echo "LAB_PIMOX_WORKER_MAC_MODE must be 'auto' or 'deterministic'." >&2
return 1
;;
esac
}
validate_ipv4_cidr_or_host() {
local value="$1"
[[ "${value}" =~ ^[0-9]{1,3}(\.[0-9]{1,3}){3}(/[0-9]{1,2})?$ ]]
}
configure_pimox_worker_guest_network() {
local pimox_host="$1"
local pimox_user="$2"
local pimox_key="$3"
local vmid="$4"
local qm_bin="$5"
local worker_ip="$6"
local gateway="$7"
local dns_servers="$8"
local interface_name="$9"
local node_name="${10:-}"
local timeout_seconds="${LAB_PIMOX_GUEST_AGENT_CONFIG_TIMEOUT_SECONDS:-300}"
local deadline
local script
local encoded_script
local network_output
local network_exitcode
local worker_address
local lan_probe_host="${LAB_PIMOX_WORKER_LAN_PROBE_HOST:-${LAB_DEBIAN_LAN_IP:-}}"
local require_lan_probe="${LAB_PIMOX_WORKER_REQUIRE_LAN_PROBE:-false}"
local lan_probe_block=""
if ! validate_ipv4_cidr_or_host "${worker_ip}"; then
echo "Invalid LAB_PIMOX_WORKER_STATIC_IPS entry '${worker_ip}' for VM ${vmid}." >&2
return 1
fi
if [[ "${worker_ip}" == */* && "${worker_ip}" != */24 ]]; then
echo "LAB_PIMOX_WORKER_STATIC_IPS currently supports host IPv4 values or /24 CIDRs, got '${worker_ip}'." >&2
return 1
fi
if [[ "${worker_ip}" != */* ]]; then
worker_ip="${worker_ip}/24"
fi
worker_address="${worker_ip%%/*}"
if ! [[ "${gateway}" =~ ^[0-9]{1,3}(\.[0-9]{1,3}){3}$ ]]; then
echo "Invalid LAB_PIMOX_WORKER_GATEWAY '${gateway}'." >&2
return 1
fi
if ! [[ "${dns_servers}" =~ ^[0-9.[:space:]]+$ ]]; then
echo "Invalid LAB_PIMOX_WORKER_DNS_SERVERS '${dns_servers}'." >&2
return 1
fi
if ! [[ "${interface_name}" =~ ^[A-Za-z0-9_.:-]+$ ]]; then
echo "Invalid LAB_PIMOX_WORKER_INTERFACE '${interface_name}'." >&2
return 1
fi
if [[ -n "${node_name}" ]] && ! [[ "${node_name}" =~ ^[A-Za-z0-9_.-]+$ ]]; then
echo "Invalid Pimox guest node name '${node_name}' for VM ${vmid}." >&2
return 1
fi
if [[ -n "${lan_probe_host}" ]] && ! [[ "${lan_probe_host}" =~ ^[0-9]{1,3}(\.[0-9]{1,3}){3}$ ]]; then
echo "Invalid LAB_PIMOX_WORKER_LAN_PROBE_HOST '${lan_probe_host}'." >&2
return 1
fi
if ! truthy "${require_lan_probe}" && ! disabled_value "${require_lan_probe}"; then
echo "LAB_PIMOX_WORKER_REQUIRE_LAN_PROBE must be true or false." >&2
return 1
fi
if truthy "${require_lan_probe}"; then
lan_probe_block="$(cat <<EOF
echo "guest-check: ping gateway ${gateway}"
ping -c 2 -W 2 '${gateway}'
EOF
)"
if [[ -n "${lan_probe_host}" ]]; then
lan_probe_block+="
echo \"guest-check: ping Debian/probe host ${lan_probe_host}\"
ping -c 2 -W 2 '${lan_probe_host}'"
fi
else
lan_probe_block="echo 'guest-check: LAN probe disabled by LAB_PIMOX_WORKER_REQUIRE_LAN_PROBE=false'"
fi
script="$(cat <<EOF
set -eu
echo 'guest-check: initial links'
ip -br link
echo 'guest-check: initial addresses'
ip -br addr || true
echo 'guest-check: initial routes'
ip route || true
if [ -n '${node_name}' ]; then
sudo hostnamectl set-hostname '${node_name}'
sudo sed -i -e '/homelab-arm64-template/d' -e '/^[[:space:]]*127[.]0[.]1[.]1[[:space:]]/d' /etc/hosts
printf '%s\n' '127.0.1.1 ${node_name}.homelab.local ${node_name}' | sudo tee -a /etc/hosts >/dev/null
fi
cat >/tmp/homelab-interfaces <<'INTERFACES'
auto lo
iface lo inet loopback
auto ${interface_name}
iface ${interface_name} inet static
address ${worker_address}
netmask 255.255.255.0
gateway ${gateway}
dns-nameservers ${dns_servers}
INTERFACES
sudo cp /tmp/homelab-interfaces /etc/network/interfaces
sudo mkdir -p /etc/cloud/cloud.cfg.d
printf '%s\n' 'network: {config: disabled}' | sudo tee /etc/cloud/cloud.cfg.d/99-disable-network-config.cfg >/dev/null
for unit in systemd-networkd systemd-networkd.socket NetworkManager dhcpcd; do
sudo systemctl disable --now "\$unit" >/dev/null 2>&1 || true
done
sudo pkill -x dhclient >/dev/null 2>&1 || true
sudo pkill -x dhcpcd >/dev/null 2>&1 || true
sudo systemctl enable networking >/dev/null 2>&1 || true
if command -v timeout >/dev/null 2>&1; then
sudo timeout 20 ifdown --force ${interface_name} 2>/dev/null || true
else
sudo ifdown --force ${interface_name} 2>/dev/null || true
fi
sudo ip addr flush dev ${interface_name} scope global || true
sudo ip route flush dev ${interface_name} || true
sudo ip link set ${interface_name} up
sudo ip addr add ${worker_ip} dev ${interface_name}
sudo ip route replace default via ${gateway} dev ${interface_name} src ${worker_address}
printf '%s\n' ${dns_servers} | awk '{ for (i = 1; i <= NF; i++) print "nameserver " \$i }' | sudo tee /etc/resolv.conf >/dev/null
sudo ssh-keygen -A
sudo install -d -m 0755 /run/sshd
sudo mkdir -p /etc/ssh/sshd_config.d
sudo tee /etc/ssh/sshd_config.d/99-homelab-worker-listen.conf >/dev/null <<'SSHD_CONFIG'
Port 22
ListenAddress 0.0.0.0
PubkeyAuthentication yes
PasswordAuthentication no
KbdInteractiveAuthentication no
PermitRootLogin no
UsePAM yes
SSHD_CONFIG
sudo sshd -t
sudo systemctl unmask ssh.service ssh.socket sshd.service sshd.socket >/dev/null 2>&1 || true
sudo systemctl disable --now ssh.socket sshd.socket >/dev/null 2>&1 || true
ssh_unit=ssh.service
if ! systemctl list-unit-files ssh.service 2>/dev/null | grep -q '^ssh[.]service'; then
ssh_unit=sshd.service
fi
sudo systemctl enable "\$ssh_unit" >/dev/null
sudo systemctl restart "\$ssh_unit"
ip -br addr show ${interface_name}
ip route
ip -4 addr show dev ${interface_name} | grep -q '${worker_address}/'
${lan_probe_block}
echo 'guest-check: ssh service'
sudo systemctl is-active "\$ssh_unit"
if command -v ss >/dev/null 2>&1; then
ss -ltnp 2>/dev/null || ss -ltn
ss -ltn | awk '\$4 == "0.0.0.0:22" { found = 1 } END { exit found ? 0 : 1 }'
fi
EOF
)"
encoded_script="$(printf '%s' "${script}" | base64 | tr -d '\n')"
deadline=$((SECONDS + timeout_seconds))
while ((SECONDS < deadline)); do
if network_output="$(pimox_ssh "${pimox_host}" "${pimox_user}" "${pimox_key}" "sudo '${qm_bin}' guest exec '${vmid}' -- bash -lc \"printf '%s' '${encoded_script}' | base64 -d | sudo bash\"" 2>&1)"; then
printf '%s\n' "${network_output}" | sed 's/^/ guest-network: /'
if network_exitcode="$(pimox_guest_exec_exitcode "${network_output}")" && [[ "${network_exitcode}" == "0" ]]; then
return 0
fi
echo "Static guest network validation failed inside Pimox VM ${vmid}." >&2
if [[ -n "${network_exitcode:-}" ]]; then
echo "Guest exit code: ${network_exitcode}" >&2
fi
return 1
fi
sleep 5
done
echo "Timed out configuring static guest network for Pimox VM ${vmid} through qemu-guest-agent." >&2
if [[ -n "${network_output:-}" ]]; then
printf '%s\n' "${network_output}" | sed 's/^/ /' >&2
fi
pimox_worker_guest_agent_recovery_hint "${pimox_host}" "${pimox_user}" "${vmid}" "${qm_bin}"
return 1
}
configure_pimox_worker_forwarding() {
local pimox_host="$1"
local pimox_user="$2"
local pimox_key="$3"
local worker_ip="$4"
local enabled="${LAB_PIMOX_WORKER_CONFIGURE_FORWARDING:-true}"
local backup_dir="${LAB_PIMOX_WORKER_IPTABLES_BACKUP_DIR:-~/iptables-backups}"
local worker_address
if disabled_value "${enabled}"; then
return 0
fi
if ! truthy "${enabled}"; then
echo "LAB_PIMOX_WORKER_CONFIGURE_FORWARDING must be true or false." >&2
return 1
fi
if ! validate_ipv4_cidr_or_host "${worker_ip}"; then
echo "Invalid Pimox worker forwarding IP '${worker_ip}'." >&2
return 1
fi
worker_address="${worker_ip%%/*}"
pimox_ssh "${pimox_host}" "${pimox_user}" "${pimox_key}" "set -eu
iptables_bin=\"\$(command -v iptables 2>/dev/null || true)\"
if [ -z \"\$iptables_bin\" ] && [ -x /usr/sbin/iptables ]; then
iptables_bin=/usr/sbin/iptables
fi
if [ -z \"\$iptables_bin\" ]; then
if command -v apt-get >/dev/null 2>&1; then
echo 'iptables not found on Pimox host; installing iptables for worker forwarding rules.'
sudo apt-get update
sudo apt-get install -y --no-install-recommends iptables
fi
fi
iptables_bin=\"\$(command -v iptables 2>/dev/null || true)\"
if [ -z \"\$iptables_bin\" ] && [ -x /usr/sbin/iptables ]; then
iptables_bin=/usr/sbin/iptables
fi
if [ -z \"\$iptables_bin\" ]; then
echo 'iptables not found on Pimox host and could not be installed; cannot configure worker forwarding rules.' >&2
exit 1
fi
iptables_wait_seconds='${LAB_PIMOX_WORKER_IPTABLES_WAIT_SECONDS:-60}'
case \"\$iptables_wait_seconds\" in
''|*[!0-9]*)
echo \"LAB_PIMOX_WORKER_IPTABLES_WAIT_SECONDS must be a non-negative integer, got '\$iptables_wait_seconds'.\" >&2
exit 1
;;
esac
iptables_wait_args=
if \"\$iptables_bin\" -h 2>&1 | grep -q -- ' -w'; then
iptables_wait_args=\"-w \$iptables_wait_seconds\"
else
echo 'Pimox host iptables does not support -w; proceeding without xtables lock wait.'
fi
iptables_cmd() {
sudo \"\$iptables_bin\" \$iptables_wait_args \"\$@\"
}
iptables_save_bin=\"\$(command -v iptables-save 2>/dev/null || true)\"
if [ -z \"\$iptables_save_bin\" ] && [ -x /usr/sbin/iptables-save ]; then
iptables_save_bin=/usr/sbin/iptables-save
fi
backup_dir='${backup_dir}'
case \"\$backup_dir\" in
'~'|'~/') backup_dir=\"\$HOME\" ;;
'~/'*) backup_dir=\"\$HOME/\${backup_dir#~/}\" ;;
*/'~/'*) backup_dir=\"\${backup_dir%%/~/*}/\${backup_dir#*/~/}\" ;;
esac
mkdir -p \"\$backup_dir\"
backup_file=\"\$backup_dir/iptables-before-jeannie-workers-\$(date +%Y%m%d-%H%M%S).rules\"
if [ -n \"\$iptables_save_bin\" ]; then
sudo \"\$iptables_save_bin\" >\"\$backup_file\"
echo \"Saved Pimox iptables backup: \$backup_file\"
fi
sudo mkdir -p /etc/sysctl.d
printf '%s\n' 'net.ipv4.ip_forward = 1' | sudo tee /etc/sysctl.d/99-homelab-pimox-worker-forwarding.conf >/dev/null
sudo sysctl -w net.ipv4.ip_forward=1 >/dev/null
chain=FORWARD
if iptables_cmd -S DOCKER-USER >/dev/null 2>&1; then
chain=DOCKER-USER
fi
if ! iptables_cmd -C \"\$chain\" -s '${worker_address}/32' -j ACCEPT 2>/dev/null; then
iptables_cmd -I \"\$chain\" 1 -s '${worker_address}/32' -j ACCEPT
fi
if ! iptables_cmd -C \"\$chain\" -d '${worker_address}/32' -j ACCEPT 2>/dev/null; then
iptables_cmd -I \"\$chain\" 1 -d '${worker_address}/32' -j ACCEPT
fi
echo \"Pimox worker forwarding rules active in \$chain for ${worker_address}\""
}
iptables_cmd() {
sudo \"\$iptables_bin\" \$iptables_wait_args \"\$@\"
}
cpuset_cpu_count() {
local cpuset="$1"
local count=0
local part
local start
local end
local -a parts
IFS=',' read -r -a parts <<<"${cpuset}"
for part in "${parts[@]}"; do
if [[ "${part}" =~ ^([0-9]+)-([0-9]+)$ ]]; then
start="${BASH_REMATCH[1]}"
end="${BASH_REMATCH[2]}"
if ((end < start)); then
return 1
fi
count=$((count + end - start + 1))
elif [[ "${part}" =~ ^[0-9]+$ ]]; then
count=$((count + 1))
else
return 1
fi
done
printf '%s\n' "${count}"
}
pimox_worker_cpu_affinity() {
local index="$1"
local affinities="$2"
local worker_cores="$3"
local affinity
local affinity_index=1
local cpu_count
for affinity in ${affinities}; do
if ((affinity_index == index)); then
if ! cpu_count="$(cpuset_cpu_count "${affinity}")"; then
echo "Invalid Pimox worker CPU affinity '${affinity}'. Use CPU IDs or ranges, such as 4-5." >&2
exit 1
fi
if ((cpu_count != worker_cores)); then
echo "Pimox worker index ${index} uses ${worker_cores} cores but affinity '${affinity}' contains ${cpu_count} CPUs." >&2
exit 1
fi
printf '%s\n' "${affinity}"
return 0
fi
affinity_index=$((affinity_index + 1))
done
echo "No LAB_PIMOX_WORKER_CPU_AFFINITIES entry exists for Pimox worker index ${index}." >&2
exit 1
}
pimox_start_vm_with_cpuset() {
local host="$1"
local user="$2"
local key_path="$3"
local qm_bin="$4"
local vmid="$5"
local cpuset="$6"
if [[ -z "${cpuset}" ]]; then
pimox_ssh "${host}" "${user}" "${key_path}" "sudo '${qm_bin}' start '${vmid}'"
return
fi
if ! cpuset_cpu_count "${cpuset}" >/dev/null; then
echo "Invalid Pimox KVM CPU set '${cpuset}'. Use CPU IDs or ranges, such as 4-7." >&2
exit 1
fi
# Pimox 7 daemonizes qm start before KVM is spawned. Launch qm's generated
# command under taskset so PSCI brings secondary guest CPUs online reliably.
pimox_ssh "${host}" "${user}" "${key_path}" "set -eu
vmid='${vmid}'
qm_bin='${qm_bin}'
cpuset='${cpuset}'
if ! command -v taskset >/dev/null 2>&1; then
echo 'taskset is required to start this Pimox VM with a KVM CPU set' >&2
exit 1
fi
if ! taskset -c \"\$cpuset\" true >/dev/null 2>&1; then
echo \"Pimox KVM CPU set \$cpuset is not valid on this host\" >&2
exit 1
fi
start_script=\$(mktemp \"/tmp/homelab-qemu-\${vmid}.XXXXXX\")
cleanup() {
rm -f \"\$start_script\"
}
trap cleanup 0
sudo \"\$qm_bin\" showcmd \"\$vmid\" --pretty >\"\$start_script\"
if ! { grep -Fq -- '/usr/bin/kvm' \"\$start_script\" || grep -Fq -- 'qemu-system-aarch64' \"\$start_script\"; } ||
! grep -Fq -- \"-id \$vmid\" \"\$start_script\"; then
echo \"qm showcmd for VM \$vmid did not produce the expected KVM command\" >&2
sed 's/^/ showcmd: /' \"\$start_script\" >&2
exit 1
fi
smp_count=\$(grep -c '^[[:space:]]*-smp[[:space:]]' \"\$start_script\" || true)
if [ \"\$smp_count\" -ne 1 ]; then
echo \"Expected one native -smp argument for VM \$vmid, found \$smp_count. Remove stale qm args before starting.\" >&2
exit 1
fi
sudo taskset -c \"\$cpuset\" bash \"\$start_script\""
}
ensure_pimox_pin_hookscript() {
local host="$1"
local user="$2"
local key_path="$3"
local qm_bin="$4"
local storage="$5"
local script_name="$6"
local cpu_map="$7"
local script_ref="${storage}:snippets/${script_name}"
local snippets_dir="${LAB_PIMOX_PIN_HOOKSCRIPT_SNIPPETS_DIR:-/var/lib/vz/snippets}"
local remote_tmp="/tmp/homelab-${script_name}"
local local_tmp
local entry
local vmid
local cpuset
local map_lines=""
if [[ -z "${cpu_map}" ]]; then
return 0
fi
if ! [[ "${storage}" =~ ^[A-Za-z0-9_.:-]+$ ]]; then
echo "LAB_PIMOX_PIN_HOOKSCRIPT_STORAGE must be a valid Pimox storage identifier." >&2
exit 1
fi
if ! [[ "${script_name}" =~ ^[A-Za-z0-9_.-]+$ ]]; then
echo "LAB_PIMOX_PIN_HOOKSCRIPT_NAME must be a safe file name." >&2
exit 1
fi
for entry in ${cpu_map}; do
vmid="${entry%%=*}"
cpuset="${entry#*=}"
if [[ "${vmid}" == "${entry}" || -z "${vmid}" || -z "${cpuset}" ]]; then
echo "Invalid LAB_PIMOX_PIN_CPU_MAP entry '${entry}'. Use VMID=CPUSET, for example 9001=4-7." >&2
exit 1
fi
if ! [[ "${vmid}" =~ ^[0-9]+$ ]]; then
echo "Invalid LAB_PIMOX_PIN_CPU_MAP VMID '${vmid}'." >&2
exit 1
fi
if ! cpuset_cpu_count "${cpuset}" >/dev/null; then
echo "Invalid LAB_PIMOX_PIN_CPU_MAP CPU set '${cpuset}' for VM ${vmid}. Use CPU IDs or ranges, such as 4-7." >&2
exit 1
fi
map_lines+=" ${vmid} => \"${cpuset}\","$'\n'
done
local_tmp="$(mktemp "${TMPDIR:-/tmp}/homelab-pimox-pin.XXXXXX")"
# shellcheck disable=SC2016
{
printf '%s\n' '#!/usr/bin/perl'
printf '%s\n' 'use strict; use warnings;'
printf '%s\n' 'my ($vmid, $phase) = @ARGV;'
printf '%s\n' 'my %cpus = ('
printf '%s' "${map_lines}"
printf '%s\n' ');'
printf '%s\n' "if (\$phase eq 'post-start' && \$cpus{\$vmid}) {"
printf '%s\n' ' my $pid_file = "/var/run/qemu-server/$vmid.pid";'
printf '%s\n' ' exit(0) unless -r $pid_file;'
printf '%s\n' ' chomp(my $pid = `cat $pid_file`);'
printf '%s\n' ' system("taskset -cp $cpus{$vmid} $pid >/dev/null 2>&1");'
printf '%s\n' ' open(my $threads, "-|", "ps -L -o tid= -p $pid 2>/dev/null") or exit(0);'
printf '%s\n' ' while (my $tid = <$threads>) {'
printf '%s\n' ' chomp($tid);'
printf '%s\n' ' next unless $tid =~ /^\d+$/;'
printf '%s\n' ' system("taskset -cp $cpus{$vmid} $tid >/dev/null 2>&1");'
printf '%s\n' ' }'
printf '%s\n' '}'
printf '%s\n' 'exit(0);'
} >"${local_tmp}"
echo "Installing Pimox KVM CPU pin hookscript ${script_ref} with map: ${cpu_map}"
pimox_ssh "${host}" "${user}" "${key_path}" "mkdir -p /tmp"
pimox_scp "${key_path}" "${local_tmp}" "${user}@${host}:${remote_tmp}"
rm -f "${local_tmp}"
pimox_ssh "${host}" "${user}" "${key_path}" "set -eu
sudo mkdir -p '${snippets_dir}'
sudo install -m 0755 '${remote_tmp}' '${snippets_dir}/${script_name}'
rm -f '${remote_tmp}'"
for entry in ${cpu_map}; do
vmid="${entry%%=*}"
cpuset="${entry#*=}"
pimox_ssh "${host}" "${user}" "${key_path}" "set -eu
if sudo '${qm_bin}' status '${vmid}' >/dev/null 2>&1; then
sudo '${qm_bin}' set '${vmid}' --hookscript '${script_ref}'
if sudo '${qm_bin}' status '${vmid}' | grep -q 'status: running'; then
if ! command -v taskset >/dev/null 2>&1; then
echo 'taskset is required to enforce Pimox KVM CPU pinning for running VM ${vmid}' >&2
exit 1
fi
pid_file='/var/run/qemu-server/${vmid}.pid'
if ! sudo test -r \"\$pid_file\"; then
echo 'Pimox VM ${vmid} is running but its QEMU pid file is missing; cannot enforce CPU pinning.' >&2
exit 1
fi
pid=\"\$(sudo cat \"\$pid_file\")\"
echo 'Applying Pimox KVM CPU affinity ${cpuset} to running VM ${vmid} pid' \"\$pid\"
sudo taskset -cp '${cpuset}' \"\$pid\" >/dev/null
if command -v ps >/dev/null 2>&1; then
ps -L -o tid= -p \"\$pid\" 2>/dev/null | while read -r tid; do
case \"\$tid\" in
''|*[!0-9]*) continue ;;
esac
sudo taskset -cp '${cpuset}' \"\$tid\" >/dev/null 2>&1 || true
done
fi
fi
fi"
done
}
pimox_shutdown_vm_gracefully() {
local host="$1"
local user="$2"
local key_path="$3"
local qm_bin="$4"
local vmid="$5"
pimox_ssh "${host}" "${user}" "${key_path}" "set -eu
sudo '${qm_bin}' shutdown '${vmid}' --timeout 120 || true
elapsed=0
while [ \"\$elapsed\" -lt 300 ]; do
if sudo '${qm_bin}' status '${vmid}' | grep -q 'status: stopped'; then
exit 0
fi
sleep 5
elapsed=\$((elapsed + 5))
done
echo 'VM ${vmid} did not stop gracefully within 300 seconds.' >&2
exit 1"
}
pimox_guest_cpu_count() {
local guest_ip="$1"
local guest_user="$2"
local guest_key_path="$3"
local known_hosts_file="${REPO_ROOT}/.lab/pimox-worker-known_hosts"
ssh -i "${guest_key_path}" \
-o BatchMode=yes \
-o ConnectTimeout=10 \
-o IdentitiesOnly=yes \
-o StrictHostKeyChecking=accept-new \
-o UserKnownHostsFile="${known_hosts_file}" \
"${guest_user}@${guest_ip}" \
'nproc --all'
}
ensure_pimox_guest_root_disk_size() {
local pimox_host="$1"
local pimox_user="$2"
local pimox_key="$3"
local vmid="$4"
local qm_bin="$5"
local guest_ip="$6"
local guest_user="$7"
local guest_key_path="$8"
local desired_gib="$9"
local description="${10}"
local known_hosts_file="${REPO_ROOT}/.lab/pimox-worker-known_hosts"
local current_gib
if ! [[ "${desired_gib}" =~ ^[0-9]+$ ]] || ((desired_gib <= 0)); then
echo "Desired Pimox guest disk size must be a positive integer GiB value; got '${desired_gib}'." >&2
exit 1
fi
current_gib="$(pimox_ssh "${pimox_host}" "${pimox_user}" "${pimox_key}" "sudo '${qm_bin}' config '${vmid}' | awk -F'size=' '/^scsi0:/ { split(\$2, a, /[,G]/); print a[1]; exit }'" 2>/dev/null || true)"
if [[ "${current_gib}" =~ ^[0-9]+$ ]] && ((current_gib < desired_gib)); then
echo "Resizing ${description} scsi0 from ${current_gib}G to ${desired_gib}G..."
pimox_ssh "${pimox_host}" "${pimox_user}" "${pimox_key}" "sudo '${qm_bin}' resize '${vmid}' scsi0 '${desired_gib}G'"
elif [[ -z "${current_gib}" ]]; then
echo "Could not read ${description} scsi0 size; continuing with guest filesystem growth check." >&2
fi
ssh -i "${guest_key_path}" \
-o BatchMode=yes \
-o ConnectTimeout=10 \
-o IdentitiesOnly=yes \
-o StrictHostKeyChecking=accept-new \
-o UserKnownHostsFile="${known_hosts_file}" \
"${guest_user}@${guest_ip}" \
"set -eu
if ! command -v growpart >/dev/null 2>&1 || ! command -v crictl >/dev/null 2>&1; then
sudo apt-get update
sudo apt-get install -y --no-install-recommends cloud-guest-utils e2fsprogs cri-tools
fi
root_source=\"\$(findmnt -no SOURCE /)\"
root_fstype=\"\$(findmnt -no FSTYPE /)\"
part_num=\"\$(printf '%s' \"\$root_source\" | sed -n 's/.*[^0-9]\\([0-9][0-9]*\\)$/\\1/p')\"
if [ -z \"\$part_num\" ]; then
echo \"Could not detect root partition number from \$root_source\" >&2
exit 1
fi
case \"\$root_source\" in
*p\"\$part_num\") disk=\"\${root_source%p\$part_num}\" ;;
*) disk=\"\${root_source%\$part_num}\" ;;
esac
sudo growpart \"\$disk\" \"\$part_num\" || true
case \"\$root_fstype\" in
ext2|ext3|ext4)
sudo resize2fs \"\$root_source\"
;;
xfs)
if ! command -v xfs_growfs >/dev/null 2>&1; then
sudo apt-get update
sudo apt-get install -y --no-install-recommends xfsprogs
fi
sudo xfs_growfs /
;;
*)
echo \"Unsupported root filesystem type \$root_fstype for automatic online grow.\" >&2
exit 1
;;
esac
df -h /
crictl --version || true"
}
ensure_pimox_worker_node() {
local index="$1"
local spec_file="$2"
local pimox_host="$3"
local pimox_user="$4"
local pimox_key="$5"
local template_vmid="$6"
local bridge="$7"
local worker_base_vmid="$8"
local worker_name_prefix="$9"
local worker_node_prefix="${10}"
local worker_key_prefix="${11}"
local worker_cores="${12}"
local worker_memory="${13}"
local worker_user="${14}"
local worker_key_path="${15}"
local ip_prefix="${16}"
local timeout_seconds="${17}"
local qm_bin="${18}"
local worker_storage="${19}"
local worker_replace_existing="${20}"
local worker_cpu_affinity="${21}"
local worker_kvm_cpuset="${22}"
local worker_hookscript_ref="${23}"
local worker_disk_gib="${24}"
local worker_network_mode="${LAB_PIMOX_WORKER_NETWORK_MODE:-static}"
local worker_static_ips="${LAB_PIMOX_WORKER_STATIC_IPS:-192.168.100.66 192.168.100.67 192.168.100.76}"
local worker_gateway="${LAB_PIMOX_WORKER_GATEWAY:-192.168.100.1}"
local worker_dns_servers="${LAB_PIMOX_WORKER_DNS_SERVERS:-192.168.100.89 1.1.1.1}"
local worker_interface="${LAB_PIMOX_WORKER_INTERFACE:-enp0s18}"
local padded
local vmid
local worker_key
local worker_name
local node_name
local net0_config
local guest_ip
local guest_cpu_count
local static_ip
printf -v padded '%02d' "${index}"
vmid=$((worker_base_vmid + index - 1))
worker_key="${worker_key_prefix}${padded}"
worker_name="${worker_name_prefix}-${padded}"
node_name="${worker_node_prefix}-${padded}"
if ! net0_config="$(pimox_worker_net0_config "${vmid}" "${bridge}")"; then
exit 1
fi
if pimox_ssh "${pimox_host}" "${pimox_user}" "${pimox_key}" "sudo '${qm_bin}' status '${vmid}' >/dev/null 2>&1"; then
if pimox_ssh "${pimox_host}" "${pimox_user}" "${pimox_key}" "sudo '${qm_bin}' config '${vmid}' | grep -q '^template: 1$'"; then
echo "VM ${vmid} exists as a template; refusing to reuse it as worker ${worker_name}." >&2
exit 1
fi
if ! truthy "${worker_replace_existing}" &&
! pimox_ssh "${pimox_host}" "${pimox_user}" "${pimox_key}" "sudo '${qm_bin}' config '${vmid}' | awk -F': ' -v storage='${worker_storage}' '/^(scsi|virtio|sata|ide)[0-9]+:/ { disks = 1; if (\$2 !~ \"^\" storage \":\") bad = 1 } END { exit (disks && !bad) ? 0 : 1 }'"; then
echo "Existing Pimox worker VM ${vmid} (${worker_name}) is not fully on storage ${worker_storage}; replacing it from template ${template_vmid}."
worker_replace_existing=true
fi
if truthy "${worker_replace_existing}"; then
echo "Replacing existing Pimox worker VM ${vmid} (${worker_name}) before cloning from template ${template_vmid}..."
pimox_ssh "${pimox_host}" "${pimox_user}" "${pimox_key}" "set -eu
sudo '${qm_bin}' stop '${vmid}' >/dev/null 2>&1 || true
elapsed=0
while [ \"\$elapsed\" -lt 300 ]; do
if sudo '${qm_bin}' status '${vmid}' | grep -q 'status: stopped'; then
break
fi
sleep 5
elapsed=\$((elapsed + 5))
done
sudo '${qm_bin}' destroy '${vmid}' --purge 1 >/dev/null 2>&1 || sudo '${qm_bin}' destroy '${vmid}'"
else
pimox_ssh "${pimox_host}" "${pimox_user}" "${pimox_key}" "set -eu
was_running=false
had_legacy_args=false
if sudo '${qm_bin}' status '${vmid}' | grep -q 'status: running'; then
was_running=true
fi
if sudo '${qm_bin}' config '${vmid}' | grep -q '^args:'; then
had_legacy_args=true
fi
sudo '${qm_bin}' set '${vmid}' \
--agent enabled=1 \
--bios ovmf \
--boot 'order=scsi0;net0' \
--cores '${worker_cores}' \
--memory '${worker_memory}' \
--net0 '${net0_config}' \
--numa 0 \
--ostype l26 \
--scsihw virtio-scsi-pci \
--sockets 1 \
--vga virtio
if [ \"\$had_legacy_args\" = true ]; then
sudo '${qm_bin}' set '${vmid}' --delete args
fi
if [ -n '${worker_hookscript_ref}' ]; then
sudo '${qm_bin}' set '${vmid}' --hookscript '${worker_hookscript_ref}'
fi
if [ -n '${worker_cpu_affinity}' ]; then
affinity_output=\"\$(sudo '${qm_bin}' set '${vmid}' --affinity '${worker_cpu_affinity}' 2>&1)\" || {
case \"\$affinity_output\" in
*'Unknown option: affinity'*)
echo 'Pimox qm does not support --affinity; skipping CPU affinity ${worker_cpu_affinity} for VM ${vmid}.'
;;
*)
printf '%s\n' \"\$affinity_output\" >&2
exit 1
;;
esac
}
fi
if [ \"\$had_legacy_args\" = true ] && [ \"\$was_running\" = true ]; then
echo 'Restarting VM ${vmid} to apply removal of legacy qm args.'
sudo '${qm_bin}' shutdown '${vmid}' --timeout 120 || true
elapsed=0
while [ \"\$elapsed\" -lt 300 ]; do
if sudo '${qm_bin}' status '${vmid}' | grep -q 'status: stopped'; then
break
fi
sleep 5
elapsed=\$((elapsed + 5))
done
if ! sudo '${qm_bin}' status '${vmid}' | grep -q 'status: stopped'; then
echo 'VM ${vmid} did not stop after removing legacy qm args.' >&2
exit 1
fi
fi"
fi
fi
if ! pimox_ssh "${pimox_host}" "${pimox_user}" "${pimox_key}" "sudo '${qm_bin}' status '${vmid}' >/dev/null 2>&1"; then
pimox_ssh "${pimox_host}" "${pimox_user}" "${pimox_key}" "set -eu
if ! ip link show '${bridge}' >/dev/null 2>&1; then
echo 'Pimox bridge ${bridge} does not exist. Refusing to change Orange Pi networking.' >&2
exit 1
fi
pvesm_cmd=\"\$(command -v pvesm 2>/dev/null || true)\"
if [ -z \"\$pvesm_cmd\" ] && [ -x /usr/sbin/pvesm ]; then
pvesm_cmd=/usr/sbin/pvesm
fi
if [ -z \"\$pvesm_cmd\" ]; then
echo 'pvesm was not found; cannot validate Pimox worker storage ${worker_storage}' >&2
exit 1
fi
if ! sudo \"\$pvesm_cmd\" status | awk -v storage='${worker_storage}' 'NR > 1 && \$1 == storage { found = 1 } END { exit found ? 0 : 1 }'; then
echo 'Pimox worker storage ${worker_storage} was not found. Refusing to create worker ${worker_name}.' >&2
exit 1
fi
sudo '${qm_bin}' clone '${template_vmid}' '${vmid}' --name '${worker_name}' --full 1 --storage '${worker_storage}'
sudo '${qm_bin}' set '${vmid}' \
--agent enabled=1 \
--bios ovmf \
--boot 'order=scsi0;net0' \
--cores '${worker_cores}' \
--memory '${worker_memory}' \
--net0 '${net0_config}' \
--numa 0 \
--ostype l26 \
--scsihw virtio-scsi-pci \
--sockets 1 \
--vga virtio
if sudo '${qm_bin}' config '${vmid}' | grep -q '^args:'; then
sudo '${qm_bin}' set '${vmid}' --delete args
fi
if [ -n '${worker_hookscript_ref}' ]; then
sudo '${qm_bin}' set '${vmid}' --hookscript '${worker_hookscript_ref}'
fi
if [ -n '${worker_cpu_affinity}' ]; then
affinity_output=\"\$(sudo '${qm_bin}' set '${vmid}' --affinity '${worker_cpu_affinity}' 2>&1)\" || {
case \"\$affinity_output\" in
*'Unknown option: affinity'*)
echo 'Pimox qm does not support --affinity; skipping CPU affinity ${worker_cpu_affinity} for VM ${vmid}.'
;;
*)
printf '%s\n' \"\$affinity_output\" >&2
exit 1
;;
esac
}
fi
sudo '${qm_bin}' set '${vmid}' --onboot 1"
fi
if pimox_ssh "${pimox_host}" "${pimox_user}" "${pimox_key}" "sudo '${qm_bin}' status '${vmid}' | grep -q 'status: stopped'"; then
pimox_start_vm_with_cpuset "${pimox_host}" "${pimox_user}" "${pimox_key}" "${qm_bin}" "${vmid}" "${worker_kvm_cpuset}"
elif ! pimox_ssh "${pimox_host}" "${pimox_user}" "${pimox_key}" "sudo '${qm_bin}' status '${vmid}' | grep -q 'status: running'"; then
echo "Pimox worker VM ${vmid} (${worker_name}) is neither stopped nor running after configuration." >&2
exit 1
fi
case "${worker_network_mode}" in
static)
if ! static_ip="$(pimox_worker_static_ip "${index}" "${worker_static_ips}")"; then
echo "LAB_PIMOX_WORKER_NETWORK_MODE=static requires LAB_PIMOX_WORKER_STATIC_IPS to include an IP for worker index ${index}." >&2
exit 1
fi
echo "Configuring Pimox worker VM ${vmid} static network ${static_ip} via qemu-guest-agent..."
configure_pimox_worker_forwarding \
"${pimox_host}" \
"${pimox_user}" \
"${pimox_key}" \
"${static_ip}"
if ! configure_pimox_worker_guest_network \
"${pimox_host}" \
"${pimox_user}" \
"${pimox_key}" \
"${vmid}" \
"${qm_bin}" \
"${static_ip}" \
"${worker_gateway}" \
"${worker_dns_servers}" \
"${worker_interface}" \
"${node_name}"; then
pimox_worker_vm_debug "${pimox_host}" "${pimox_user}" "${pimox_key}" "${vmid}" "${qm_bin}"
exit 1
fi
;;
dhcp)
;;
*)
echo "LAB_PIMOX_WORKER_NETWORK_MODE must be 'static' or 'dhcp'." >&2
exit 1
;;
esac
if ! guest_ip="$(wait_for_pimox_guest_ssh "${pimox_host}" "${pimox_user}" "${pimox_key}" "${vmid}" "${worker_user}" "${worker_key_path}" "${ip_prefix}" "${timeout_seconds}" "${qm_bin}")"; then
echo "Timed out waiting for worker VM ${vmid} (${worker_name}) to report a reachable guest IP." >&2
exit 1
fi
ensure_pimox_guest_root_disk_size \
"${pimox_host}" \
"${pimox_user}" \
"${pimox_key}" \
"${vmid}" \
"${qm_bin}" \
"${guest_ip}" \
"${worker_user}" \
"${worker_key_path}" \
"${worker_disk_gib}" \
"Pimox worker VM ${vmid} (${worker_name})"
guest_cpu_count="$(pimox_guest_cpu_count "${guest_ip}" "${worker_user}" "${worker_key_path}" 2>/dev/null || true)"
if ! [[ "${guest_cpu_count}" =~ ^[0-9]+$ ]] || ((guest_cpu_count < worker_cores)); then
echo "Pimox worker VM ${vmid} (${worker_name}) reports ${guest_cpu_count:-unknown} CPU(s); restarting through the pinned KVM launch path." >&2
pimox_shutdown_vm_gracefully "${pimox_host}" "${pimox_user}" "${pimox_key}" "${qm_bin}" "${vmid}"
pimox_start_vm_with_cpuset "${pimox_host}" "${pimox_user}" "${pimox_key}" "${qm_bin}" "${vmid}" "${worker_kvm_cpuset}"
if ! guest_ip="$(wait_for_pimox_guest_ssh "${pimox_host}" "${pimox_user}" "${pimox_key}" "${vmid}" "${worker_user}" "${worker_key_path}" "${ip_prefix}" "${timeout_seconds}" "${qm_bin}")"; then
echo "Timed out waiting for worker VM ${vmid} (${worker_name}) after pinned KVM restart." >&2
exit 1
fi
guest_cpu_count="$(pimox_guest_cpu_count "${guest_ip}" "${worker_user}" "${worker_key_path}" 2>/dev/null || true)"
fi
if ! [[ "${guest_cpu_count}" =~ ^[0-9]+$ ]] || ((guest_cpu_count < worker_cores)); then
echo "Pimox worker VM ${vmid} (${worker_name}) reports ${guest_cpu_count:-unknown} CPU(s); expected at least ${worker_cores}." >&2
echo "On Pimox 7 ARM this means KVM was not launched on a compatible host CPU set. Check LAB_PIMOX_WORKER_KVM_CPUSET (default: 4-7)." >&2
exit 1
fi
printf '%s\t%s\t%s\t%s\t%s\n' "${worker_key}" "${guest_ip}" "${worker_user}" "${node_name}" "${worker_key_path}" >>"${spec_file}"
}
ensure_pimox_control_plane_node() {
local pimox_host="$1"
local pimox_user="$2"
local pimox_key="$3"
local template_vmid="$4"
local bridge="$5"
local vmid="$6"
local vm_name="$7"
local node_ip="$8"
local guest_user="$9"
local guest_key_path="${10}"
local ip_prefix="${11}"
local timeout_seconds="${12}"
local qm_bin="${13}"
local storage="${14}"
local replace_existing="${15}"
local cores="${16}"
local memory="${17}"
local cpu_affinity="${18}"
local kvm_cpuset="${19}"
local hookscript_ref="${20}"
local disk_gib="${21}"
local network_mode="${LAB_PIMOX_CONTROL_PLANE_NETWORK_MODE:-${LAB_PIMOX_WORKER_NETWORK_MODE:-static}}"
local gateway="${LAB_PIMOX_CONTROL_PLANE_GATEWAY:-${LAB_PIMOX_WORKER_GATEWAY:-192.168.100.1}}"
local dns_servers="${LAB_PIMOX_CONTROL_PLANE_DNS_SERVERS:-${LAB_PIMOX_WORKER_DNS_SERVERS:-192.168.100.89 1.1.1.1}}"
local interface_name="${LAB_PIMOX_CONTROL_PLANE_INTERFACE:-${LAB_PIMOX_WORKER_INTERFACE:-enp0s18}}"
local net0_config
local guest_ip
local guest_cpu_count
if ! net0_config="$(pimox_worker_net0_config "${vmid}" "${bridge}")"; then
exit 1
fi
if pimox_ssh "${pimox_host}" "${pimox_user}" "${pimox_key}" "sudo '${qm_bin}' status '${vmid}' >/dev/null 2>&1"; then
if pimox_ssh "${pimox_host}" "${pimox_user}" "${pimox_key}" "sudo '${qm_bin}' config '${vmid}' | grep -q '^template: 1$'"; then
echo "VM ${vmid} exists as a template; refusing to reuse it as control-plane ${vm_name}." >&2
exit 1
fi
if truthy "${replace_existing}"; then
echo "Replacing existing Pimox control-plane VM ${vmid} (${vm_name}) before cloning from template ${template_vmid}..."
pimox_ssh "${pimox_host}" "${pimox_user}" "${pimox_key}" "set -eu
sudo '${qm_bin}' stop '${vmid}' >/dev/null 2>&1 || true
elapsed=0
while [ \"\$elapsed\" -lt 300 ]; do
if sudo '${qm_bin}' status '${vmid}' | grep -q 'status: stopped'; then
break
fi
sleep 5
elapsed=\$((elapsed + 5))
done
sudo '${qm_bin}' destroy '${vmid}' --purge 1 >/dev/null 2>&1 || sudo '${qm_bin}' destroy '${vmid}'"
else
pimox_ssh "${pimox_host}" "${pimox_user}" "${pimox_key}" "set -eu
was_running=false
had_legacy_args=false
if sudo '${qm_bin}' status '${vmid}' | grep -q 'status: running'; then
was_running=true
fi
if sudo '${qm_bin}' config '${vmid}' | grep -q '^args:'; then
had_legacy_args=true
fi
sudo '${qm_bin}' set '${vmid}' \
--agent enabled=1 \
--bios ovmf \
--boot 'order=scsi0;net0' \
--cores '${cores}' \
--memory '${memory}' \
--net0 '${net0_config}' \
--numa 0 \
--ostype l26 \
--scsihw virtio-scsi-pci \
--sockets 1 \
--vga virtio
if [ \"\$had_legacy_args\" = true ]; then
sudo '${qm_bin}' set '${vmid}' --delete args
fi
if [ -n '${hookscript_ref}' ]; then
sudo '${qm_bin}' set '${vmid}' --hookscript '${hookscript_ref}'
fi
if [ -n '${cpu_affinity}' ]; then
affinity_output=\"\$(sudo '${qm_bin}' set '${vmid}' --affinity '${cpu_affinity}' 2>&1)\" || {
case \"\$affinity_output\" in
*'Unknown option: affinity'*)
echo 'Pimox qm does not support --affinity; skipping CPU affinity ${cpu_affinity} for VM ${vmid}.'
;;
*)
printf '%s\n' \"\$affinity_output\" >&2
exit 1
;;
esac
}
fi
if [ \"\$had_legacy_args\" = true ] && [ \"\$was_running\" = true ]; then
echo 'Restarting VM ${vmid} to apply removal of legacy qm args.'
sudo '${qm_bin}' shutdown '${vmid}' --timeout 120 || true
elapsed=0
while [ \"\$elapsed\" -lt 300 ]; do
if sudo '${qm_bin}' status '${vmid}' | grep -q 'status: stopped'; then
break
fi
sleep 5
elapsed=\$((elapsed + 5))
done
if ! sudo '${qm_bin}' status '${vmid}' | grep -q 'status: stopped'; then
echo 'VM ${vmid} did not stop after removing legacy qm args.' >&2
exit 1
fi
fi"
fi
fi
if ! pimox_ssh "${pimox_host}" "${pimox_user}" "${pimox_key}" "sudo '${qm_bin}' status '${vmid}' >/dev/null 2>&1"; then
echo "Creating Pimox control-plane VM ${vmid} (${vm_name}) from template ${template_vmid}..."
pimox_ssh "${pimox_host}" "${pimox_user}" "${pimox_key}" "set -eu
if ! ip link show '${bridge}' >/dev/null 2>&1; then
echo 'Pimox bridge ${bridge} does not exist. Refusing to change Orange Pi networking.' >&2
exit 1
fi
pvesm_cmd=\"\$(command -v pvesm 2>/dev/null || true)\"
if [ -z \"\$pvesm_cmd\" ] && [ -x /usr/sbin/pvesm ]; then
pvesm_cmd=/usr/sbin/pvesm
fi
if [ -z \"\$pvesm_cmd\" ]; then
echo 'pvesm was not found; cannot validate Pimox control-plane storage ${storage}' >&2
exit 1
fi
if ! sudo \"\$pvesm_cmd\" status | awk -v storage='${storage}' 'NR > 1 && \$1 == storage { found = 1 } END { exit found ? 0 : 1 }'; then
echo 'Pimox control-plane storage ${storage} was not found. Refusing to create ${vm_name}.' >&2
exit 1
fi
sudo '${qm_bin}' clone '${template_vmid}' '${vmid}' --name '${vm_name}' --full 1 --storage '${storage}'
sudo '${qm_bin}' set '${vmid}' \
--agent enabled=1 \
--bios ovmf \
--boot 'order=scsi0;net0' \
--cores '${cores}' \
--memory '${memory}' \
--net0 '${net0_config}' \
--numa 0 \
--ostype l26 \
--scsihw virtio-scsi-pci \
--sockets 1 \
--vga virtio
if sudo '${qm_bin}' config '${vmid}' | grep -q '^args:'; then
sudo '${qm_bin}' set '${vmid}' --delete args
fi
if [ -n '${hookscript_ref}' ]; then
sudo '${qm_bin}' set '${vmid}' --hookscript '${hookscript_ref}'
fi
if [ -n '${cpu_affinity}' ]; then
affinity_output=\"\$(sudo '${qm_bin}' set '${vmid}' --affinity '${cpu_affinity}' 2>&1)\" || {
case \"\$affinity_output\" in
*'Unknown option: affinity'*)
echo 'Pimox qm does not support --affinity; skipping CPU affinity ${cpu_affinity} for VM ${vmid}.'
;;
*)
printf '%s\n' \"\$affinity_output\" >&2
exit 1
;;
esac
}
fi
sudo '${qm_bin}' set '${vmid}' --onboot 1"
fi
if pimox_ssh "${pimox_host}" "${pimox_user}" "${pimox_key}" "sudo '${qm_bin}' status '${vmid}' | grep -q 'status: stopped'"; then
pimox_start_vm_with_cpuset "${pimox_host}" "${pimox_user}" "${pimox_key}" "${qm_bin}" "${vmid}" "${kvm_cpuset}"
elif ! pimox_ssh "${pimox_host}" "${pimox_user}" "${pimox_key}" "sudo '${qm_bin}' status '${vmid}' | grep -q 'status: running'"; then
echo "Pimox control-plane VM ${vmid} (${vm_name}) is neither stopped nor running after configuration." >&2
exit 1
fi
case "${network_mode}" in
static)
if [[ -z "${node_ip}" ]]; then
echo "LAB_PIMOX_CONTROL_PLANE_NETWORK_MODE=static requires LAB_CLUSTER_CONTROL_PLANE_LAN_IP." >&2
exit 1
fi
echo "Configuring Pimox control-plane VM ${vmid} static network ${node_ip} via qemu-guest-agent..."
configure_pimox_worker_forwarding \
"${pimox_host}" \
"${pimox_user}" \
"${pimox_key}" \
"${node_ip}"
if ! configure_pimox_worker_guest_network \
"${pimox_host}" \
"${pimox_user}" \
"${pimox_key}" \
"${vmid}" \
"${qm_bin}" \
"${node_ip}" \
"${gateway}" \
"${dns_servers}" \
"${interface_name}" \
"${vm_name}"; then
pimox_worker_vm_debug "${pimox_host}" "${pimox_user}" "${pimox_key}" "${vmid}" "${qm_bin}"
exit 1
fi
;;
dhcp)
;;
*)
echo "LAB_PIMOX_CONTROL_PLANE_NETWORK_MODE must be 'static' or 'dhcp'." >&2
exit 1
;;
esac
if ! guest_ip="$(wait_for_pimox_guest_ssh "${pimox_host}" "${pimox_user}" "${pimox_key}" "${vmid}" "${guest_user}" "${guest_key_path}" "${ip_prefix}" "${timeout_seconds}" "${qm_bin}")"; then
echo "Timed out waiting for control-plane VM ${vmid} (${vm_name}) to report a reachable guest IP." >&2
exit 1
fi
ensure_pimox_guest_root_disk_size \
"${pimox_host}" \
"${pimox_user}" \
"${pimox_key}" \
"${vmid}" \
"${qm_bin}" \
"${guest_ip}" \
"${guest_user}" \
"${guest_key_path}" \
"${disk_gib}" \
"Pimox control-plane VM ${vmid} (${vm_name})"
guest_cpu_count="$(pimox_guest_cpu_count "${guest_ip}" "${guest_user}" "${guest_key_path}" 2>/dev/null || true)"
if ! [[ "${guest_cpu_count}" =~ ^[0-9]+$ ]] || ((guest_cpu_count < cores)); then
echo "Pimox control-plane VM ${vmid} (${vm_name}) reports ${guest_cpu_count:-unknown} CPU(s); restarting through the pinned KVM launch path." >&2
pimox_shutdown_vm_gracefully "${pimox_host}" "${pimox_user}" "${pimox_key}" "${qm_bin}" "${vmid}"
pimox_start_vm_with_cpuset "${pimox_host}" "${pimox_user}" "${pimox_key}" "${qm_bin}" "${vmid}" "${kvm_cpuset}"
if ! guest_ip="$(wait_for_pimox_guest_ssh "${pimox_host}" "${pimox_user}" "${pimox_key}" "${vmid}" "${guest_user}" "${guest_key_path}" "${ip_prefix}" "${timeout_seconds}" "${qm_bin}")"; then
echo "Timed out waiting for control-plane VM ${vmid} (${vm_name}) after pinned KVM restart." >&2
exit 1
fi
guest_cpu_count="$(pimox_guest_cpu_count "${guest_ip}" "${guest_user}" "${guest_key_path}" 2>/dev/null || true)"
fi
if ! [[ "${guest_cpu_count}" =~ ^[0-9]+$ ]] || ((guest_cpu_count < cores)); then
echo "Pimox control-plane VM ${vmid} (${vm_name}) reports ${guest_cpu_count:-unknown} CPU(s); expected at least ${cores}." >&2
echo "On Pimox 7 ARM this means KVM was not launched on a compatible host CPU set. Check LAB_PIMOX_CONTROL_PLANE_KVM_CPUSET (default: LAB_PIMOX_KVM_CPUSET)." >&2
exit 1
fi
}
write_cluster_worker_var_file() {
local var_file="$1"
local default_platform_labels_json='{"node-role.kubernetes.io/worker":"worker","homelab.dev/node-role":"app","homelab.dev/storage":"ssd","homelab.dev/workload-class":"platform"}'
local pimox_labels_json="${LAB_PIMOX_WORKER_NODE_LABELS_JSON:-${default_platform_labels_json}}"
local manual_labels_json="${LAB_MANUAL_WORKER_NODE_LABELS_JSON:-${pimox_labels_json}}"
shift
LAB_INCLUDE_RASPBERRY_WORKER="${LAB_INCLUDE_RASPBERRY_WORKER:-false}" \
LAB_RASPBERRY_HOST="${LAB_RASPBERRY_HOST:-192.168.100.89}" \
LAB_RASPBERRY_USER="${LAB_RASPBERRY_USER:-jv}" \
LAB_RASPBERRY_NODE_NAME="${LAB_RASPBERRY_NODE_NAME:-raspberry}" \
LAB_RASPBERRY_SSH_KEY_PATH="${LAB_RASPBERRY_SSH_KEY_PATH:-/home/jv/.ssh/id_ed25519}" \
LAB_RASPBERRY_NODE_LABELS_JSON="${LAB_RASPBERRY_NODE_LABELS_JSON:-{\"node-role.kubernetes.io/worker\":\"worker\",\"homelab.dev/node-role\":\"edge-app\",\"homelab.dev/storage\":\"local\",\"homelab.dev/workload-class\":\"edge\"}}" \
LAB_MANUAL_WORKER_NODE_LABELS_JSON="${manual_labels_json}" \
LAB_PIMOX_WORKER_NODE_LABELS_JSON="${pimox_labels_json}" \
python3 - "${var_file}" "$@" <<'PY'
import json
import os
from pathlib import Path
import sys
var_file = sys.argv[1]
spec_files = sys.argv[2:]
nodes = {}
node_labels = {}
try:
raspberry_labels = json.loads(os.environ["LAB_RASPBERRY_NODE_LABELS_JSON"])
manual_labels = json.loads(os.environ["LAB_MANUAL_WORKER_NODE_LABELS_JSON"])
pimox_labels = json.loads(os.environ["LAB_PIMOX_WORKER_NODE_LABELS_JSON"])
except json.JSONDecodeError as exc:
raise SystemExit(f"Invalid node label JSON: {exc}") from exc
if os.environ["LAB_INCLUDE_RASPBERRY_WORKER"].lower() not in {"0", "false", "no", "off", "disabled"}:
nodes["raspberrypi"] = {
"host": os.environ["LAB_RASPBERRY_HOST"],
"user": os.environ["LAB_RASPBERRY_USER"],
"node_name": os.environ["LAB_RASPBERRY_NODE_NAME"],
"ssh_key_path": os.environ["LAB_RASPBERRY_SSH_KEY_PATH"],
}
node_labels["raspberrypi"] = raspberry_labels
for spec_file in spec_files:
path = Path(spec_file)
if not path.exists() or path.stat().st_size == 0:
continue
labels = pimox_labels if path.name == "pimox-workers.tsv" else manual_labels
with path.open(encoding="utf-8") as handle:
for line_number, line in enumerate(handle, start=1):
line = line.rstrip("\n")
if not line or line.startswith("#"):
continue
try:
key, host, user, node_name, ssh_key_path = line.split("\t")
except ValueError as exc:
raise SystemExit(
f"{spec_file}:{line_number}: expected tab-separated "
"key, host, user, node_name, ssh_key_path"
) from exc
nodes[key] = {
"host": host,
"user": user,
"node_name": node_name,
"ssh_key_path": ssh_key_path,
}
node_labels[key] = labels
with open(var_file, "w", encoding="utf-8") as handle:
json.dump({"worker_nodes": nodes, "worker_node_labels": node_labels}, handle, indent=2)
handle.write("\n")
PY
}
prepare_cluster_worker_var_file() {
local include_raspberry_default="$1"
local manual_spec_file="${REPO_ROOT}/.lab/manual-workers.tsv"
local pimox_spec_file="${REPO_ROOT}/.lab/pimox-workers.tsv"
local var_file="${REPO_ROOT}/.lab/cluster-workers.auto.tfvars.json"
local include_manual="${LAB_INCLUDE_MANUAL_WORKERS:-false}"
local -a spec_files=()
export LAB_INCLUDE_RASPBERRY_WORKER="${LAB_INCLUDE_RASPBERRY_WORKER:-${include_raspberry_default}}"
mkdir -p "${REPO_ROOT}/.lab"
ensure_static_pimox_worker_spec_file "${pimox_spec_file}"
if truthy "${include_manual}"; then
spec_files+=("${manual_spec_file}")
elif ! disabled_value "${include_manual}"; then
echo "LAB_INCLUDE_MANUAL_WORKERS must be true or false." >&2
return 1
fi
spec_files+=("${pimox_spec_file}")
write_cluster_worker_var_file "${var_file}" "${spec_files[@]}"
export LAB_CLUSTER_VAR_FILE="${var_file}"
}
ensure_static_pimox_worker_spec_file() {
local spec_file="$1"
local worker_network_mode="${LAB_PIMOX_WORKER_NETWORK_MODE:-static}"
local worker_count="${LAB_PIMOX_WORKER_COUNT:-1}"
local worker_skip_indexes="${LAB_PIMOX_SKIP_WORKER_INDEXES:-}"
local worker_key_prefix="${LAB_PIMOX_WORKER_KEY_PREFIX:-pimox}"
local worker_node_prefix="${LAB_PIMOX_WORKER_NODE_PREFIX:-pimox-worker}"
local worker_user="${LAB_PIMOX_WORKER_USER:-jv}"
local worker_key_path="${LAB_PIMOX_WORKER_SSH_KEY_PATH:-/home/jv/.ssh/id_ed25519}"
local worker_static_ips="${LAB_PIMOX_WORKER_STATIC_IPS:-192.168.100.66 192.168.100.67 192.168.100.76}"
local index
local padded
local worker_key
local node_name
local static_ip
if [[ -s "${spec_file}" || "${worker_network_mode}" != "static" ]]; then
return 0
fi
if ! [[ "${worker_count}" =~ ^[0-9]+$ ]]; then
echo "LAB_PIMOX_WORKER_COUNT must be a non-negative integer." >&2
return 1
fi
if ((worker_count == 0)); then
return 0
fi
mkdir -p "$(dirname "${spec_file}")"
: >"${spec_file}"
for ((index = 1; index <= worker_count; index++)); do
if worker_index_is_skipped "${index}" "${worker_skip_indexes}"; then
continue
fi
if ! static_ip="$(pimox_worker_static_ip "${index}" "${worker_static_ips}")"; then
echo "LAB_PIMOX_WORKER_NETWORK_MODE=static requires LAB_PIMOX_WORKER_STATIC_IPS to include an IP for worker index ${index}." >&2
return 1
fi
printf -v padded '%02d' "${index}"
worker_key="${worker_key_prefix}${padded}"
node_name="${worker_node_prefix}-${padded}"
printf '%s\t%s\t%s\t%s\t%s\n' "${worker_key}" "${static_ip}" "${worker_user}" "${node_name}" "${worker_key_path}" >>"${spec_file}"
done
}
cluster_worker_var_file_has_workers() {
local var_file="$1"
[[ -s "${var_file}" ]] || return 1
python3 - "${var_file}" <<'PY'
import json
import sys
with open(sys.argv[1], encoding="utf-8") as handle:
document = json.load(handle)
sys.exit(0 if document.get("worker_nodes") else 1)
PY
}
preflight_check() {
local description="$1"
local output
shift
printf '%s %s... ' '-->' "${description}"
if output="$("$@" 2>&1)"; then
printf 'ok\n'
return 0
fi
printf 'failed\n'
if [[ -n "${output}" ]]; then
printf '%s\n' "${output}" | sed 's/^/ /' >&2
fi
return 1
}
preflight_warn() {
local description="$1"
local output
shift
printf '%s %s... ' '-->' "${description}"
if output="$("$@" 2>&1)"; then
printf 'ok\n'
return 0
fi
printf 'warning\n'
if [[ -n "${output}" ]]; then
printf '%s\n' "${output}" | sed 's/^/ /' >&2
fi
return 0
}
check_gitea_reachable() {
local gitea_url="${LAB_GITEA_LOCAL_URL:-http://${LAB_GITEA_HOST:-192.168.100.73}:${LAB_GITEA_HTTP_PORT:-3000}/}"
local output
if output="$(curl -fsS --max-time 10 "${gitea_url}" 2>&1 >/dev/null)"; then
return 0
fi
printf '%s\n' "${output}" >&2
cat >&2 <<'EOF'
Gitea local HTTP failed. Run ./jeannie doctor-gitea --verbose.
If the local Gitea container is down or unhealthy, run ./jeannie deploy-gitea.
EOF
return 1
}
check_debian_docker_root() {
local expected_root="${LAB_DEBIAN_DOCKER_ROOT:-/var/lib/docker}"
local actual_root
if ! command -v docker >/dev/null 2>&1; then
echo "docker command was not found on Debian host" >&2
return 1
fi
actual_root="$(sudo docker info --format '{{.DockerRootDir}}')"
if [[ "${actual_root}" != "${expected_root}" ]]; then
echo "Debian Docker root is ${actual_root}; expected ${expected_root}" >&2
return 1
fi
}
fix_debian_docker_root() {
local expected_root="${LAB_DEBIAN_DOCKER_ROOT:-/var/lib/docker}"
local daemon_file="/etc/docker/daemon.json"
local current_root=""
require_debian_server "fix-debian-docker-root"
if ! command -v docker >/dev/null 2>&1; then
echo "docker command was not found on Debian host" >&2
exit 1
fi
current_root="$(sudo docker info --format '{{.DockerRootDir}}' 2>/dev/null || true)"
if [[ "${current_root}" == "${expected_root}" ]]; then
echo "Debian Docker root is already ${expected_root}."
return 0
fi
echo "Moving Debian Docker root from ${current_root:-unknown} to ${expected_root}..."
sudo mkdir -p "${expected_root}" /etc/docker
echo "Stopping Docker services..."
sudo systemctl stop docker 2>/dev/null || true
sudo systemctl stop containerd 2>/dev/null || true
if [[ -n "${current_root}" && -d "${current_root}" && "${current_root}" != "${expected_root}" ]]; then
echo "Copying existing Docker data to ${expected_root}..."
sudo rsync -aHAX --numeric-ids "${current_root}/" "${expected_root}/"
fi
sudo python3 - "${daemon_file}" "${expected_root}" <<'PY'
import json
import os
import sys
path, expected_root = sys.argv[1:3]
document = {}
if os.path.exists(path) and os.path.getsize(path) > 0:
with open(path, encoding="utf-8") as handle:
document = json.load(handle)
document["data-root"] = expected_root
with open(path, "w", encoding="utf-8") as handle:
json.dump(document, handle, indent=2, sort_keys=True)
handle.write("\n")
PY
echo "Starting Docker services..."
sudo systemctl start containerd
sudo systemctl start docker
check_debian_docker_root
echo "Debian Docker root is now ${expected_root}."
}
check_debian_tailscale_ip() {
local expected_ip="${LAB_DEBIAN_TAILSCALE_IP:-}"
if [[ -z "${expected_ip}" ]]; then
return 0
fi
if ! command -v tailscale >/dev/null 2>&1; then
echo "tailscale command was not found on Debian host" >&2
return 1
fi
if ! tailscale ip -4 | grep -Fxq "${expected_ip}"; then
echo "Debian Tailscale IP does not include ${expected_ip}" >&2
tailscale ip -4 >&2 || true
return 1
fi
}
check_edge_ssh() {
prepare_edge_connection
}
check_rpi_ssh() {
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}}"
ssh -i "${rpi_key}" -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new "${rpi_user}@${rpi_host}" "true"
}
check_rpi_docker_root_state() {
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 nvme_root="${LAB_RPI_DOCKER_ROOT:-${LAB_RPI_DOCKER_NVME_ROOT:-/nvme-storage/docker}}"
local fallback_root="${LAB_RPI_DOCKER_FALLBACK_ROOT:-/var/lib/docker}"
ssh -i "${rpi_key}" -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new "${rpi_user}@${rpi_host}" "set -eu
actual_root=\"\$(sudo docker info --format '{{.DockerRootDir}}')\"
if [ \"\$actual_root\" = '${nvme_root}' ]; then
mountpoint -q '${nvme_root}' || { echo 'Docker uses ${nvme_root}, but it is not a mount point' >&2; exit 1; }
exit 0
fi
if [ \"\$actual_root\" = '${fallback_root}' ]; then
echo 'Docker is currently using fallback root ${fallback_root}; NVMe may be unavailable.' >&2
exit 0
fi
echo \"RPi Docker root is \$actual_root; expected ${nvme_root} or ${fallback_root}\" >&2
exit 1"
}
check_rpi_tailscale_ip() {
local expected_ip="${LAB_RPI_TAILSCALE_IP:-}"
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}}"
if [[ -z "${expected_ip}" ]]; then
return 0
fi
ssh -i "${rpi_key}" -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new "${rpi_user}@${rpi_host}" "tailscale ip -4 | grep -Fx '${expected_ip}'"
}
check_pimox_storage() {
local mode="${LAB_PIMOX_PIPELINE:-true}"
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 worker_storage="${LAB_PIMOX_WORKER_STORAGE:-${TF_VAR_pimox_worker_storage:-opi5_ssd}}"
if disabled_value "${mode}"; then
return 0
fi
pimox_ssh "${pimox_host}" "${pimox_user}" "${pimox_key}" "set -eu
pvesm_cmd=\"\$(command -v pvesm 2>/dev/null || true)\"
if [ -z \"\$pvesm_cmd\" ] && [ -x /usr/sbin/pvesm ]; then
pvesm_cmd=/usr/sbin/pvesm
fi
if [ -z \"\$pvesm_cmd\" ]; then
echo 'pvesm was not found' >&2
exit 1
fi
sudo \"\$pvesm_cmd\" status | awk -v storage='${worker_storage}' 'NR > 1 && \$1 == storage && \$3 == \"active\" { found = 1 } END { exit found ? 0 : 1 }'"
}
check_local_disk_free_gib() {
local path="$1"
local min_gib="$2"
local available_kib
local min_kib
available_kib="$(df -Pk "${path}" | awk 'NR == 2 { print $4 }')"
min_kib=$((min_gib * 1024 * 1024))
if ((available_kib < min_kib)); then
echo "${path} has $((available_kib / 1024 / 1024)) GiB free; expected at least ${min_gib} GiB" >&2
return 1
fi
}
check_systemd_active() {
local unit="$1"
systemctl is-active --quiet "${unit}"
}
check_rpi_docker_writable() {
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}}"
ssh -i "${rpi_key}" -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new "${rpi_user}@${rpi_host}" "set -eu
root=\"\$(sudo docker info --format '{{.DockerRootDir}}')\"
sudo mkdir -p \"\$root/.homelab-check\"
sudo sh -c \"echo ok > '\$root/.homelab-check/write-test'\"
sudo rm -f \"\$root/.homelab-check/write-test\""
}
check_edge_disk_free() {
local min_gib="${LAB_PREFLIGHT_EDGE_MIN_FREE_GIB:-2}"
[[ "${min_gib}" =~ ^[0-9]+$ ]] || { echo "Invalid edge minimum free space." >&2; return 1; }
prepare_edge_connection || return 1
ssh "${EDGE_SSH_ARGS[@]}" "${TF_VAR_edge_user:-${LAB_EDGE_USER:-ubuntu}}@${TF_VAR_edge_ssh_host}" "set -eu
available_kib=\"\$(df -Pk / | awk 'NR == 2 { print \$4 }')\"
min_kib=$((min_gib * 1024 * 1024))
if [ \"\$available_kib\" -lt \"\$min_kib\" ]; then
echo \"edge / has \$((available_kib / 1024 / 1024)) GiB free; expected at least ${min_gib} GiB\" >&2
exit 1
fi"
}
check_pihole_dns_query() {
local rpi_host="${LAB_RPI_HOST:-${LAB_RASPBERRY_HOST:-192.168.100.89}}"
local query_name="${LAB_PIHOLE_STATUS_QUERY:-cloudflare.com}"
local output
if command -v dig >/dev/null 2>&1; then
output="$(dig @"${rpi_host}" "${query_name}" A +time=3 +tries=1 +short 2>&1)" || {
printf '%s\n' "${output}" >&2
echo "Pi-hole DNS query to ${rpi_host}:53 failed; check RPi firewall and that the Pi-hole container publishes 53/udp on the LAN address." >&2
return 1
}
if [[ -z "${output}" ]]; then
echo "Pi-hole returned no A records for ${query_name}" >&2
return 1
fi
return 0
fi
if command -v nslookup >/dev/null 2>&1; then
nslookup "${query_name}" "${rpi_host}" >/dev/null
return $?
fi
echo "dig or nslookup is required to test Pi-hole DNS directly." >&2
return 1
}
homelab_preflight() {
local phase="${1:-full}"
local failures=0
require_debian_server "preflight"
if truthy "${LAB_SKIP_PREFLIGHT:-false}"; then
echo "Skipping homelab preflight because LAB_SKIP_PREFLIGHT=${LAB_SKIP_PREFLIGHT}."
return 0
fi
case "${phase}" in
early | full)
;;
*)
echo "Unsupported preflight phase '${phase}'." >&2
exit 1
;;
esac
echo "Running ${phase} homelab preflight checks from ${HOMELAB_INVENTORY_FILE:-${REPO_ROOT}/homelab.yml}..."
preflight_check "Debian Docker root is ${LAB_DEBIAN_DOCKER_ROOT:-/var/lib/docker}" check_debian_docker_root || failures=$((failures + 1))
preflight_check "Debian Tailscale IP ${LAB_DEBIAN_TAILSCALE_IP:-unset}" check_debian_tailscale_ip || failures=$((failures + 1))
preflight_check "RPi SSH ${LAB_RPI_USER:-${LAB_RASPBERRY_USER:-jv}}@${LAB_RPI_HOST:-${LAB_RASPBERRY_HOST:-192.168.100.89}}" check_rpi_ssh || failures=$((failures + 1))
if [[ "${phase}" == "full" ]]; then
preflight_check "Gitea reachable at ${LAB_GITEA_LOCAL_URL:-http://${LAB_GITEA_HOST:-192.168.100.73}:${LAB_GITEA_HTTP_PORT:-3000}/}" check_gitea_reachable || failures=$((failures + 1))
preflight_check "RPi Docker root is NVMe or fallback" check_rpi_docker_root_state || failures=$((failures + 1))
fi
preflight_warn "RPi Tailscale IP ${LAB_RPI_TAILSCALE_IP:-unset}" check_rpi_tailscale_ip
preflight_check "Pimox storage ${LAB_PIMOX_WORKER_STORAGE:-${TF_VAR_pimox_worker_storage:-opi5_ssd}} is active" check_pimox_storage || failures=$((failures + 1))
preflight_check "OCI edge private management access" check_edge_ssh || failures=$((failures + 1))
if ((failures > 0)); then
echo "Preflight failed with ${failures} blocking check(s). Fix the inventory or host state before continuing." >&2
exit 1
fi
echo "${phase^} preflight checks passed."
}
doctor_preapply() {
local failures=0
require_debian_server "doctor-preapply"
echo "Running pre-apply readiness checks..."
preflight_check "Debian / has at least ${LAB_PREFLIGHT_ROOT_MIN_FREE_GIB:-10} GiB free" check_local_disk_free_gib / "${LAB_PREFLIGHT_ROOT_MIN_FREE_GIB:-10}" || failures=$((failures + 1))
preflight_check "Debian /data has at least ${LAB_PREFLIGHT_DATA_MIN_FREE_GIB:-20} GiB free" check_local_disk_free_gib /data "${LAB_PREFLIGHT_DATA_MIN_FREE_GIB:-20}" || failures=$((failures + 1))
preflight_check "Docker is active" check_systemd_active docker || failures=$((failures + 1))
preflight_check "containerd is active" check_systemd_active containerd || failures=$((failures + 1))
preflight_check "RPi Docker root is writable" check_rpi_docker_writable || failures=$((failures + 1))
preflight_check "Pimox storage ${LAB_PIMOX_WORKER_STORAGE:-${TF_VAR_pimox_worker_storage:-opi5_ssd}} is active" check_pimox_storage || failures=$((failures + 1))
preflight_check "OCI edge / has at least ${LAB_PREFLIGHT_EDGE_MIN_FREE_GIB:-2} GiB free" check_edge_disk_free || failures=$((failures + 1))
preflight_check "Pi-hole DNS query resolves" check_pihole_dns_query || failures=$((failures + 1))
if ((failures > 0)); then
echo "Pre-apply doctor failed with ${failures} blocking check(s)." >&2
exit 1
fi
echo "Pre-apply doctor checks passed."
}
inventory_check() {
"${REPO_ROOT}/scripts/validate-homelab-inventory" "${HOMELAB_INVENTORY_FILE:-${REPO_ROOT}/homelab.yml}"
}
run_pimox_pipeline() {
cluster_runtime_require --vm-start || return 1
local mode="${LAB_PIMOX_PIPELINE:-true}"
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 bridge="${LAB_PIMOX_BRIDGE:-${TF_VAR_pimox_template_bridge:-vmbr0}}"
local template_vmid="${LAB_PIMOX_TEMPLATE_VMID:-${TF_VAR_pimox_template_vmid:-9000}}"
local template_name="${LAB_PIMOX_TEMPLATE_NAME:-${TF_VAR_pimox_template_name:-debian13-arm64-k8s-template}}"
local template_cores="${LAB_PIMOX_TEMPLATE_CORES:-${TF_VAR_pimox_template_cores:-2}}"
local template_memory="${LAB_PIMOX_TEMPLATE_MEMORY:-${TF_VAR_pimox_template_memory:-8192}}"
local template_disk_gib="${LAB_PIMOX_TEMPLATE_DISK_GIB:-30}"
local template_replace_existing="${LAB_PIMOX_TEMPLATE_REPLACE_EXISTING:-${TF_VAR_pimox_template_replace_existing:-false}}"
local provisioning_interface
local worker_count="${LAB_PIMOX_WORKER_COUNT:-1}"
local worker_base_vmid="${LAB_PIMOX_WORKER_BASE_VMID:-9010}"
local worker_name_prefix="${LAB_PIMOX_WORKER_NAME_PREFIX:-pimox-worker}"
local worker_node_prefix="${LAB_PIMOX_WORKER_NODE_PREFIX:-pimox-worker}"
local worker_key_prefix="${LAB_PIMOX_WORKER_KEY_PREFIX:-pimox}"
local worker_skip_indexes="${LAB_PIMOX_SKIP_WORKER_INDEXES:-}"
local worker_cores="${LAB_PIMOX_WORKER_CORES:-2}"
local worker_memory="${LAB_PIMOX_WORKER_MEMORY:-8192}"
local worker_disk_gib="${LAB_PIMOX_WORKER_DISK_GIB:-30}"
local worker_cpu_affinities="${LAB_PIMOX_WORKER_CPU_AFFINITIES:-}"
local pimox_kvm_cpuset="${LAB_PIMOX_KVM_CPUSET:-4-7}"
local template_kvm_cpuset="${LAB_PIMOX_TEMPLATE_KVM_CPUSET:-${pimox_kvm_cpuset}}"
local worker_kvm_cpuset="${LAB_PIMOX_WORKER_KVM_CPUSET:-${pimox_kvm_cpuset}}"
local pin_hookscript_enabled="${LAB_PIMOX_PIN_HOOKSCRIPT_ENABLED:-true}"
local pin_hookscript_storage="${LAB_PIMOX_PIN_HOOKSCRIPT_STORAGE:-local}"
local pin_hookscript_name="${LAB_PIMOX_PIN_HOOKSCRIPT_NAME:-pin.pl}"
local pin_hookscript_ref=""
local pin_cpu_map="${LAB_PIMOX_PIN_CPU_MAP:-}"
local control_plane_enabled="${LAB_PIMOX_CONTROL_PLANE_ENABLED:-auto}"
local control_plane_vmid="${LAB_PIMOX_CONTROL_PLANE_VMID:-${LAB_CLUSTER_PIMOX_CONTROL_PLANE_VMID:-}}"
local control_plane_name="${LAB_PIMOX_CONTROL_PLANE_NAME:-${LAB_CLUSTER_CONTROL_PLANE_NODE_NAME:-pimox-cp-01}}"
local control_plane_ip="${LAB_PIMOX_CONTROL_PLANE_IP:-${LAB_CLUSTER_CONTROL_PLANE_LAN_IP:-}}"
local control_plane_user="${LAB_PIMOX_CONTROL_PLANE_USER:-${LAB_CLUSTER_CONTROL_PLANE_USER:-${LAB_PIMOX_WORKER_USER:-jv}}}"
local control_plane_key_path="${LAB_PIMOX_CONTROL_PLANE_SSH_KEY_PATH:-${LAB_CLUSTER_CONTROL_PLANE_SSH_KEY_PATH:-${LAB_PIMOX_WORKER_SSH_KEY_PATH:-/home/jv/.ssh/id_ed25519}}}"
local control_plane_cores="${LAB_PIMOX_CONTROL_PLANE_CORES:-2}"
local control_plane_memory="${LAB_PIMOX_CONTROL_PLANE_MEMORY:-8192}"
local control_plane_disk_gib="${LAB_PIMOX_CONTROL_PLANE_DISK_GIB:-30}"
local control_plane_storage="${LAB_PIMOX_CONTROL_PLANE_STORAGE:-${LAB_CLUSTER_PIMOX_STORAGE:-${LAB_PIMOX_WORKER_STORAGE:-${TF_VAR_pimox_worker_storage:-opi5_ssd}}}}"
local control_plane_replace_existing="${LAB_PIMOX_CONTROL_PLANE_REPLACE_EXISTING:-false}"
local control_plane_cpu_affinity="${LAB_PIMOX_CONTROL_PLANE_CPU_AFFINITY:-}"
local control_plane_kvm_cpuset="${LAB_PIMOX_CONTROL_PLANE_KVM_CPUSET:-${pimox_kvm_cpuset}}"
local worker_replace_existing="${LAB_PIMOX_WORKER_REPLACE_EXISTING:-false}"
local worker_storage="${LAB_PIMOX_WORKER_STORAGE:-${TF_VAR_pimox_worker_storage:-opi5_ssd}}"
local worker_user="${LAB_PIMOX_WORKER_USER:-jv}"
local worker_key_path="${LAB_PIMOX_WORKER_SSH_KEY_PATH:-/home/jv/.ssh/id_ed25519}"
local ip_prefix="${LAB_PIMOX_GUEST_IP_PREFIX:-192.168.100.}"
local timeout_seconds="${LAB_PIMOX_GUEST_TIMEOUT_SECONDS:-3600}"
local worker_wait_timeout_seconds="${LAB_PIMOX_WORKER_WAIT_TIMEOUT_SECONDS:-600}"
local spec_file="${REPO_ROOT}/.lab/pimox-workers.tsv"
local var_file="${REPO_ROOT}/.lab/cluster-workers.auto.tfvars.json"
local index
local readiness_output
local readiness_status
local worker_cpu_affinity
local cpuset_cpu_total
local cpuset_name
local cpuset_value
local required_cores
local worker_vmid
if disabled_value "${mode}"; then
return 0
fi
if [[ "${mode}" == "auto" && -n "${LAB_PIMOX_WORKER_COUNT+x}" ]]; then
mode="true"
fi
if [[ "${control_plane_enabled}" == "auto" ]]; then
if [[ -n "${control_plane_vmid}" && -n "${control_plane_ip}" ]]; then
control_plane_enabled="true"
else
control_plane_enabled="false"
fi
fi
if ! [[ "${worker_count}" =~ ^[0-9]+$ ]]; then
echo "LAB_PIMOX_WORKER_COUNT must be a non-negative integer." >&2
exit 1
fi
if ! [[ "${template_cores}" =~ ^[0-9]+$ && "${worker_cores}" =~ ^[0-9]+$ && "${control_plane_cores}" =~ ^[0-9]+$ ]]; then
echo "LAB_PIMOX_TEMPLATE_CORES, LAB_PIMOX_WORKER_CORES, and LAB_PIMOX_CONTROL_PLANE_CORES must be positive integers." >&2
exit 1
fi
if ! [[ "${template_memory}" =~ ^[0-9]+$ && "${worker_memory}" =~ ^[0-9]+$ && "${control_plane_memory}" =~ ^[0-9]+$ ]]; then
echo "LAB_PIMOX_TEMPLATE_MEMORY, LAB_PIMOX_WORKER_MEMORY, and LAB_PIMOX_CONTROL_PLANE_MEMORY must be positive integer MiB values." >&2
exit 1
fi
if ((template_cores == 0 || worker_cores == 0 || control_plane_cores == 0 || template_memory == 0 || worker_memory == 0 || control_plane_memory == 0)); then
echo "Pimox template, control-plane, and worker CPU and memory values must be greater than zero." >&2
exit 1
fi
if ! [[ "${template_disk_gib}" =~ ^[0-9]+$ && "${worker_disk_gib}" =~ ^[0-9]+$ && "${control_plane_disk_gib}" =~ ^[0-9]+$ ]]; then
echo "LAB_PIMOX_TEMPLATE_DISK_GIB, LAB_PIMOX_WORKER_DISK_GIB, and LAB_PIMOX_CONTROL_PLANE_DISK_GIB must be positive integer GiB values." >&2
exit 1
fi
if ((template_disk_gib == 0 || worker_disk_gib == 0 || control_plane_disk_gib == 0)); then
echo "Pimox template, control-plane, and worker disk sizes must be greater than zero." >&2
exit 1
fi
for cpuset_name in template_kvm_cpuset control_plane_kvm_cpuset worker_kvm_cpuset; do
cpuset_value="${!cpuset_name}"
if [[ -z "${cpuset_value}" ]]; then
continue
fi
if ! cpuset_cpu_total="$(cpuset_cpu_count "${cpuset_value}")"; then
echo "${cpuset_name}='${cpuset_value}' is invalid. Use CPU IDs or ranges, such as 4-7." >&2
exit 1
fi
required_cores="${template_cores}"
if [[ "${cpuset_name}" == "worker_kvm_cpuset" ]]; then
required_cores="${worker_cores}"
elif [[ "${cpuset_name}" == "control_plane_kvm_cpuset" ]]; then
required_cores="${control_plane_cores}"
fi
if ((cpuset_cpu_total < required_cores)); then
echo "${cpuset_name}='${cpuset_value}' has ${cpuset_cpu_total} CPU(s), but ${required_cores} are required." >&2
exit 1
fi
done
if ! truthy "${pin_hookscript_enabled}" && ! disabled_value "${pin_hookscript_enabled}"; then
echo "LAB_PIMOX_PIN_HOOKSCRIPT_ENABLED must be true or false." >&2
exit 1
fi
if truthy "${pin_hookscript_enabled}"; then
if [[ -z "${pin_cpu_map}" ]]; then
if truthy "${control_plane_enabled}" && [[ -n "${control_plane_kvm_cpuset}" ]]; then
pin_cpu_map+="${control_plane_vmid}=${control_plane_kvm_cpuset} "
fi
for ((index = 1; index <= worker_count; index++)); do
if worker_index_is_skipped "${index}" "${worker_skip_indexes}" || [[ -z "${worker_kvm_cpuset}" ]]; then
continue
fi
worker_vmid=$((worker_base_vmid + index - 1))
pin_cpu_map+="${worker_vmid}=${worker_kvm_cpuset} "
done
fi
if [[ -n "${pin_cpu_map// /}" ]]; then
pin_hookscript_ref="${pin_hookscript_storage}:snippets/${pin_hookscript_name}"
echo "Pimox K8s VM CPU pin map: ${pin_cpu_map}"
fi
fi
if ! [[ "${timeout_seconds}" =~ ^[0-9]+$ && "${timeout_seconds}" -gt 0 ]]; then
echo "LAB_PIMOX_GUEST_TIMEOUT_SECONDS must be a positive integer." >&2
exit 1
fi
if ! [[ "${worker_wait_timeout_seconds}" =~ ^[0-9]+$ && "${worker_wait_timeout_seconds}" -gt 0 ]]; then
echo "LAB_PIMOX_WORKER_WAIT_TIMEOUT_SECONDS must be a positive integer." >&2
exit 1
fi
if ! truthy "${worker_replace_existing}" && ! disabled_value "${worker_replace_existing}"; then
echo "LAB_PIMOX_WORKER_REPLACE_EXISTING must be true or false." >&2
exit 1
fi
if ! truthy "${control_plane_enabled}" && ! disabled_value "${control_plane_enabled}"; then
echo "LAB_PIMOX_CONTROL_PLANE_ENABLED must be true, false, or auto." >&2
exit 1
fi
if truthy "${control_plane_enabled}"; then
if [[ -z "${control_plane_vmid}" ]]; then
echo "LAB_PIMOX_CONTROL_PLANE_ENABLED=true requires LAB_CLUSTER_PIMOX_CONTROL_PLANE_VMID or LAB_PIMOX_CONTROL_PLANE_VMID." >&2
exit 1
fi
if ! [[ "${control_plane_vmid}" =~ ^[0-9]+$ ]]; then
echo "LAB_PIMOX_CONTROL_PLANE_VMID must be an integer." >&2
exit 1
fi
if [[ "${control_plane_vmid}" == "${template_vmid}" ]]; then
echo "LAB_PIMOX_CONTROL_PLANE_VMID cannot match LAB_PIMOX_TEMPLATE_VMID (${template_vmid})." >&2
exit 1
fi
if ((worker_count > 0 && control_plane_vmid >= worker_base_vmid && control_plane_vmid < worker_base_vmid + worker_count)); then
echo "LAB_PIMOX_CONTROL_PLANE_VMID ${control_plane_vmid} overlaps the worker VMID range ${worker_base_vmid}-$((worker_base_vmid + worker_count - 1))." >&2
exit 1
fi
if ! truthy "${control_plane_replace_existing}" && ! disabled_value "${control_plane_replace_existing}"; then
echo "LAB_PIMOX_CONTROL_PLANE_REPLACE_EXISTING must be true or false." >&2
exit 1
fi
if ! [[ "${control_plane_storage}" =~ ^[A-Za-z0-9_.:-]+$ ]]; then
echo "LAB_PIMOX_CONTROL_PLANE_STORAGE must be a valid Pimox storage identifier." >&2
exit 1
fi
if [[ "${control_plane_storage}" == "local" ]]; then
echo "LAB_PIMOX_CONTROL_PLANE_STORAGE cannot be local; only the Pimox template VM should live on local storage." >&2
exit 1
fi
fi
if ! [[ "${worker_storage}" =~ ^[A-Za-z0-9_.:-]+$ ]]; then
echo "LAB_PIMOX_WORKER_STORAGE must be a valid Pimox storage identifier." >&2
exit 1
fi
if [[ "${worker_storage}" == "local" ]]; then
echo "LAB_PIMOX_WORKER_STORAGE cannot be local; only the Pimox template VM should live on local storage." >&2
exit 1
fi
set +e
readiness_output="$(pimox_ssh "${pimox_host}" "${pimox_user}" "${pimox_key}" "set -eu
if ! { command -v qm >/dev/null 2>&1 || [ -x '${qm_bin}' ]; }; then
echo 'qm was not found in PATH and ${qm_bin} is not executable'
exit 1
fi
if ! ip link show '${bridge}' >/dev/null 2>&1; then
echo 'bridge ${bridge} was not found'
exit 1
fi
if ! sudo -n true >/dev/null 2>&1; then
echo 'passwordless sudo is not available for ${pimox_user}'
exit 1
fi
pvesm_cmd=\"\$(command -v pvesm 2>/dev/null || true)\"
if [ -z \"\$pvesm_cmd\" ] && [ -x /usr/sbin/pvesm ]; then
pvesm_cmd=/usr/sbin/pvesm
fi
if [ -z \"\$pvesm_cmd\" ]; then
echo 'pvesm was not found; cannot validate Pimox worker storage ${worker_storage}'
exit 1
fi
if ! sudo \"\$pvesm_cmd\" status | awk -v storage='${worker_storage}' 'NR > 1 && \$1 == storage && \$3 == \"active\" { found = 1 } END { exit found ? 0 : 1 }'; then
echo 'Pimox worker storage ${worker_storage} was not found or is not active'
exit 1
fi" 2>&1)"
readiness_status=$?
set -e
if ((readiness_status != 0)); then
if [[ "${mode}" == "auto" ]]; then
echo "Skipping Pimox automation because ${pimox_user}@${pimox_host} with bridge ${bridge} is not ready."
return 0
fi
echo "Pimox automation requested, but ${pimox_user}@${pimox_host} is not ready: ${readiness_output}" >&2
exit 1
fi
ensure_python3
provisioning_interface="${TF_VAR_provisioning_interface:-${LAB_PROVISIONING_INTERFACE:-$(detect_route_interface "${pimox_host}")}}"
if [[ -z "${provisioning_interface}" ]]; then
echo "Could not detect the Debian interface used to reach ${pimox_host}; set LAB_PROVISIONING_INTERFACE." >&2
exit 1
fi
export TF_VAR_provisioning_interface="${provisioning_interface}"
export TF_VAR_pimox_host="${pimox_host}"
export TF_VAR_pimox_user="${pimox_user}"
export TF_VAR_pimox_ssh_key_path="${pimox_key}"
export TF_VAR_pimox_qm_bin="${qm_bin}"
export TF_VAR_pimox_template_bridge="${bridge}"
export TF_VAR_pimox_template_vmid="${template_vmid}"
export TF_VAR_pimox_template_name="${template_name}"
export TF_VAR_pimox_template_cores="${template_cores}"
export TF_VAR_pimox_template_memory="${template_memory}"
export TF_VAR_pimox_template_scsi0="${TF_VAR_pimox_template_scsi0:-local:${template_disk_gib}}"
export TF_VAR_pimox_template_replace_existing="${template_replace_existing}"
export TF_VAR_pimox_template_kvm_cpuset="${template_kvm_cpuset}"
export TF_VAR_pimox_template_builder_enabled="${TF_VAR_pimox_template_builder_enabled:-true}"
export TF_VAR_pimox_template_build_ssh_key_path="${TF_VAR_pimox_template_build_ssh_key_path:-${worker_key_path}}"
export TF_VAR_pimox_template_build_user="${TF_VAR_pimox_template_build_user:-${worker_user}}"
export TF_VAR_pimox_template_guest_ip_prefix="${TF_VAR_pimox_template_guest_ip_prefix:-${ip_prefix}}"
export TF_VAR_pimox_template_build_timeout_seconds="${TF_VAR_pimox_template_build_timeout_seconds:-${timeout_seconds}}"
echo "Preparing Pimox provisioning and Debian worker template on ${pimox_host} without changing Orange Pi host networking..."
run_tofu_stack "bootstrap/provisioning"
if ! pimox_ssh "${pimox_host}" "${pimox_user}" "${pimox_key}" "sudo '${qm_bin}' config '${template_vmid}' | grep -q '^template: 1$'"; then
echo "Template VM ${template_vmid} is not available as a Pimox template after provisioning." >&2
exit 1
fi
pimox_ssh "${pimox_host}" "${pimox_user}" "${pimox_key}" "sudo '${qm_bin}' set '${template_vmid}' --agent enabled=1"
echo "Worker VM clones will be created on Pimox storage ${worker_storage}; template VM ${template_vmid} stays on its configured template storage; guest roots target ${worker_disk_gib}G."
if [[ -n "${pin_hookscript_ref}" ]]; then
ensure_pimox_pin_hookscript \
"${pimox_host}" \
"${pimox_user}" \
"${pimox_key}" \
"${qm_bin}" \
"${pin_hookscript_storage}" \
"${pin_hookscript_name}" \
"${pin_cpu_map}"
fi
if truthy "${control_plane_enabled}"; then
echo "Ensuring Pimox control-plane VM ${control_plane_vmid} (${control_plane_name}) on storage ${control_plane_storage}..."
ensure_pimox_control_plane_node \
"${pimox_host}" \
"${pimox_user}" \
"${pimox_key}" \
"${template_vmid}" \
"${bridge}" \
"${control_plane_vmid}" \
"${control_plane_name}" \
"${control_plane_ip}" \
"${control_plane_user}" \
"${control_plane_key_path}" \
"${ip_prefix}" \
"${timeout_seconds}" \
"${qm_bin}" \
"${control_plane_storage}" \
"${control_plane_replace_existing}" \
"${control_plane_cores}" \
"${control_plane_memory}" \
"${control_plane_cpu_affinity}" \
"${control_plane_kvm_cpuset}" \
"${pin_hookscript_ref}" \
"${control_plane_disk_gib}"
fi
if ((worker_count == 0)); then
return 0
fi
mkdir -p "${REPO_ROOT}/.lab"
: >"${spec_file}"
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
worker_cpu_affinity=""
if [[ -n "${worker_cpu_affinities}" ]]; then
worker_cpu_affinity="$(pimox_worker_cpu_affinity "${index}" "${worker_cpu_affinities}" "${worker_cores}")"
fi
ensure_pimox_worker_node \
"${index}" \
"${spec_file}" \
"${pimox_host}" \
"${pimox_user}" \
"${pimox_key}" \
"${template_vmid}" \
"${bridge}" \
"${worker_base_vmid}" \
"${worker_name_prefix}" \
"${worker_node_prefix}" \
"${worker_key_prefix}" \
"${worker_cores}" \
"${worker_memory}" \
"${worker_user}" \
"${worker_key_path}" \
"${ip_prefix}" \
"${worker_wait_timeout_seconds}" \
"${qm_bin}" \
"${worker_storage}" \
"${worker_replace_existing}" \
"${worker_cpu_affinity}" \
"${worker_kvm_cpuset}" \
"${pin_hookscript_ref}" \
"${worker_disk_gib}"
done
write_cluster_worker_var_file "${var_file}" "${REPO_ROOT}/.lab/manual-workers.tsv" "${spec_file}"
export LAB_CLUSTER_VAR_FILE="${var_file}"
}
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
}
restore_docker_networking_after_iptables_cleanup() {
if ! command -v docker >/dev/null 2>&1; then
return 0
fi
if ! systemctl is-active --quiet docker 2>/dev/null; then
return 0
fi
echo "Restarting Docker to restore published-port iptables rules after Kubernetes cleanup..."
sudo systemctl restart docker
}
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
}
cleanup_node() {
# A remote profile must never authorize wiping an unrelated local cluster.
python3 "${REPO_ROOT}/scripts/cluster-context.py" check-local-host \
--profile "${LAB_CLUSTER_PROFILE}" || return 1
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_docker_networking_after_iptables_cleanup
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
}
image_ref_tag() {
local image_ref="$1"
local tag
tag="${image_ref##*:}"
if [[ "${tag}" == "${image_ref}" || "${tag}" == */* ]]; then
echo "Image reference ${image_ref} must include an immutable tag." >&2
exit 1
fi
printf '%s\n' "${tag}"
}
website_image_tag() {
local source_hash="$1"
printf 'src-%s\n' "${source_hash:0:12}"
}
demos_image_tag() {
local source_hash="$1"
printf 'src-%s\n' "${source_hash:0:12}"
}
apps_registry_endpoint() {
if [[ -n "${TF_VAR_registry_endpoint:-}" ]]; then
printf '%s\n' "${TF_VAR_registry_endpoint}"
return 0
fi
if [[ -n "${LAB_REGISTRY_ENDPOINT:-}" ]]; then
printf '%s\n' "${LAB_REGISTRY_ENDPOINT}"
return 0
fi
demos_registry_endpoint
}
demos_registry_endpoint() {
local image
image="$(awk '$1 == "image:" && $2 ~ /demos-static/ {print $2; exit}' "${REPO_ROOT}/apps/demos-static/web-app.yaml")"
if [[ -z "${image}" || "${image}" != */* ]]; then
echo "Could not determine demos registry endpoint from apps/demos-static/web-app.yaml" >&2
exit 1
fi
printf '%s\n' "${image%%/*}"
}
website_source_hash() {
(
cd "${1:-${REPO_ROOT}}"
find apps/website -type f -print0 | sort -z | xargs -0 sha256sum | sha256sum | awk '{print $1}'
)
}
demos_source_hash() {
(
cd "${REPO_ROOT}"
find apps/demos-static -type f -print0 | sort -z | xargs -0 sha256sum | sha256sum | awk '{print $1}'
)
}
registry_image_exists() {
local registry_endpoint="$1"
local repository="$2"
local tag="$3"
local accept_header
if ! command -v curl >/dev/null 2>&1; then
return 1
fi
accept_header="application/vnd.oci.image.index.v1+json, application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.list.v2+json, application/vnd.docker.distribution.manifest.v2+json"
curl -fsS \
-H "Accept: ${accept_header}" \
"http://${registry_endpoint}/v2/${repository}/manifests/${tag}" >/dev/null
}
image_state_value() {
local state_file="$1"
local key="$2"
awk -F= -v key="${key}" '$1 == key {print substr($0, index($0, "=") + 1); exit}' "${state_file}" 2>/dev/null || true
}
website_image_is_current() {
local state_file="$1"
local source_hash="$2"
local platforms="$3"
local image_ref="$4"
local registry_endpoint="$5"
local image_tag
local saved_hash
local saved_platforms
local saved_image
[[ -f "${state_file}" ]] || return 1
saved_hash="$(image_state_value "${state_file}" source_hash)"
saved_platforms="$(image_state_value "${state_file}" platforms)"
saved_image="$(image_state_value "${state_file}" image)"
[[ "${saved_hash}" == "${source_hash}" ]] || return 1
[[ "${saved_platforms}" == "${platforms}" ]] || return 1
[[ "${saved_image}" == "${image_ref}" ]] || return 1
image_tag="$(image_ref_tag "${image_ref}")"
registry_image_exists "${registry_endpoint}" php-website "${image_tag}"
}
ensure_website_image_tag_not_reused() {
local state_file="$1"
local source_hash="$2"
local image_ref="$3"
local saved_hash
local saved_image
[[ -f "${state_file}" ]] || return 0
saved_hash="$(image_state_value "${state_file}" source_hash)"
saved_image="$(image_state_value "${state_file}" image)"
if [[ -n "${saved_hash}" && -n "${saved_image}" && "${saved_hash}" != "${source_hash}" && "${saved_image}" == "${image_ref}" ]]; then
echo "Website source changed but the computed php-website image ref is still ${image_ref}." >&2
echo "Check WEBSITE_IMAGE_TAG or the website image tag generator before rebuilding." >&2
exit 1
fi
}
demos_image_is_current() {
local state_file="$1"
local source_hash="$2"
local platforms="$3"
local image_ref="$4"
local registry_endpoint="$5"
local image_tag
local saved_hash
local saved_platforms
local saved_image
[[ -f "${state_file}" ]] || return 1
saved_hash="$(image_state_value "${state_file}" source_hash)"
saved_platforms="$(image_state_value "${state_file}" platforms)"
saved_image="$(image_state_value "${state_file}" image)"
[[ "${saved_hash}" == "${source_hash}" ]] || return 1
[[ "${saved_platforms}" == "${platforms}" ]] || return 1
[[ "${saved_image}" == "${image_ref}" ]] || return 1
image_tag="$(image_ref_tag "${image_ref}")"
registry_image_exists "${registry_endpoint}" demos-static "${image_tag}"
}
write_website_image_state() {
local state_file="$1"
local source_hash="$2"
local platforms="$3"
local image_ref="$4"
mkdir -p "$(dirname "${state_file}")"
{
printf 'source_hash=%s\n' "${source_hash}"
printf 'platforms=%s\n' "${platforms}"
printf 'image=%s\n' "${image_ref}"
} > "${state_file}"
}
write_demos_image_state() {
local state_file="$1"
local source_hash="$2"
local platforms="$3"
local image_ref="$4"
mkdir -p "$(dirname "${state_file}")"
{
printf 'source_hash=%s\n' "${source_hash}"
printf 'platforms=%s\n' "${platforms}"
printf 'image=%s\n' "${image_ref}"
} > "${state_file}"
}
path_available_mb() {
local path="$1"
while [[ ! -e "${path}" && "${path}" != "/" ]]; do
path="$(dirname "${path}")"
done
df -Pm "${path}" | awk 'NR == 2 {print $4}'
}
docker_root_dir() {
docker info --format '{{.DockerRootDir}}' 2>/dev/null || printf '/var/lib/docker\n'
}
prune_unused_docker_build_data() {
docker buildx rm lab-builder 2>/dev/null || true
docker rm -f buildx_buildkit_lab-builder0 2>/dev/null || true
docker builder prune -af 2>/dev/null || true
docker system prune -af 2>/dev/null || true
}
ensure_docker_build_space() {
local docker_root
local free_mb
local min_free_mb
min_free_mb="${DOCKER_BUILD_MIN_FREE_MB:-4096}"
docker_root="$(docker_root_dir)"
free_mb="$(path_available_mb "${docker_root}")"
if (( free_mb >= min_free_mb )); then
return 0
fi
echo "Docker data root ${docker_root} has ${free_mb}MiB free; pruning unused Docker build data..."
prune_unused_docker_build_data
free_mb="$(path_available_mb "${docker_root}")"
if (( free_mb < min_free_mb )); then
echo "Docker data root ${docker_root} still has only ${free_mb}MiB free after cleanup." >&2
echo "Free space there or move Docker's data-root to a larger filesystem such as /home before building." >&2
echo "Override the threshold with DOCKER_BUILD_MIN_FREE_MB if this host can build with less space." >&2
exit 1
fi
}
prepare_buildx_builder() {
local registry_endpoint="$1"
docker run --rm --privileged multiarch/qemu-user-static --reset -p yes
cat <<EOF > "${BUILDX_CONFIG}"
[registry."${registry_endpoint}"]
http = true
insecure = true
[registry."127.0.0.1:30500"]
http = true
insecure = true
[registry."localhost:30500"]
http = true
insecure = true
EOF
docker buildx rm lab-builder 2>/dev/null || true
docker buildx create --name lab-builder --driver docker-container --driver-opt network=host --config "${BUILDX_CONFIG}" --use
docker buildx inspect --bootstrap
}
ensure_cosign_available() {
local arch
local cosign_url
local discovered_bin
local target_dir
local target_path
local tmp_path
if [[ -n "${COSIGN_BIN}" ]]; then
if [[ -x "${COSIGN_BIN}" ]] && "${COSIGN_BIN}" version >/dev/null 2>&1; then
return 0
fi
echo "COSIGN_BIN points to ${COSIGN_BIN}, but it is not executable or crashes when run." >&2
exit 1
fi
if command -v cosign >/dev/null 2>&1; then
discovered_bin="$(command -v cosign)"
if "${discovered_bin}" version >/dev/null 2>&1; then
COSIGN_BIN="${discovered_bin}"
return 0
fi
echo "Ignoring system Cosign at ${discovered_bin} because it failed a version check." >&2
fi
case "$(uname -m)" in
x86_64 | amd64)
arch="amd64"
;;
aarch64 | arm64)
arch="arm64"
;;
*)
echo "Unsupported Cosign install architecture: $(uname -m)" >&2
exit 1
;;
esac
target_dir="${HOMELAB_STATE_DIR}/bin"
target_path="${target_dir}/cosign-v${COSIGN_VERSION}-linux-${arch}"
if [[ -x "${target_path}" ]]; then
if "${target_path}" version >/dev/null 2>&1; then
COSIGN_BIN="${target_path}"
return 0
fi
echo "Removing cached Cosign at ${target_path} because it failed a version check." >&2
rm -f "${target_path}"
fi
if ! command -v curl >/dev/null 2>&1; then
echo "curl is required to download Cosign ${COSIGN_VERSION}." >&2
exit 1
fi
mkdir -p "${target_dir}"
tmp_path="${target_path}.tmp"
cosign_url="https://github.com/sigstore/cosign/releases/download/v${COSIGN_VERSION}/cosign-linux-${arch}"
echo "Installing Cosign ${COSIGN_VERSION} into ${target_path}..."
curl -fsSL "${cosign_url}" -o "${tmp_path}"
chmod 0755 "${tmp_path}"
mv "${tmp_path}" "${target_path}"
if ! "${target_path}" version >/dev/null 2>&1; then
echo "Downloaded Cosign ${COSIGN_VERSION} to ${target_path}, but it failed a version check." >&2
exit 1
fi
COSIGN_BIN="${target_path}"
}
ensure_cosign_password() {
if [[ -n "${COSIGN_PASSWORD:-}" ]]; then
return 0
fi
if [[ -r "${COSIGN_PASSWORD_FILE}" ]]; then
COSIGN_PASSWORD="$(<"${COSIGN_PASSWORD_FILE}")"
export COSIGN_PASSWORD
return 0
fi
mkdir -p "$(dirname "${COSIGN_PASSWORD_FILE}")"
if command -v openssl >/dev/null 2>&1; then
openssl rand -hex 32 > "${COSIGN_PASSWORD_FILE}"
elif command -v python3 >/dev/null 2>&1; then
python3 - <<'PY' > "${COSIGN_PASSWORD_FILE}"
import secrets
print(secrets.token_hex(32))
PY
else
echo "openssl or python3 is required to generate a non-interactive Cosign key password." >&2
exit 1
fi
chmod 0600 "${COSIGN_PASSWORD_FILE}"
COSIGN_PASSWORD="$(<"${COSIGN_PASSWORD_FILE}")"
export COSIGN_PASSWORD
}
run_cosign() {
ensure_cosign_available
ensure_cosign_password
COSIGN_PASSWORD="${COSIGN_PASSWORD}" "${COSIGN_BIN}" "$@"
}
ensure_cosign_keypair() {
ensure_cosign_available
ensure_cosign_password
if [[ -f "${COSIGN_KEY_PATH}" && -f "${COSIGN_PUBLIC_KEY_PATH}" ]]; then
return 0
fi
if [[ -f "${COSIGN_KEY_PATH}" || -f "${COSIGN_PUBLIC_KEY_PATH}" ]]; then
echo "Found only one Cosign key file. Expected both ${COSIGN_KEY_PATH} and ${COSIGN_PUBLIC_KEY_PATH}." >&2
exit 1
fi
mkdir -p "$(dirname "${COSIGN_KEY_PATH}")"
echo "Generating homelab Cosign key pair under ${REPO_ROOT}/.lab..."
COSIGN_PASSWORD="${COSIGN_PASSWORD}" "${COSIGN_BIN}" generate-key-pair --output-key-prefix "${COSIGN_KEY_PREFIX}"
chmod 0600 "${COSIGN_KEY_PATH}"
chmod 0644 "${COSIGN_PUBLIC_KEY_PATH}"
}
publish_cosign_public_key_config_map() {
kubectl --kubeconfig "${KUBECONFIG_PATH}" create namespace kyverno --dry-run=client -o yaml |
kubectl --kubeconfig "${KUBECONFIG_PATH}" apply -f -
kubectl --kubeconfig "${KUBECONFIG_PATH}" -n kyverno create configmap "${HOMELAB_COSIGN_PUBLIC_KEY_CONFIGMAP}" \
--from-file=cosign.pub="${COSIGN_PUBLIC_KEY_PATH}" \
--dry-run=client -o yaml |
kubectl --kubeconfig "${KUBECONFIG_PATH}" apply -f -
}
cosign_registry_flags() {
local registry_endpoint="$1"
local image_ref="$2"
if [[ "${image_ref}" == "${registry_endpoint}/"* ]]; then
printf '%s\n' "--allow-http-registry"
fi
}
image_supply_chain_metadata_exists() {
local image_ref="$1"
local registry_endpoint="$2"
local digest_ref
local -a registry_flags=()
if ! digest_ref="$(image_digest_ref "${image_ref}")"; then
return 1
fi
mapfile -t registry_flags < <(cosign_registry_flags "${registry_endpoint}" "${digest_ref}")
run_cosign verify \
--key "${COSIGN_PUBLIC_KEY_PATH}" \
--insecure-ignore-tlog=true \
"${registry_flags[@]}" \
"${digest_ref}" >/dev/null 2>&1 &&
run_cosign verify-attestation \
--key "${COSIGN_PUBLIC_KEY_PATH}" \
--type "${HOMELAB_SBOM_PREDICATE_TYPE}" \
--insecure-ignore-tlog=true \
"${registry_flags[@]}" \
"${digest_ref}" >/dev/null 2>&1
}
write_image_sbom_predicate() {
local image_ref="$1"
local output_file="$2"
local source_hash="$3"
docker buildx imagetools inspect "${image_ref}" --format '{{ json .SBOM.SPDX }}' > "${output_file}"
python3 - "${output_file}" "${image_ref}" "${source_hash}" <<'PY'
from datetime import datetime, timezone
import json
import re
import sys
path = sys.argv[1]
image_ref = sys.argv[2]
source_hash = sys.argv[3]
try:
with open(path, encoding="utf-8") as handle:
document = json.load(handle)
except json.JSONDecodeError:
document = None
if not isinstance(document, dict):
safe_ref = re.sub(r"[^A-Za-z0-9.-]+", "-", image_ref).strip("-")
document = {
"spdxVersion": "SPDX-2.3",
"dataLicense": "CC0-1.0",
"SPDXID": "SPDXRef-DOCUMENT",
"name": f"homelab image SBOM for {image_ref}",
"documentNamespace": f"https://homelab.local/spdx/{safe_ref}/{source_hash}",
"creationInfo": {
"created": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
"creators": ["Tool: jeannie"],
},
"packages": [
{
"name": image_ref,
"SPDXID": "SPDXRef-Image",
"downloadLocation": "NOASSERTION",
"filesAnalyzed": False,
"licenseConcluded": "NOASSERTION",
"licenseDeclared": "NOASSERTION",
"copyrightText": "NOASSERTION",
}
],
"relationships": [
{
"spdxElementId": "SPDXRef-DOCUMENT",
"relationshipType": "DESCRIBES",
"relatedSpdxElement": "SPDXRef-Image",
}
],
}
with open(path, "w", encoding="utf-8") as handle:
json.dump(document, handle, sort_keys=True)
handle.write("\n")
if not isinstance(document, dict):
raise SystemExit("image SBOM predicate is not a JSON object")
if document.get("SPDXID") != "SPDXRef-DOCUMENT":
raise SystemExit("image SBOM predicate is not an SPDX document")
if not document.get("packages"):
raise SystemExit("image SBOM predicate does not include packages")
PY
}
image_digest_ref() {
local image_ref="$1"
local digest
local repository
if [[ "${image_ref}" == *@sha256:* ]]; then
printf '%s\n' "${image_ref}"
return 0
fi
digest="$(docker buildx imagetools inspect "${image_ref}" --format '{{ .Manifest.Digest }}')"
if [[ -z "${digest}" || "${digest}" == "<no value>" ]]; then
echo "Unable to resolve image digest for ${image_ref}." >&2
return 1
fi
if [[ "${image_ref##*/}" == *:* ]]; then
repository="${image_ref%:*}"
else
repository="${image_ref}"
fi
printf '%s@%s\n' "${repository}" "${digest}"
}
publish_image_supply_chain_metadata() {
local image_ref="$1"
local registry_endpoint="$2"
local source_hash="$3"
local digest_ref
local sbom_file
local -a registry_flags=()
if image_supply_chain_metadata_exists "${image_ref}" "${registry_endpoint}"; then
echo "Image ${image_ref} already has a valid Cosign signature and signed SPDX SBOM."
return 0
fi
if ! digest_ref="$(image_digest_ref "${image_ref}")" || [[ -z "${digest_ref}" ]]; then
echo "Cannot publish supply-chain metadata because image digest resolution failed for ${image_ref}." >&2
return 1
fi
mapfile -t registry_flags < <(cosign_registry_flags "${registry_endpoint}" "${digest_ref}")
sbom_file="$(mktemp)"
write_image_sbom_predicate "${digest_ref}" "${sbom_file}" "${source_hash}"
echo "Signing image ${digest_ref} and attaching signed SPDX SBOM..."
run_cosign sign \
--yes \
--key "${COSIGN_KEY_PATH}" \
--tlog-upload=false \
-a "homelab.dev/source-hash=${source_hash}" \
"${registry_flags[@]}" \
"${digest_ref}"
run_cosign attest \
--yes \
--key "${COSIGN_KEY_PATH}" \
--predicate "${sbom_file}" \
--type "${HOMELAB_SBOM_PREDICATE_TYPE}" \
--tlog-upload=false \
"${registry_flags[@]}" \
"${digest_ref}"
rm -f "${sbom_file}"
if ! image_supply_chain_metadata_exists "${image_ref}" "${registry_endpoint}"; then
echo "Cosign verification failed after signing ${digest_ref}." >&2
exit 1
fi
}
dump_argocd_debug() {
local app="$1"
kubectl --kubeconfig "${KUBECONFIG_PATH}" -n argocd get application "${app}" -o yaml || true
kubectl --kubeconfig "${KUBECONFIG_PATH}" -n argocd describe application "${app}" || true
kubectl --kubeconfig "${KUBECONFIG_PATH}" -n argocd get pods -o wide || true
kubectl --kubeconfig "${KUBECONFIG_PATH}" -n argocd logs deployment/argocd-repo-server --tail=120 || true
kubectl --kubeconfig "${KUBECONFIG_PATH}" -n argocd logs statefulset/argocd-application-controller --tail=120 || true
}
dump_namespace_debug() {
local namespace="$1"
kubectl --kubeconfig "${KUBECONFIG_PATH}" -n "${namespace}" get all -o wide || true
kubectl --kubeconfig "${KUBECONFIG_PATH}" -n "${namespace}" get pvc -o wide || true
kubectl --kubeconfig "${KUBECONFIG_PATH}" -n "${namespace}" describe pods || true
kubectl --kubeconfig "${KUBECONFIG_PATH}" -n "${namespace}" get events --sort-by=.lastTimestamp 2>/dev/null | tail -80 || true
}
wait_for_namespace() {
local namespace="$1"
local app="$2"
local timeout_seconds="$3"
local elapsed=0
until kubectl --kubeconfig "${KUBECONFIG_PATH}" get namespace "${namespace}" >/dev/null 2>&1; do
if ((elapsed >= timeout_seconds)); then
echo "Timed out waiting for namespace ${namespace} from Argo CD app ${app}" >&2
dump_argocd_debug "${app}"
exit 1
fi
sleep 5
elapsed=$((elapsed + 5))
done
}
wait_for_namespaced_resource() {
local namespace="$1"
local kind="$2"
local name="$3"
local app="$4"
local timeout_seconds="$5"
local elapsed=0
until kubectl --kubeconfig "${KUBECONFIG_PATH}" -n "${namespace}" get "${kind}/${name}" >/dev/null 2>&1; do
if ((elapsed >= timeout_seconds)); then
echo "Timed out waiting for ${kind}/${name} in namespace ${namespace} from Argo CD app ${app}" >&2
dump_argocd_debug "${app}"
kubectl --kubeconfig "${KUBECONFIG_PATH}" -n "${namespace}" get events --sort-by=.lastTimestamp 2>/dev/null | tail -80 || true
exit 1
fi
sleep 5
elapsed=$((elapsed + 5))
done
}
wait_for_cluster_resource() {
local kind="$1"
local name="$2"
local app="$3"
local timeout_seconds="$4"
local elapsed=0
local api_resource
api_resource="${kind%%/*}"
if ! kubectl --kubeconfig "${KUBECONFIG_PATH}" get crd "${api_resource}" >/dev/null 2>&1; then
echo "Required CRD ${api_resource} is not installed; cannot wait for ${kind}/${name} from Argo CD app ${app}." >&2
kubectl --kubeconfig "${KUBECONFIG_PATH}" -n argocd get application "${app}" \
-o jsonpath='sync={.status.sync.status} health={.status.health.status} message={.status.operationState.message}{"\n"}' 2>/dev/null || true
dump_argocd_debug "${app}"
exit 1
fi
until kubectl --kubeconfig "${KUBECONFIG_PATH}" get "${kind}/${name}" >/dev/null 2>&1; do
if ((elapsed >= timeout_seconds)); then
echo "Timed out waiting for ${kind}/${name} from Argo CD app ${app}" >&2
dump_argocd_debug "${app}"
exit 1
fi
sleep 5
elapsed=$((elapsed + 5))
done
}
wait_for_deployment_ready() {
local namespace="$1"
local deployment="$2"
local app="$3"
local timeout_seconds="$4"
local desired_replicas
local ready_replicas
local deadline
if ! [[ "${timeout_seconds}" =~ ^[0-9]+$ ]] || ((timeout_seconds < 1)); then
echo "Deployment readiness timeout must be a positive number of seconds." >&2
return 2
fi
desired_replicas="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" -n "${namespace}" get deployment "${deployment}" -o jsonpath='{.spec.replicas}' 2>/dev/null || true)"
desired_replicas="${desired_replicas:-1}"
deadline=$((SECONDS + timeout_seconds))
if ! kubectl --kubeconfig "${KUBECONFIG_PATH}" -n "${namespace}" rollout status "deployment/${deployment}" --timeout="${timeout_seconds}s"; then
echo "Timed out waiting for deployment/${deployment} rollout in namespace ${namespace}" >&2
dump_argocd_debug "${app}"
dump_namespace_debug "${namespace}"
exit 1
fi
until ready_replicas="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" -n "${namespace}" get deployment "${deployment}" -o jsonpath='{.status.readyReplicas}' 2>/dev/null)"; \
(( ${ready_replicas:-0} >= desired_replicas )); do
if ((SECONDS >= deadline)); then
echo "Timed out waiting for deployment/${deployment} in namespace ${namespace} to have ${desired_replicas} ready replicas" >&2
dump_argocd_debug "${app}"
dump_namespace_debug "${namespace}"
exit 1
fi
sleep 5
done
}
cleanup_disabled_deployment_pods() {
local namespace="$1"
local deployment="$2"
local selector="$3"
local app="$4"
local desired_replicas
desired_replicas="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" -n "${namespace}" get deployment "${deployment}" -o jsonpath='{.spec.replicas}' 2>/dev/null || true)"
if [[ "${desired_replicas:-0}" != "0" ]]; then
return 0
fi
echo "Cleaning up stale pods for disabled deployment/${deployment} in namespace ${namespace}."
if ! kubectl --kubeconfig "${KUBECONFIG_PATH}" -n "${namespace}" delete pod -l "${selector}" --ignore-not-found --wait=true --timeout=120s; then
echo "Failed to clean up stale pods for deployment/${deployment} in namespace ${namespace}" >&2
dump_argocd_debug "${app}"
dump_namespace_debug "${namespace}"
exit 1
fi
}
scale_down_disabled_deployment() {
local namespace="$1"
local deployment="$2"
local selector="$3"
local app="$4"
echo "Scaling disabled deployment/${deployment} in namespace ${namespace} to 0 replicas."
if ! kubectl --kubeconfig "${KUBECONFIG_PATH}" -n "${namespace}" scale "deployment/${deployment}" --replicas=0; then
echo "Failed to scale disabled deployment/${deployment} in namespace ${namespace}." >&2
dump_argocd_debug "${app}"
dump_namespace_debug "${namespace}"
exit 1
fi
cleanup_disabled_deployment_pods "${namespace}" "${deployment}" "${selector}" "${app}"
}
deploy_gitea() {
local mode="${LAB_GITEA_DEPLOY:-true}"
local gitea_host="${LAB_GITEA_HOST:-${LAB_DEBIAN_LAN_IP:-192.168.100.73}}"
local gitea_user="${LAB_GITEA_USER:-${LAB_DEBIAN_USER:-jv}}"
local gitea_key="${LAB_GITEA_SSH_KEY_PATH:-${LAB_RASPBERRY_SSH_KEY_PATH:-/home/jv/.ssh/id_ed25519}}"
local install_dir="${LAB_GITEA_INSTALL_DIR:-/data/homelab-gitea}"
local image="${LAB_GITEA_IMAGE:-gitea/gitea:1.21.7}"
local http_port="${LAB_GITEA_HTTP_PORT:-3000}"
local ssh_port="${LAB_GITEA_SSH_PORT:-32222}"
local domain="${LAB_GITEA_DOMAIN:-${LAB_DOMAIN:?LAB_DOMAIN is required from homelab.yml}}"
local root_url="${LAB_GITEA_ROOT_URL:-${LAB_PUBLIC_URL:?LAB_PUBLIC_URL is required from homelab.yml}/git/}"
local container_name="${LAB_GITEA_CONTAINER_NAME:-homelab-gitea}"
local compose_file="${REPO_ROOT}/infra/gitea/docker-compose.yml"
local install_docker="${LAB_GITEA_INSTALL_DOCKER:-false}"
require_debian_server "deploy-gitea"
if disabled_value "${mode}"; then
install_gitea_backup_timer
return 0
fi
if [[ ! -s "${compose_file}" ]]; then
echo "Missing ${compose_file}" >&2
exit 1
fi
echo "Deploying external Gitea on ${gitea_user}@${gitea_host}:${http_port}..."
ssh -i "${gitea_key}" -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new "${gitea_user}@${gitea_host}" "rm -rf /tmp/homelab-gitea && mkdir -p /tmp/homelab-gitea"
scp -i "${gitea_key}" -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new "${compose_file}" "${gitea_user}@${gitea_host}:/tmp/homelab-gitea/docker-compose.yml"
ssh -i "${gitea_key}" -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new "${gitea_user}@${gitea_host}" "set -eu
install_dir='${install_dir}'
install_docker='${install_docker}'
install_missing_packages() {
missing_packages=''
for package in \"\$@\"; do
if ! dpkg-query -W -f='\${Status}' \"\$package\" 2>/dev/null | grep -q 'install ok installed'; then
missing_packages=\"\$missing_packages \$package\"
fi
done
if [ -n \"\$missing_packages\" ]; then
sudo apt-get update
sudo apt-get install -y --no-install-recommends \$missing_packages
fi
}
install_missing_packages ca-certificates curl iptables
if ! command -v docker >/dev/null 2>&1; then
if [ \"\$install_docker\" = 'true' ]; then
curl -fsSL https://get.docker.com | sudo sh
else
echo 'Docker is not installed on the Gitea host. Install Docker through the host bootstrap first, or rerun with LAB_GITEA_INSTALL_DOCKER=true to allow get.docker.com installation.' >&2
exit 1
fi
fi
if ! sudo docker compose version >/dev/null 2>&1; then
install_missing_packages docker-compose-plugin
fi
repair_docker_iptables() {
if sudo iptables -t nat -S DOCKER >/dev/null 2>&1; then
return 0
fi
echo 'Docker NAT chain is missing on the Gitea host; restarting Docker once to restore iptables state...'
sudo systemctl restart docker
sleep 3
if sudo iptables -t nat -S DOCKER >/dev/null 2>&1; then
return 0
fi
echo 'Docker NAT chain is still missing after restarting Docker.' >&2
sudo iptables -t nat -S >&2 || true
sudo systemctl status docker --no-pager -l >&2 || true
exit 1
}
repair_docker_iptables
sudo mkdir -p \"\$install_dir/data\"
sudo cp /tmp/homelab-gitea/docker-compose.yml \"\$install_dir/docker-compose.yml\"
sudo chown -R 1000:1000 \"\$install_dir/data\"
sudo tee \"\$install_dir/.env\" >/dev/null <<ENV_EOT
GITEA_IMAGE=${image}
GITEA_CONTAINER_NAME=${container_name}
GITEA_HTTP_PORT=${http_port}
GITEA_SSH_PORT=${ssh_port}
GITEA_DOMAIN=${domain}
GITEA_ROOT_URL=${root_url}
GITEA_UID=1000
GITEA_GID=1000
ENV_EOT
cd \"\$install_dir\"
sudo docker compose pull
sudo docker compose up -d --remove-orphans
sudo docker compose ps
"
install_gitea_backup_timer
}
install_missing_debian_packages() {
local missing_packages=()
local package
for package in "$@"; do
if ! dpkg-query -W -f='${Status}' "${package}" 2>/dev/null | grep -q "install ok installed"; then
missing_packages+=("${package}")
fi
done
if ((${#missing_packages[@]})); then
sudo apt-get update
sudo apt-get install -y --no-install-recommends "${missing_packages[@]}"
fi
}
ensure_local_docker_compose() {
local command_name="$1"
local install_docker="$2"
install_missing_debian_packages ca-certificates curl iptables
if ! command -v docker >/dev/null 2>&1; then
if [[ "${install_docker}" == "true" ]]; then
curl -fsSL https://get.docker.com | sudo sh
else
echo "Docker is not installed on the Debian host. Install Docker through host bootstrap first, or rerun with LAB_${command_name}_INSTALL_DOCKER=true to allow get.docker.com installation." >&2
exit 1
fi
fi
if ! sudo docker compose version >/dev/null 2>&1; then
install_missing_debian_packages docker-compose-plugin
fi
}
repair_local_docker_iptables() {
if sudo iptables -t nat -S DOCKER >/dev/null 2>&1; then
return 0
fi
echo "Docker NAT chain is missing on the Debian host; restarting Docker once to restore iptables state..."
sudo systemctl restart docker
sleep 3
if sudo iptables -t nat -S DOCKER >/dev/null 2>&1; then
return 0
fi
echo "Docker NAT chain is still missing after restarting Docker." >&2
sudo iptables -t nat -S >&2 || true
sudo systemctl status docker --no-pager -l >&2 || true
exit 1
}
deploy_api() {
local target="${JEANNIE_SSH_TARGET:-debian-lab}"
local staging="${JEANNIE_API_STAGING_DIR:-/tmp/jeannie-api}"
local server_token="${JEANNIE_SERVER_TOKEN:-${JEANNIE_REMOTE_TOKEN:-}}"
local quoted_token
if [[ -z "${server_token}" ]]; then
echo "Set JEANNIE_SERVER_TOKEN before deploying the Jeannie API." >&2
return 1
fi
if [[ "$(uname -s)" == "Linux" ]] && [[ -r /etc/os-release ]] &&
grep -q '^ID=debian$' /etc/os-release; then
JEANNIE_SERVER_TOKEN="${server_token}" bash "${REPO_ROOT}/infra/jeannie-temporal/deploy-remote.sh"
return 0
fi
quoted_token="$(printf '%q' "${server_token}")"
echo "Staging the Jeannie API on ${target}..."
tar -czf - cmd internal infra go.mod jeannie lib scripts homelab.yml |
ssh -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new "${target}" \
"rm -rf '${staging}' && mkdir -p '${staging}' && tar -xzf - -C '${staging}'"
ssh -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new "${target}" \
"cd '${staging}' && JEANNIE_SERVER_TOKEN=${quoted_token} bash infra/jeannie-temporal/deploy-remote.sh"
echo "Jeannie API deployed on ${target}."
}
deploy_heimdall() {
local mode="${LAB_HEIMDALL_DEPLOY:-true}"
local install_dir="${LAB_HEIMDALL_INSTALL_DIR:-/data/homelab-heimdall}"
local data_dir="${LAB_HEIMDALL_DATA_DIR:-${install_dir}/data}"
local config_dir="${LAB_HEIMDALL_CONFIG_DIR:-${data_dir}/config}"
local http_port="${LAB_HEIMDALL_HTTP_PORT:-8082}"
local bind_ip="${LAB_HEIMDALL_BIND_IP:-0.0.0.0}"
local public_url="${LAB_HEIMDALL_PUBLIC_URL:-https://heimdall.${LAB_DOMAIN:-lab2025.duckdns.org}/}"
local image="${HEIMDALL_IMAGE:-lscr.io/linuxserver/heimdall:v2.7.6-ls347}"
local container_name="${HEIMDALL_CONTAINER_NAME:-homelab-heimdall}"
local seeder_container_name="${HEIMDALL_SEEDER_CONTAINER_NAME:-homelab-heimdall-link-seeder}"
local network="${HEIMDALL_NETWORK:-homelab-heimdall}"
local homepage_image="${HOMEPAGE_IMAGE:-ghcr.io/gethomepage/homepage:v1.5.0}"
local homepage_container_name="${HOMEPAGE_CONTAINER_NAME:-homelab-homepage}"
local homepage_http_port="${LAB_HOMEPAGE_HTTP_PORT:-8083}"
local homepage_bind_ip="${LAB_HOMEPAGE_BIND_IP:-0.0.0.0}"
local homepage_public_url="${LAB_HOMEPAGE_PUBLIC_URL:-https://homepage.${LAB_DOMAIN:-lab2025.duckdns.org}/}"
local homepage_config_dir="${LAB_HOMEPAGE_CONFIG_DIR:-${install_dir}/homepage/config}"
local install_docker="${LAB_HEIMDALL_INSTALL_DOCKER:-false}"
local source_dir="${REPO_ROOT}/infra/heimdall"
local link_generator="${REPO_ROOT}/scripts/generate-heimdall-links"
local homepage_generator="${REPO_ROOT}/scripts/generate-homepage-config"
local elapsed=0
local value_name
local value
require_debian_server "deploy-heimdall"
if disabled_value "${mode}"; then
return 0
fi
for value_name in install_dir data_dir config_dir http_port bind_ip public_url image container_name seeder_container_name network homepage_image homepage_container_name homepage_http_port homepage_bind_ip homepage_public_url homepage_config_dir install_docker; do
value="${!value_name}"
if [[ "${value}" == *$'\n'* ]]; then
echo "${value_name} cannot contain a newline." >&2
exit 1
fi
done
if [[ -x "${link_generator}" ]]; then
"${link_generator}"
fi
if [[ -x "${homepage_generator}" ]]; then
"${homepage_generator}"
fi
if [[ ! -s "${source_dir}/docker-compose.yml" || ! -s "${source_dir}/links.json" || ! -s "${source_dir}/seed-heimdall.py" || ! -s "${source_dir}/homepage/services.yaml" ]]; then
echo "Missing Heimdall source files in ${source_dir}" >&2
exit 1
fi
echo "Deploying external Heimdall on the Debian host at ${install_dir}..."
ensure_local_docker_compose "HEIMDALL" "${install_docker}"
repair_local_docker_iptables
sudo mkdir -p "${install_dir}" "${config_dir}" "${homepage_config_dir}"
sudo cp "${source_dir}/docker-compose.yml" "${install_dir}/docker-compose.yml"
sudo cp "${source_dir}/links.json" "${install_dir}/links.json"
sudo cp "${source_dir}/seed-heimdall.py" "${install_dir}/seed-heimdall.py"
sudo cp "${source_dir}/homepage/services.yaml" "${homepage_config_dir}/services.yaml"
sudo cp "${source_dir}/homepage/bookmarks.yaml" "${homepage_config_dir}/bookmarks.yaml"
sudo cp "${source_dir}/homepage/settings.yaml" "${homepage_config_dir}/settings.yaml"
sudo cp "${source_dir}/homepage/widgets.yaml" "${homepage_config_dir}/widgets.yaml"
sudo chown -R 1000:1000 "${data_dir}"
sudo tee "${install_dir}/.env" >/dev/null <<ENV_EOT
HEIMDALL_IMAGE=${image}
HEIMDALL_CONTAINER_NAME=${container_name}
HEIMDALL_SEEDER_CONTAINER_NAME=${seeder_container_name}
HEIMDALL_HTTP_PORT=${http_port}
HEIMDALL_BIND_IP=${bind_ip}
HEIMDALL_PUBLIC_URL=${public_url%/}
HEIMDALL_CONFIG_DIR=${config_dir}
HEIMDALL_UID=1000
HEIMDALL_GID=1000
HEIMDALL_NETWORK=${network}
HOMEPAGE_IMAGE=${homepage_image}
HOMEPAGE_CONTAINER_NAME=${homepage_container_name}
HOMEPAGE_HTTP_PORT=${homepage_http_port}
HOMEPAGE_BIND_IP=${homepage_bind_ip}
HOMEPAGE_PUBLIC_URL=${homepage_public_url%/}
HOMEPAGE_CONFIG_DIR=${homepage_config_dir}
HOMEPAGE_ALLOWED_HOSTS=homepage.${LAB_DOMAIN:-lab2025.duckdns.org},127.0.0.1:${homepage_http_port},localhost:${homepage_http_port}
HOMEPAGE_UID=1000
HOMEPAGE_GID=1000
TZ=America/Mexico_City
ENV_EOT
(
cd "${install_dir}"
sudo docker compose pull
sudo docker compose up -d --remove-orphans
sudo docker compose ps
)
until curl -fsS --connect-timeout 5 "http://127.0.0.1:${http_port}/" >/dev/null; do
if ((elapsed >= 180)); then
echo "Timed out waiting for Heimdall on http://127.0.0.1:${http_port}/" >&2
(cd "${install_dir}" && sudo docker compose ps && sudo docker compose logs --tail=120) >&2 || true
exit 1
fi
sleep 5
elapsed=$((elapsed + 5))
done
elapsed=0
until curl -fsS --connect-timeout 5 "http://127.0.0.1:${homepage_http_port}/" >/dev/null; do
if ((elapsed >= 360)); then
echo "Timed out waiting for Homepage on http://127.0.0.1:${homepage_http_port}/" >&2
(cd "${install_dir}" && sudo docker compose ps && sudo docker compose logs --tail=120) >&2 || true
exit 1
fi
sleep 5
elapsed=$((elapsed + 5))
done
echo "Heimdall is reachable at http://127.0.0.1:${http_port}/ and ${public_url%/}/."
echo "Homepage is reachable at http://127.0.0.1:${homepage_http_port}/ and ${homepage_public_url%/}/."
}
deploy_searxng() {
local mode="${LAB_SEARXNG_DEPLOY:-true}"
local install_dir="${LAB_SEARXNG_INSTALL_DIR:-/data/homelab-searxng}"
local http_port="${LAB_SEARXNG_HTTP_PORT:-8888}"
local bind_ip="${LAB_SEARXNG_BIND_IP:-0.0.0.0}"
local public_url="${LAB_SEARXNG_PUBLIC_URL:-https://search.${LAB_DOMAIN:-lab2025.duckdns.org}/}"
local image="${SEARXNG_IMAGE:-docker.io/searxng/searxng:2026.12.3-44427d4a8}"
local valkey_image="${VALKEY_IMAGE:-docker.io/valkey/valkey:9-alpine}"
local container_name="${SEARXNG_CONTAINER_NAME:-homelab-searxng}"
local valkey_container_name="${VALKEY_CONTAINER_NAME:-homelab-searxng-valkey}"
local source_dir="${REPO_ROOT}/infra/searxng"
local install_docker="${LAB_SEARXNG_INSTALL_DOCKER:-false}"
local secret=""
local elapsed=0
local value_name
local value
require_debian_server "deploy-searxng"
if disabled_value "${mode}"; then
return 0
fi
for value_name in install_dir http_port bind_ip public_url image valkey_image container_name valkey_container_name install_docker; do
value="${!value_name}"
if [[ "${value}" == *$'\n'* ]]; then
echo "${value_name} cannot contain a newline." >&2
return 1
fi
done
if ! [[ "${http_port}" =~ ^[0-9]+$ ]] || ((http_port < 1 || http_port > 65535)); then
echo "LAB_SEARXNG_HTTP_PORT must be a valid TCP port." >&2
return 1
fi
if [[ ! -s "${source_dir}/docker-compose.yml" || ! -s "${source_dir}/settings.yml" || ! -s "${source_dir}/limiter.toml" ]]; then
echo "Missing SearXNG source files in ${source_dir}." >&2
return 1
fi
ensure_local_docker_compose "SEARXNG" "${install_docker}"
repair_local_docker_iptables
sudo mkdir -p "${install_dir}/config"
sudo cp "${source_dir}/docker-compose.yml" "${install_dir}/docker-compose.yml"
sudo cp "${source_dir}/settings.yml" "${install_dir}/config/settings.yml"
sudo cp "${source_dir}/limiter.toml" "${install_dir}/config/limiter.toml"
sudo chmod 0644 "${install_dir}/docker-compose.yml" "${install_dir}/config/settings.yml" "${install_dir}/config/limiter.toml"
if sudo test -s "${install_dir}/.env"; then
secret="$(sudo sed -n 's/^SEARXNG_SECRET=//p' "${install_dir}/.env" | head -n 1)"
fi
if ! [[ "${secret}" =~ ^[[:xdigit:]]{64}$ ]]; then
secret="$(openssl rand -hex 32)"
fi
umask 077
printf '%s\n' \
"SEARXNG_IMAGE=${image}" \
"VALKEY_IMAGE=${valkey_image}" \
"SEARXNG_CONTAINER_NAME=${container_name}" \
"VALKEY_CONTAINER_NAME=${valkey_container_name}" \
"SEARXNG_BIND_IP=${bind_ip}" \
"SEARXNG_HTTP_PORT=${http_port}" \
"SEARXNG_PORT=8080" \
"SEARXNG_BASE_URL=${public_url%/}/" \
"SEARXNG_SECRET=${secret}" \
"SEARXNG_LIMITER=true" \
"SEARXNG_PUBLIC_INSTANCE=false" \
"SEARXNG_IMAGE_PROXY=true" \
"SEARXNG_VALKEY_URL=valkey://valkey:6379/0" |
sudo tee "${install_dir}/.env" >/dev/null
sudo chmod 0600 "${install_dir}/.env"
(
cd "${install_dir}"
sudo docker compose pull
sudo docker compose up -d --remove-orphans
sudo docker compose ps
)
until curl -fsS --connect-timeout 5 "http://127.0.0.1:${http_port}/healthz" >/dev/null; do
if ((elapsed >= 180)); then
echo "Timed out waiting for SearXNG on http://127.0.0.1:${http_port}/healthz" >&2
(cd "${install_dir}" && sudo docker compose ps && sudo docker compose logs --tail=160) >&2 || true
return 1
fi
sleep 5
elapsed=$((elapsed + 5))
done
echo "SearXNG is healthy at http://127.0.0.1:${http_port}/ and will be published at ${public_url%/}/ by the edge stage."
}
deploy_privatebin() {
local mode="${LAB_PRIVATEBIN_DEPLOY:-true}"
local install_dir="${LAB_PRIVATEBIN_INSTALL_DIR:-/data/homelab-privatebin}"
local http_port="${LAB_PRIVATEBIN_HTTP_PORT:-8889}"
local bind_ip="${LAB_PRIVATEBIN_BIND_IP:-0.0.0.0}"
local public_url="${LAB_PRIVATEBIN_PUBLIC_URL:-https://paste.${LAB_DOMAIN:-lab2025.duckdns.org}/}"
local image="${PRIVATEBIN_IMAGE:-docker.io/privatebin/nginx-fpm-alpine:2.1.0-alpine3.24}"
local container_name="${PRIVATEBIN_CONTAINER_NAME:-homelab-privatebin}"
local source_dir="${REPO_ROOT}/infra/privatebin"
local install_docker="${LAB_PRIVATEBIN_INSTALL_DOCKER:-false}"
local elapsed=0
require_debian_server "deploy-privatebin"
disabled_value "${mode}" && return 0
if ! [[ "${http_port}" =~ ^[0-9]+$ ]] || ((http_port < 1 || http_port > 65535)); then
echo "LAB_PRIVATEBIN_HTTP_PORT must be a valid TCP port." >&2
return 1
fi
if [[ ! -s "${source_dir}/docker-compose.yml" || ! -s "${source_dir}/conf.php" ]]; then
echo "Missing PrivateBin source files in ${source_dir}." >&2
return 1
fi
ensure_local_docker_compose "PRIVATEBIN" "${install_docker}"
repair_local_docker_iptables
sudo mkdir -p "${install_dir}/data"
sudo cp "${source_dir}/docker-compose.yml" "${install_dir}/docker-compose.yml"
sudo cp "${source_dir}/conf.php" "${install_dir}/conf.php"
sudo chmod 0644 "${install_dir}/docker-compose.yml" "${install_dir}/conf.php"
sudo chown -R 65534:82 "${install_dir}/data"
umask 077
printf '%s\n' \
"PRIVATEBIN_IMAGE=${image}" \
"PRIVATEBIN_CONTAINER_NAME=${container_name}" \
"PRIVATEBIN_BIND_IP=${bind_ip}" \
"PRIVATEBIN_HTTP_PORT=${http_port}" |
sudo tee "${install_dir}/.env" >/dev/null
sudo chmod 0600 "${install_dir}/.env"
(cd "${install_dir}" && sudo docker compose pull && sudo docker compose up -d --remove-orphans && sudo docker compose ps)
until curl -fsS --connect-timeout 5 "http://127.0.0.1:${http_port}/" >/dev/null; do
if ((elapsed >= 180)); then
echo "Timed out waiting for PrivateBin on http://127.0.0.1:${http_port}/" >&2
(cd "${install_dir}" && sudo docker compose ps && sudo docker compose logs --tail=160) >&2 || true
return 1
fi
sleep 5
elapsed=$((elapsed + 5))
done
echo "PrivateBin is healthy locally and will be published at ${public_url%/}/ by the edge stage."
}
deploy_miniflux() {
local mode="${LAB_MINIFLUX_DEPLOY:-true}"
local install_dir="${LAB_MINIFLUX_INSTALL_DIR:-/data/homelab-miniflux}"
local http_port="${LAB_MINIFLUX_HTTP_PORT:-8890}"
local bind_ip="${LAB_MINIFLUX_BIND_IP:-0.0.0.0}"
local public_url="${LAB_MINIFLUX_PUBLIC_URL:-https://feeds.${LAB_DOMAIN:-lab2025.duckdns.org}/}"
local image="${MINIFLUX_IMAGE:-docker.io/miniflux/miniflux:2.3.6}"
local postgres_image="${MINIFLUX_POSTGRES_IMAGE:-docker.io/postgres:18-alpine}"
local source_dir="${REPO_ROOT}/infra/miniflux"
local install_docker="${LAB_MINIFLUX_INSTALL_DOCKER:-false}"
local admin_username="${MINIFLUX_ADMIN_USERNAME:-jv}"
local admin_password=""
local db_password=""
local elapsed=0
require_debian_server "deploy-miniflux"
disabled_value "${mode}" && return 0
if ! [[ "${http_port}" =~ ^[0-9]+$ ]] || ((http_port < 1 || http_port > 65535)); then
echo "LAB_MINIFLUX_HTTP_PORT must be a valid TCP port." >&2
return 1
fi
if [[ ! -s "${source_dir}/docker-compose.yml" ]]; then
echo "Missing Miniflux source files in ${source_dir}." >&2
return 1
fi
ensure_local_docker_compose "MINIFLUX" "${install_docker}"
repair_local_docker_iptables
sudo mkdir -p "${install_dir}/postgres"
sudo cp "${source_dir}/docker-compose.yml" "${install_dir}/docker-compose.yml"
sudo chmod 0644 "${install_dir}/docker-compose.yml"
if sudo test -s "${install_dir}/.env"; then
admin_password="$(sudo sed -n 's/^MINIFLUX_ADMIN_PASSWORD=//p' "${install_dir}/.env" | head -n 1)"
db_password="$(sudo sed -n 's/^MINIFLUX_DB_PASSWORD=//p' "${install_dir}/.env" | head -n 1)"
fi
[[ "${admin_password}" =~ ^[[:xdigit:]]{48}$ ]] || admin_password="$(openssl rand -hex 24)"
[[ "${db_password}" =~ ^[[:xdigit:]]{48}$ ]] || db_password="$(openssl rand -hex 24)"
umask 077
printf '%s\n' \
"MINIFLUX_IMAGE=${image}" \
"MINIFLUX_POSTGRES_IMAGE=${postgres_image}" \
"MINIFLUX_BIND_IP=${bind_ip}" \
"MINIFLUX_HTTP_PORT=${http_port}" \
"MINIFLUX_PUBLIC_URL=${public_url%/}/" \
"MINIFLUX_ADMIN_USERNAME=${admin_username}" \
"MINIFLUX_ADMIN_PASSWORD=${admin_password}" \
"MINIFLUX_DB_PASSWORD=${db_password}" |
sudo tee "${install_dir}/.env" >/dev/null
sudo chmod 0600 "${install_dir}/.env"
(cd "${install_dir}" && sudo docker compose pull && sudo docker compose up -d --remove-orphans && sudo docker compose ps)
until curl -fsS --connect-timeout 5 "http://127.0.0.1:${http_port}/healthcheck" >/dev/null; do
if ((elapsed >= 240)); then
echo "Timed out waiting for Miniflux on http://127.0.0.1:${http_port}/healthcheck" >&2
(cd "${install_dir}" && sudo docker compose ps && sudo docker compose logs --tail=160) >&2 || true
return 1
fi
sleep 5
elapsed=$((elapsed + 5))
done
echo "Miniflux is healthy at ${public_url%/}/. Initial credentials remain in ${install_dir}/.env."
}
deploy_opsproof() {
local install_dir="${LAB_OPSPROOF_INSTALL_DIR:-/data/homelab-opsproof}"
local http_port="${LAB_OPSPROOF_HTTP_PORT:-8891}"
local bind_ip="${LAB_OPSPROOF_BIND_IP:-127.0.0.1}"
local health_ip="${LAB_OPSPROOF_BIND_IP:-127.0.0.1}"
local go_version="${LAB_OPSPROOF_GO_VERSION:-1.27.4}"
local go_sha256="${LAB_OPSPROOF_GO_SHA256:-7226736c2339719cda28fbf3a54d71aa63bcefe376e98cef00034268dab24840}"
local starter_commit="${LAB_OPSPROOF_STARTER_COMMIT:-6dd8bd22b9d335e55b190aa16f3271e73c97cd25}"
local starter_repo="${LAB_OPSPROOF_STARTER_REPO:-https://github.com/laravel/go.git}"
local overlay_dir="${REPO_ROOT}/apps/opsproof/overlay"
local service_user="${LAB_OPSPROOF_SERVICE_USER:-$(id -un)}"
local postgres_image="${LAB_OPSPROOF_POSTGRES_IMAGE:-docker.io/postgres:18-alpine}"
local postgres_port="${LAB_OPSPROOF_POSTGRES_PORT:-55439}"
local postgres_container="${LAB_OPSPROOF_POSTGRES_CONTAINER:-opsproof-postgres}"
local postgres_db="${LAB_OPSPROOF_POSTGRES_DB:-opsproof}"
local postgres_user="${LAB_OPSPROOF_POSTGRES_USER:-opsproof}"
local jeannie_api_url="${LAB_OPSPROOF_JEANNIE_URL:-http://127.0.0.1:${LAB_JEANNIE_API_BACKEND_PORT:-8787}}"
local jeannie_api_token="${LAB_OPSPROOF_JEANNIE_TOKEN:-${JEANNIE_SERVER_TOKEN:-${JEANNIE_REMOTE_TOKEN:-}}}"
local jeannie_api_env="${LAB_OPSPROOF_JEANNIE_ENV_FILE:-/etc/jeannie/temporal.env}"
local toolchain_dir="${install_dir}/toolchains/go${go_version}"
local release_dir="${install_dir}/releases/${starter_commit}"
local database_env="${install_dir}/.database.env"
local build_dir=""
local archive=""
local app_key=""
local postgres_password=""
local postgres_uid=""
local postgres_gid=""
local database_url=""
local oidc_env="${install_dir}/.oidc.env"
local oidc_secret=""
local public_url="${LAB_OPSPROOF_PUBLIC_URL:-http://${bind_ip}:${http_port}}"
local operator_emails="${LAB_OPSPROOF_OPERATOR_EMAILS:-}"
local opsproof_dex_values=""
local elapsed=0
local node_major=""
local required
require_debian_server "deploy-opsproof"
if [[ "${health_ip}" == "0.0.0.0" || "${health_ip}" == "::" ]]; then
health_ip="127.0.0.1"
fi
if ! [[ "${http_port}" =~ ^[0-9]+$ ]] || ((http_port < 1 || http_port > 65535)); then
echo "LAB_OPSPROOF_HTTP_PORT must be a valid TCP port." >&2
return 1
fi
if ! [[ "${bind_ip}" =~ ^[0-9a-fA-F:.]+$ ]]; then
echo "LAB_OPSPROOF_BIND_IP must be an IP address." >&2
return 1
fi
if ! [[ "${go_version}" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ && "${go_sha256}" =~ ^[[:xdigit:]]{64}$ ]]; then
echo "OpsProof Go version or checksum is invalid." >&2
return 1
fi
if ! [[ "${starter_commit}" =~ ^[[:xdigit:]]{40}$ ]]; then
echo "LAB_OPSPROOF_STARTER_COMMIT must be a full Git commit SHA." >&2
return 1
fi
if ! [[ "${service_user}" =~ ^[a-z_][a-z0-9_-]*[$]?$ ]]; then
echo "LAB_OPSPROOF_SERVICE_USER is invalid." >&2
return 1
fi
if ! [[ "${postgres_port}" =~ ^[0-9]+$ ]] || ((postgres_port < 1 || postgres_port > 65535)); then
echo "LAB_OPSPROOF_POSTGRES_PORT must be a valid TCP port." >&2
return 1
fi
if ! [[ "${postgres_container}" =~ ^[a-zA-Z0-9][a-zA-Z0-9_.-]+$ ]] ||
! [[ "${postgres_db}" =~ ^[a-zA-Z_][a-zA-Z0-9_]*$ ]] ||
! [[ "${postgres_user}" =~ ^[a-zA-Z_][a-zA-Z0-9_]*$ ]]; then
echo "OpsProof PostgreSQL container, database, or user name is invalid." >&2
return 1
fi
if [[ -z "${jeannie_api_token}" && -r "${jeannie_api_env}" ]]; then
jeannie_api_token="$(sed -n 's/^JEANNIE_SERVER_TOKEN=//p' "${jeannie_api_env}" | head -n 1)"
elif [[ -z "${jeannie_api_token}" ]] && sudo test -r "${jeannie_api_env}"; then
jeannie_api_token="$(sudo sed -n 's/^JEANNIE_SERVER_TOKEN=//p' "${jeannie_api_env}" | head -n 1)"
fi
if ! [[ "${jeannie_api_url}" =~ ^https?://[^[:space:]]+$ ]]; then
echo "LAB_OPSPROOF_JEANNIE_URL must be an HTTP or HTTPS URL." >&2
return 1
fi
if ! [[ "${public_url}" =~ ^https?://[^[:space:]]+$ ]]; then
echo "LAB_OPSPROOF_PUBLIC_URL must be an HTTP or HTTPS URL." >&2
return 1
fi
if [[ -z "${operator_emails}" ]]; then
opsproof_dex_values="$(dex_secret_values)" || return 1
eval "${opsproof_dex_values}"
operator_emails="${DEX_USER_EMAIL:-}"
fi
if [[ -z "${operator_emails}" || "${operator_emails}" == *[[:space:]]* ]]; then
echo "LAB_OPSPROOF_OPERATOR_EMAILS must contain a comma-separated operator email allowlist without spaces." >&2
return 1
fi
if [[ -z "${jeannie_api_token}" || "${jeannie_api_token}" == *[[:space:]]* ]]; then
echo "OpsProof requires the Jeannie API token through LAB_OPSPROOF_JEANNIE_TOKEN, JEANNIE_SERVER_TOKEN, or ${jeannie_api_env}." >&2
return 1
fi
for required in curl docker git npm openssl sha256sum stat systemctl tar; do
if ! command -v "${required}" >/dev/null 2>&1; then
echo "OpsProof deployment requires ${required} on Debian." >&2
return 1
fi
done
if [[ ! -s "${overlay_dir}/resources/js/pages/Welcome.tsx" ]]; then
echo "OpsProof UI overlay is missing from ${overlay_dir}." >&2
return 1
fi
if ! node_major="$(node --version 2>/dev/null | sed -E 's/^v([0-9]+).*/\1/')" ||
! [[ "${node_major}" =~ ^[0-9]+$ ]] || ((node_major < 22)); then
echo "OpsProof requires Node.js 22 or newer on Debian." >&2
return 1
fi
sudo install -d -o "${service_user}" -g "${service_user}" -m 0750 \
"${install_dir}" "${install_dir}/releases" "${install_dir}/toolchains"
if [[ -s "${oidc_env}" ]]; then
oidc_secret="$(sed -n 's/^OPSPROOF_DEX_CLIENT_SECRET=//p' "${oidc_env}" | head -n 1)"
fi
if ! [[ "${oidc_secret}" =~ ^[[:xdigit:]]{64}$ ]]; then
oidc_secret="$(openssl rand -hex 32)"
fi
umask 077
printf '%s\n' \
"OPSPROOF_PUBLIC_URL=${public_url%/}" \
"OPSPROOF_DEX_CLIENT_SECRET=${oidc_secret}" >"${oidc_env}"
chmod 0600 "${oidc_env}"
# Dex owns the OAuth client registry. Re-render it from the committed
# encrypted source plus this private generated client secret.
deploy_dex
sudo install -d -m 0700 "${install_dir}/postgres"
if ! sudo docker image inspect "${postgres_image}" >/dev/null 2>&1; then
sudo docker pull "${postgres_image}"
fi
postgres_uid="$(sudo docker run --rm --entrypoint id "${postgres_image}" -u postgres)"
postgres_gid="$(sudo docker run --rm --entrypoint id "${postgres_image}" -g postgres)"
if ! [[ "${postgres_uid}" =~ ^[0-9]+$ && "${postgres_gid}" =~ ^[0-9]+$ ]]; then
echo "Could not resolve the PostgreSQL user identity from ${postgres_image}." >&2
return 1
fi
if [[ "$(stat -c '%u:%g' "${install_dir}/postgres")" != "${postgres_uid}:${postgres_gid}" ]]; then
if sudo docker container inspect "${postgres_container}" >/dev/null 2>&1; then
sudo docker stop "${postgres_container}" >/dev/null
fi
sudo chown -R "${postgres_uid}:${postgres_gid}" "${install_dir}/postgres"
fi
sudo chmod 0700 "${install_dir}/postgres"
if [[ -s "${database_env}" ]]; then
postgres_password="$(sed -n 's/^POSTGRES_PASSWORD=//p' "${database_env}" | head -n 1)"
fi
if ! [[ "${postgres_password}" =~ ^[[:xdigit:]]{64}$ ]]; then
postgres_password="$(openssl rand -hex 32)"
fi
umask 077
printf '%s\n' \
"POSTGRES_DB=${postgres_db}" \
"POSTGRES_USER=${postgres_user}" \
"POSTGRES_PASSWORD=${postgres_password}" >"${database_env}"
chmod 0600 "${database_env}"
database_url="postgres://${postgres_user}:${postgres_password}@127.0.0.1:${postgres_port}/${postgres_db}?sslmode=disable"
cat >"${install_dir}/compose.yaml" <<COMPOSE_EOF
services:
database:
image: ${postgres_image}
container_name: ${postgres_container}
restart: unless-stopped
env_file:
- .database.env
ports:
- "127.0.0.1:${postgres_port}:5432"
volumes:
- ./postgres:/var/lib/postgresql
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${postgres_user} -d ${postgres_db}"]
interval: 5s
timeout: 3s
retries: 20
COMPOSE_EOF
(cd "${install_dir}" && sudo docker compose --env-file "${database_env}" up -d database)
elapsed=0
until [[ "$(sudo docker inspect --format '{{.State.Health.Status}}' "${postgres_container}" 2>/dev/null)" == "healthy" ]]; do
if ((elapsed >= 120)); then
echo "Timed out waiting for the OpsProof PostgreSQL service." >&2
(cd "${install_dir}" && sudo docker compose ps && sudo docker compose logs --tail=120 database) >&2 || true
return 1
fi
sleep 3
elapsed=$((elapsed + 3))
done
if [[ ! -x "${toolchain_dir}/bin/go" ]]; then
archive="$(mktemp "${install_dir}/go${go_version}.XXXXXX.tar.gz")"
curl -fsSL --retry 3 --output "${archive}" \
"https://go.dev/dl/go${go_version}.linux-amd64.tar.gz"
printf '%s %s\n' "${go_sha256}" "${archive}" | sha256sum --check --status || {
rm -f "${archive}"
echo "Downloaded Go ${go_version} archive failed checksum validation." >&2
return 1
}
build_dir="$(mktemp -d "${install_dir}/go-toolchain.XXXXXX")"
tar -xzf "${archive}" -C "${build_dir}"
mv "${build_dir}/go" "${toolchain_dir}"
rm -rf "${build_dir}" "${archive}"
build_dir=""
fi
build_dir="$(mktemp -d "${install_dir}/release.XXXXXX")"
git clone --quiet --filter=blob:none --no-checkout "${starter_repo}" "${build_dir}"
git -C "${build_dir}" checkout --quiet --detach "${starter_commit}"
if [[ "$(git -C "${build_dir}" rev-parse HEAD)" != "${starter_commit}" ]]; then
echo "Laravel Go starter checkout does not match the pinned commit." >&2
return 1
fi
cp -a "${overlay_dir}/." "${build_dir}/"
(
cd "${build_dir}"
npm ci
# The Laravel Go starter owns the formatter version. Normalize the
# tracked overlay inside the disposable build tree before enforcing it.
npm run check:fix
npm run check
npm run build
DATABASE_URL="${database_url}" PATH="${toolchain_dir}/bin:${PATH}" GOTOOLCHAIN=local go test ./...
PATH="${toolchain_dir}/bin:${PATH}" GOTOOLCHAIN=local go build -trimpath -o opsproof .
)
rm -rf "${release_dir}"
mv "${build_dir}" "${release_dir}"
build_dir=""
ln -sfn "${release_dir}" "${install_dir}/current"
if [[ -s "${install_dir}/.env" ]]; then
app_key="$(sed -n 's/^APP_KEY=//p' "${install_dir}/.env" | head -n 1)"
fi
if [[ "${app_key}" != base64:* ]]; then
app_key="base64:$(openssl rand -base64 32 | tr -d '\n')"
fi
umask 077
printf '%s\n' \
"APP_NAME=OpsProof" \
"APP_ENV=production" \
"APP_KEY=${app_key}" \
"APP_DEBUG=false" \
"APP_URL=${public_url%/}" \
"SERVER_HOST=${bind_ip}" \
"SERVER_PORT=${http_port}" \
"DATABASE_URL=${database_url}" \
"OPSPROOF_JEANNIE_URL=${jeannie_api_url}" \
"OPSPROOF_JEANNIE_TOKEN=${jeannie_api_token}" \
"OPSPROOF_DEX_ISSUER=$(dex_public_url | sed 's:/*$::')" \
"OPSPROOF_DEX_CLIENT_SECRET=${oidc_secret}" \
"OPSPROOF_DEX_REDIRECT_URL=${public_url%/}/auth/dex/callback" \
"OPSPROOF_OPERATOR_EMAILS=${operator_emails}" \
"SESSION_DRIVER=memory" \
"CACHE_STORE=memory" \
"QUEUE_CONNECTION=sync" \
"LOG_CHANNEL=stderr" \
"LOG_LEVEL=info" >"${install_dir}/.env"
chmod 0600 "${install_dir}/.env"
sudo -u "${service_user}" env \
APP_ENV=production \
APP_KEY="${app_key}" \
DATABASE_URL="${database_url}" \
CACHE_STORE=memory \
SESSION_DRIVER=memory \
QUEUE_CONNECTION=sync \
"${release_dir}/opsproof" migrate --force
sudo tee /etc/systemd/system/opsproof.service >/dev/null <<UNIT_EOF
[Unit]
Description=OpsProof evidence-first operations UI
After=network-online.target docker.service jeannie-server.service
Wants=network-online.target docker.service
[Service]
Type=simple
User=${service_user}
Group=${service_user}
WorkingDirectory=${install_dir}/current
EnvironmentFile=${install_dir}/.env
ExecStart=${install_dir}/current/opsproof
Restart=on-failure
RestartSec=5s
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=${install_dir}/current/storage
[Install]
WantedBy=multi-user.target
UNIT_EOF
sudo systemctl daemon-reload
sudo systemctl enable opsproof.service
sudo systemctl restart opsproof.service
until curl -fsS --connect-timeout 3 "http://${health_ip}:${http_port}/up" >/dev/null; do
if ((elapsed >= 90)); then
echo "Timed out waiting for OpsProof on http://${health_ip}:${http_port}/up" >&2
sudo systemctl status opsproof.service --no-pager >&2 || true
sudo journalctl -u opsproof.service -n 120 --no-pager >&2 || true
return 1
fi
sleep 3
elapsed=$((elapsed + 3))
done
echo "OpsProof Laravel Go shell and PostgreSQL service are healthy at http://${bind_ip}:${http_port}/."
}
deploy_matrix() {
local mode="${LAB_MATRIX_DEPLOY:-true}"
local install_dir="${LAB_MATRIX_INSTALL_DIR:-/home/jv/matrix-server}"
local image=""
local container_name=""
local http_port=""
local ssh_port=""
local domain=""
local install_docker="false"
local source_dir="${REPO_ROOT}/infra/matrix-server"
local value_name
local value
require_debian_server "deploy-matrix"
if disabled_value "${mode}"; then
return 0
fi
for value_name in install_dir; do
value="${!value_name}"
if [[ "${value}" == *$'\n'* ]]; then
echo "${value_name} cannot contain a newline." >&2
exit 1
fi
done
if [[ ! -s "${source_dir}/docker-compose.yml" || ! -s "${source_dir}/homeserver.yaml.tpl" || ! -s "${source_dir}/bootstrap.sh" ]]; then
echo "Missing Matrix source files in ${source_dir}" >&2
exit 1
fi
echo "Deploying Matrix stack on the Debian host at ${install_dir}..."
ensure_local_docker_compose "MATRIX" "${install_docker}"
repair_local_docker_iptables
sudo mkdir -p "${install_dir}"
sudo cp "${source_dir}/docker-compose.yml" "${install_dir}/docker-compose.yml"
sudo cp "${source_dir}/homeserver.yaml.tpl" "${install_dir}/homeserver.yaml.tpl"
sudo cp "${source_dir}/log_config.yaml" "${install_dir}/log_config.yaml"
sudo cp "${source_dir}/element-config/config.json" "${install_dir}/element-config/config.json" 2>/dev/null || {
sudo mkdir -p "${install_dir}/element-config"
sudo cp "${source_dir}/element-config/config.json" "${install_dir}/element-config/config.json"
}
sudo cp "${source_dir}/bootstrap.sh" "${install_dir}/bootstrap.sh"
sudo chmod +x "${install_dir}/bootstrap.sh"
# Secrets come from the SOPS-encrypted repo file, decrypted at deploy time.
# (Env vars override the file, for manual/ops overrides.)
if ! sops_load_secrets "${REPO_ROOT}/infra/matrix-server/matrix.secret.yaml"; then
exit 1
fi
if [[ -z "${MATRIX_POSTGRES_PASSWORD:-}" || -z "${MATRIX_REGISTRATION_SHARED_SECRET:-}" ]]; then
echo "MATRIX_POSTGRES_PASSWORD and MATRIX_REGISTRATION_SHARED_SECRET missing after decrypt." >&2
exit 1
fi
local matrix_server_name="${LAB_MATRIX_SERVER_NAME:-matrix.lab2025.duckdns.org}"
local matrix_synapse_port="${LAB_MATRIX_SYNAPSE_PORT:-8008}"
local matrix_element_port="${LAB_MATRIX_ELEMENT_PORT:-8081}"
local postgres_db="${LAB_MATRIX_POSTGRES_DB:-synapse}"
local postgres_user="${LAB_MATRIX_POSTGRES_USER:-synapse}"
sudo tee "${install_dir}/.env" >/dev/null <<ENV_EOT
MATRIX_SERVER_NAME=${matrix_server_name}
MATRIX_SYNAPSE_PORT=${matrix_synapse_port}
MATRIX_ELEMENT_PORT=${matrix_element_port}
MATRIX_SYNAPSE_CONTAINER_NAME=${LAB_MATRIX_SYNAPSE_CONTAINER_NAME:-matrix-synapse}
MATRIX_POSTGRES_CONTAINER_NAME=${LAB_MATRIX_POSTGRES_CONTAINER_NAME:-matrix-postgres}
MATRIX_ELEMENT_CONTAINER_NAME=${LAB_MATRIX_ELEMENT_CONTAINER_NAME:-matrix-element}
MATRIX_POSTGRES_DB=${postgres_db}
MATRIX_POSTGRES_USER=${postgres_user}
MATRIX_POSTGRES_PASSWORD=${MATRIX_POSTGRES_PASSWORD}
MATRIX_REGISTRATION_SHARED_SECRET=${MATRIX_REGISTRATION_SHARED_SECRET}
MATRIX_MACAROON_SECRET_KEY=${MATRIX_MACAROON_SECRET_KEY:-${MATRIX_REGISTRATION_SHARED_SECRET}}
MATRIX_FORM_SECRET=${MATRIX_FORM_SECRET:-${MATRIX_REGISTRATION_SHARED_SECRET}}
ENV_EOT
# Pull + render + chown + up. bootstrap.sh is the single source of truth.
# sudo the docker compose commands; data dirs are chown'd inside bootstrap.
(
cd "${install_dir}"
sudo docker compose --env-file "${install_dir}/.env" -f "${install_dir}/docker-compose.yml" pull
sudo MATRIX_ENV_FILE="${install_dir}/.env" bash "${install_dir}/bootstrap.sh"
)
echo "Matrix stack is reachable at http://127.0.0.1:${matrix_synapse_port}/ and Element at http://127.0.0.1:${matrix_element_port}/."
}
deploy_omniroute() {
local mode="${LAB_OMNIROUTE_DEPLOY:-true}"
local install_dir="${LAB_OMNIROUTE_INSTALL_DIR:-/home/jv/homelab-omniroute}"
local install_docker="false"
local source_dir="${REPO_ROOT}/infra/omniroute"
require_debian_server "deploy-omniroute"
if disabled_value "${mode}"; then
return 0
fi
if [[ ! -s "${source_dir}/docker-compose.yml" || ! -s "${source_dir}/bootstrap.sh" ]]; then
echo "Missing OmniRoute source files in ${source_dir}" >&2
exit 1
fi
echo "Deploying OmniRoute LLM gateway on the Debian host at ${install_dir}..."
ensure_local_docker_compose "OMNIROUTE" "${install_docker}"
repair_local_docker_iptables
sudo mkdir -p "${install_dir}"
sudo cp "${source_dir}/docker-compose.yml" "${install_dir}/docker-compose.yml"
sudo cp "${source_dir}/bootstrap.sh" "${install_dir}/bootstrap.sh"
sudo chmod +x "${install_dir}/bootstrap.sh"
sudo tee "${install_dir}/.env" >/dev/null <<ENV_EOT
OMNIROUTE_IMAGE=${LAB_OMNIROUTE_IMAGE:-diegosouzapw/omniroute:latest}
OMNIROUTE_CONTAINER_NAME=${LAB_OMNIROUTE_CONTAINER_NAME:-omniroute}
OMNIROUTE_PORT=${LAB_OMNIROUTE_PORT:-20128}
ENV_EOT
(
cd "${install_dir}"
sudo docker compose pull
sudo bash "${install_dir}/bootstrap.sh"
)
echo "OmniRoute is reachable at http://127.0.0.1:${LAB_OMNIROUTE_PORT:-20128}."
}
deploy_ai_stack() {
local mode="${LAB_AI_STACK_DEPLOY:-true}"
local install_dir="${LAB_AI_STACK_INSTALL_DIR:-/data/homelab-ai-stack}"
local install_docker="${LAB_AI_STACK_INSTALL_DOCKER:-false}"
local source_dir="${REPO_ROOT}/infra/ai-stack"
local port="${LAB_OMNIROUTE_PORT:-20128}"
local container_name="${LAB_OMNIROUTE_CONTAINER_NAME:-omniroute}"
local existing_workdir
local models_status
require_debian_server "deploy-ai-stack"
if disabled_value "${mode}"; then
return 0
fi
if [[ ! -s "${source_dir}/docker-compose.yml" || ! -s "${source_dir}/seed-secrets.sh" || ! -s "${source_dir}/bootstrap-omniroute.sh" ]]; then
echo "Missing AI stack source files in ${source_dir}" >&2
exit 1
fi
echo "Deploying Debian-hosted AI stack at ${install_dir}..."
echo "Containerized: OmniRoute gateway. Bare metal: Ollama, goose, holmes, hermes, Jeannie doctors."
ensure_local_docker_compose "AI_STACK" "${install_docker}"
repair_local_docker_iptables
sudo install -d -m 0750 -o "$(id -u)" -g "$(id -g)" "${install_dir}"
install -m 0644 "${source_dir}/docker-compose.yml" "${install_dir}/docker-compose.yml"
install -m 0755 "${source_dir}/seed-secrets.sh" "${install_dir}/seed-secrets.sh"
install -m 0755 "${source_dir}/bootstrap-omniroute.sh" "${install_dir}/bootstrap-omniroute.sh"
install -m 0644 "${source_dir}/README.md" "${install_dir}/README.md"
LAB_AI_STACK_INSTALL_DIR="${install_dir}" "${install_dir}/seed-secrets.sh"
if sudo docker ps -a --format '{{.Names}}' | grep -qx "${container_name}"; then
existing_workdir="$(sudo docker inspect -f '{{ index .Config.Labels "com.docker.compose.project.working_dir" }}' "${container_name}" 2>/dev/null || true)"
if [[ -n "${existing_workdir}" && "${existing_workdir}" != "${install_dir}" ]]; then
echo "Migrating existing ${container_name} container from ${existing_workdir} to ${install_dir}..."
sudo docker stop "${container_name}" >/dev/null 2>&1 || true
sudo docker rm "${container_name}" >/dev/null 2>&1 || true
fi
fi
(
cd "${install_dir}"
sudo docker compose --env-file "${install_dir}/.env" pull
sudo docker compose --env-file "${install_dir}/.env" up -d --remove-orphans --force-recreate omniroute
sudo docker compose --env-file "${install_dir}/.env" ps
)
local bootstrap_env=(
"LAB_AI_STACK_INSTALL_DIR=${install_dir}"
"LAB_OMNIROUTE_PORT=${port}"
)
if [[ ${LAB_AI_STACK_OPENROUTER_MODELS+x} ]]; then
bootstrap_env+=("LAB_AI_STACK_OPENROUTER_MODELS=${LAB_AI_STACK_OPENROUTER_MODELS}")
fi
if [[ ${LAB_AI_STACK_NVIDIA_MODELS+x} ]]; then
bootstrap_env+=("LAB_AI_STACK_NVIDIA_MODELS=${LAB_AI_STACK_NVIDIA_MODELS}")
fi
if [[ ${LAB_AI_STACK_ENABLE_NVIDIA_DISCOVERY+x} ]]; then
bootstrap_env+=("LAB_AI_STACK_ENABLE_NVIDIA_DISCOVERY=${LAB_AI_STACK_ENABLE_NVIDIA_DISCOVERY}")
fi
if [[ ${LAB_AI_STACK_ENABLE_NO_AUTH_PROVIDERS+x} ]]; then
bootstrap_env+=("LAB_AI_STACK_ENABLE_NO_AUTH_PROVIDERS=${LAB_AI_STACK_ENABLE_NO_AUTH_PROVIDERS}")
fi
if [[ ${LAB_AI_STACK_MODEL_VALIDATE_ATTEMPTS+x} ]]; then
bootstrap_env+=("LAB_AI_STACK_MODEL_VALIDATE_ATTEMPTS=${LAB_AI_STACK_MODEL_VALIDATE_ATTEMPTS}")
fi
if [[ ${LAB_AI_STACK_MODEL_VALIDATE_TIMEOUT_SECONDS+x} ]]; then
bootstrap_env+=("LAB_AI_STACK_MODEL_VALIDATE_TIMEOUT_SECONDS=${LAB_AI_STACK_MODEL_VALIDATE_TIMEOUT_SECONDS}")
fi
if [[ ${LAB_AI_STACK_MODEL_VALIDATE_MAX_TOKENS+x} ]]; then
bootstrap_env+=("LAB_AI_STACK_MODEL_VALIDATE_MAX_TOKENS=${LAB_AI_STACK_MODEL_VALIDATE_MAX_TOKENS}")
fi
if [[ ${LAB_AI_STACK_FAST_MODEL_TARGET+x} ]]; then
bootstrap_env+=("LAB_AI_STACK_FAST_MODEL_TARGET=${LAB_AI_STACK_FAST_MODEL_TARGET}")
fi
if [[ ${LAB_AI_STACK_SMART_MODEL_TARGET+x} ]]; then
bootstrap_env+=("LAB_AI_STACK_SMART_MODEL_TARGET=${LAB_AI_STACK_SMART_MODEL_TARGET}")
fi
env "${bootstrap_env[@]}" "${install_dir}/bootstrap-omniroute.sh"
models_status="$(curl -sS -o /dev/null -w '%{http_code}' --connect-timeout 2 --max-time 5 "http://127.0.0.1:${port}/v1/models" 2>/dev/null || true)"
if [[ "${models_status}" == "200" ]]; then
echo "AI gateway OpenAI-compatible endpoint is reachable at http://127.0.0.1:${port}/v1."
elif [[ "${models_status}" == "401" ]]; then
echo "AI gateway OpenAI-compatible endpoint is reachable and auth-protected at http://127.0.0.1:${port}/v1."
else
echo "AI gateway container started, but /v1/models returned HTTP ${models_status:-000}; check logs with:" >&2
echo " cd ${install_dir} && sudo docker compose --env-file .env logs --tail=120" >&2
fi
if curl -fsS --connect-timeout 2 --max-time 5 "http://127.0.0.1:11434/api/tags" >/dev/null 2>&1; then
echo "Bare-metal Ollama is reachable at http://127.0.0.1:11434."
else
echo "Ollama is not reachable locally; run ./jeannie ollama-setup if local model fallback is required." >&2
fi
}
deploy_ai_tools() {
local mode="${LAB_AI_TOOLS_DEPLOY:-true}"
local install_dir="${LAB_AI_STACK_INSTALL_DIR:-/data/homelab-ai-stack}"
local model_routes_file="${LAB_AI_STACK_MODEL_ROUTES_FILE:-${install_dir}/models.env}"
local tools_env_file="${LAB_AI_STACK_TOOLS_ENV_FILE:-${install_dir}/ai-tools.env}"
local holmes_config_file="${LAB_HOLMES_CONFIG_FILE:-${install_dir}/holmes-config.yaml}"
local bin_dir="${LAB_AI_TOOLS_BIN_DIR:-/home/jv/.local/bin}"
local port="${LAB_OMNIROUTE_PORT:-20128}"
local endpoint="${LAB_AI_TOOLS_GATEWAY_URL:-http://127.0.0.1:${port}/v1}"
local api_key="${LAB_AI_GATEWAY_API_KEY:-${OMNIROUTE_API_KEY:-sk_omniroute}}"
local fast_model="${LAB_AI_TOOLS_FAST_MODEL:-agent-fast-free}"
local smart_model="${LAB_AI_TOOLS_SMART_MODEL:-agent-smart-free}"
local missing_tools=()
local tool
local install_var
local install_cmd
require_debian_server "deploy-ai-tools"
if disabled_value "${mode}"; then
return 0
fi
if [[ -s "${model_routes_file}" ]]; then
# shellcheck disable=SC1090
. "${model_routes_file}"
if [[ "${AI_STACK_MODEL_VALIDATION_STATUS:-ok}" != "ok" ]]; then
echo "AI stack model routes failed runtime validation; rerun ./jeannie deploy-ai-stack after fixing provider quota/config." >&2
exit 1
fi
fast_model="${LAB_AI_TOOLS_FAST_MODEL:-${AI_STACK_AGENT_FAST_MODEL:-${fast_model}}}"
smart_model="${LAB_AI_TOOLS_SMART_MODEL:-${AI_STACK_AGENT_SMART_MODEL:-${smart_model}}}"
else
echo "AI stack model routes are missing at ${model_routes_file}; run ./jeannie deploy-ai-stack first." >&2
fi
if [[ -z "${fast_model}" || -z "${smart_model}" ]]; then
echo "AI stack model routes are empty; run ./jeannie deploy-ai-stack and ensure at least one OmniRoute model validates." >&2
exit 1
fi
echo "Configuring bare-metal AI tools for OmniRoute at ${endpoint}..."
install -d -m 0755 "${bin_dir}"
sudo install -d -m 0750 -o "$(id -u)" -g "$(id -g)" "${install_dir}"
for tool in goose holmes hermes; do
if command -v "${tool}" >/dev/null 2>&1; then
echo "${tool}: present at $(command -v "${tool}")"
continue
fi
install_var="LAB_$(printf '%s' "${tool}" | tr '[:lower:]' '[:upper:]')_INSTALL_COMMAND"
install_cmd="${!install_var:-}"
if [[ -n "${install_cmd}" ]]; then
echo "${tool}: installing with ${install_var}..."
bash -lc "${install_cmd}"
fi
if ! command -v "${tool}" >/dev/null 2>&1; then
missing_tools+=("${tool}")
else
echo "${tool}: installed at $(command -v "${tool}")"
fi
done
if ((${#missing_tools[@]} > 0)); then
echo "Missing AI tool(s): ${missing_tools[*]}" >&2
echo "Set LAB_GOOSE_INSTALL_COMMAND, LAB_HOLMES_INSTALL_COMMAND, or LAB_HERMES_INSTALL_COMMAND to make fresh installs fully automated." >&2
echo "Existing Debian hosts with these tools already installed will pass this phase without manual work." >&2
exit 1
fi
sudo tee "${tools_env_file}" >/dev/null <<ENV_EOT
# Generated by jeannie deploy-ai-tools. Do not commit.
OPENAI_BASE_URL=${endpoint}
OPENAI_API_BASE=${endpoint}
OPENAI_API_KEY=${api_key}
OMNIROUTE_API_KEY=${api_key}
LAB_AI_GATEWAY_PROVIDER=omniroute
LAB_AI_GATEWAY_URL=${endpoint}
LAB_AI_GATEWAY_API_KEY=${api_key}
LAB_AI_GATEWAY_MODEL=${smart_model}
AI_STACK_AGENT_FAST_MODEL=${fast_model}
AI_STACK_AGENT_SMART_MODEL=${smart_model}
HOLMES_MODEL=openai/${fast_model}
HOLMES_FAST_MODEL=openai/${fast_model}
HERMES_OPENAI_BASE_URL=${endpoint}
HERMES_OMNIROUTE_API_KEY=${api_key}
GOOSE_PROVIDER=openai
GOOSE_MODEL=${smart_model}
ENV_EOT
sudo chown "$(id -u):$(id -g)" "${tools_env_file}"
sudo chmod 600 "${tools_env_file}"
sudo tee "${holmes_config_file}" >/dev/null <<'ENV_EOT'
{}
ENV_EOT
sudo chown "$(id -u):$(id -g)" "${holmes_config_file}"
sudo chmod 600 "${holmes_config_file}"
for tool in goose holmes hermes; do
local wrapper="${bin_dir}/jeannie-${tool}"
tee "${wrapper}" >/dev/null <<WRAPPER_EOT
#!/usr/bin/env bash
set -euo pipefail
if [[ -s "${tools_env_file}" ]]; then
set -a
# shellcheck disable=SC1091
. "${tools_env_file}"
set +a
fi
exec ${tool} "\$@"
WRAPPER_EOT
chmod 0755 "${wrapper}"
done
echo "AI tools env ready: ${tools_env_file}"
echo "Holmes config ready: ${holmes_config_file}"
echo "Wrappers ready: ${bin_dir}/jeannie-goose, ${bin_dir}/jeannie-holmes, ${bin_dir}/jeannie-hermes"
}
deploy_hermes() {
local mode="${LAB_HERMES_DEPLOY:-true}"
local hermes_home="${LAB_HERMES_HOME:-/home/jv/.hermes}"
local install_dir="${LAB_HERMES_INSTALL_DIR:-/home/jv/.hermes/hermes-agent}"
local uv_bin="${LAB_HERMES_UV_BIN:-/home/jv/.hermes/bin/uv}"
local install_docker="${LAB_HERMES_INSTALL_DOCKER:-false}"
local ai_stack_dir="${LAB_AI_STACK_INSTALL_DIR:-/data/homelab-ai-stack}"
local ai_tools_env_file="${LAB_AI_STACK_TOOLS_ENV_FILE:-${ai_stack_dir}/ai-tools.env}"
local ai_model_routes_file="${LAB_AI_STACK_MODEL_ROUTES_FILE:-${ai_stack_dir}/models.env}"
local hermes_openai_base_url="${HERMES_OPENAI_BASE_URL:-http://localhost:${LAB_OMNIROUTE_PORT:-20128}/v1}"
local hermes_omniroute_api_key="${HERMES_OMNIROUTE_API_KEY:-${LAB_AI_GATEWAY_API_KEY:-sk_omniroute}}"
local hermes_model="${HERMES_MODEL:-agent-smart-free}"
local value_name
local value
require_debian_server "deploy-hermes"
if disabled_value "${mode}"; then
return 0
fi
for value_name in hermes_home install_dir uv_bin; do
value="${!value_name}"
if [[ "${value}" == *$'\n'* ]]; then
echo "${value_name} cannot contain a newline." >&2
exit 1
fi
done
echo "Deploying Hermes agent on the Debian host at ${install_dir}..."
ensure_local_docker_compose "HERMES" "${install_docker}"
# Install uv if missing.
if [[ ! -x "${uv_bin}" ]]; then
mkdir -p "$(dirname "${uv_bin}")"
echo "Installing uv..."
curl -LsSf https://astral.sh/uv/install.sh | bash
# uv installs to ~/.local/bin; copy/alias into HERMES bin if that path differs.
if command -v uv >/dev/null 2>&1 && [[ ! -x "${uv_bin}" ]]; then
cp "$(command -v uv)" "${uv_bin}"
fi
fi
# Install Hermes via its official installer (git method, managed venv layout).
if [[ ! -x "${hermes_home}/hermes-agent/venv/bin/python" ]]; then
echo "Installing Hermes agent..."
curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash
fi
# Ensure the Matrix platform dependencies (E2EE) are present in the venv.
if [[ -x "${uv_bin}" && -f "${install_dir}/pyproject.toml" ]]; then
cd "${install_dir}"
"${uv_bin}" pip install 'mautrix[encryption]' -p venv/bin/python
fi
# Secret env for the gateway (.env under HERMES_HOME, mode 600, never committed).
# Pull the hermes secrets from the SOPS-encrypted repo file; env vars override.
if ! sops_load_secrets "${REPO_ROOT}/infra/hermes.secret.yaml"; then
echo "WARNING: could not load hermes secrets; MATRIX_PASSWORD may be blank." >&2
fi
if [[ -s "${ai_model_routes_file}" ]]; then
# shellcheck disable=SC1090
. "${ai_model_routes_file}"
hermes_model="${HERMES_MODEL:-${AI_STACK_AGENT_SMART_MODEL:-${hermes_model}}}"
fi
if [[ -s "${ai_tools_env_file}" ]]; then
# shellcheck disable=SC1090
. "${ai_tools_env_file}"
hermes_openai_base_url="${HERMES_OPENAI_BASE_URL:-${hermes_openai_base_url}}"
hermes_omniroute_api_key="${HERMES_OMNIROUTE_API_KEY:-${OPENAI_API_KEY:-${hermes_omniroute_api_key}}}"
hermes_model="${HERMES_MODEL:-${AI_STACK_AGENT_SMART_MODEL:-${hermes_model}}}"
fi
local secrets_file="${hermes_home}/.env"
sudo install -d -m 0700 -o "$(id -u)" -g "$(id -g)" "${hermes_home}"
if [[ -f "${secrets_file}" ]]; then
sudo cp "${secrets_file}" "${secrets_file}.bak-pre-jeannie"
fi
sudo tee "${secrets_file}" >/dev/null <<ENV_EOT
OPENAI_BASE_URL=${hermes_openai_base_url}
OPENAI_API_KEY=${hermes_omniroute_api_key}
HERMES_MODEL=${hermes_model}
HERMES_CUSTOM_LOCALHOST_${LAB_OMNIROUTE_PORT:-20128}_API_KEY=${hermes_omniroute_api_key}
MATRIX_HOMESERVER=https://${LAB_MATRIX_SERVER_NAME:-matrix.lab2025.duckdns.org}
MATRIX_USER_ID=${HERMES_MATRIX_USER_ID:-@hermes:matrix.lab2025.duckdns.org}
MATRIX_PASSWORD=${MATRIX_BOT_PASSWORD:-}
MATRIX_ALLOWED_USERS=${HERMES_MATRIX_ALLOWED_USERS:-@jv:matrix.lab2025.duckdns.org}
MATRIX_E2EE_MODE=required
ENV_EOT
sudo chmod 600 "${secrets_file}"
# Create the Matrix bot account (idempotent) if the homeserver is up.
if command -v docker >/dev/null 2>&1 && docker ps --format '{{.Names}}' 2>/dev/null | grep -q '^matrix-synapse$'; then
if [[ -n "${MATRIX_BOT_PASSWORD:-}" ]]; then
if ! docker exec matrix-synapse register_new_matrix_user -c /data/homeserver.yaml \
-u hermes -p "${MATRIX_BOT_PASSWORD}" --no-admin >/dev/null 2>&1; then
echo "Hermes bot account already exists (expected on re-run) or auto-registration skipped." >&2
else
echo "Hermes Matrix bot account ready."
fi
else
echo "MATRIX_BOT_PASSWORD not set; skipping Hermes bot account registration (needed only on fresh install)." >&2
fi
fi
# Install the gateway systemd user service headlessly. Hermes may prompt to
# start the gateway interactively; Jeannie starts/enables it deterministically
# below, so answer no to keep CI/CD runs non-interactive.
printf 'n\n' | "${hermes_home}/hermes-agent/venv/bin/python" "${hermes_home}/hermes-agent/hermes" gateway install
systemctl --user daemon-reload
systemctl --user enable --now hermes-gateway 2>/dev/null || true
LAB_HERMES_HOME="${hermes_home}" LAB_HERMES_INSTALL_DIR="${install_dir}" \
bash "${REPO_ROOT}/scripts/hermes-connect"
echo "Hermes agent deployed. Run 'hermes' to configure the model, or check gateway logs at ${hermes_home}/logs/gateway.log."
}
deploy_rpi_services() {
local mode="${LAB_RPI_SERVICES_DEPLOY:-true}"
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 data_dir="${LAB_RPI_SERVICES_DATA_DIR:-${install_dir}/data}"
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 stop_legacy_pihole="${LAB_RPI_STOP_LEGACY_PIHOLE:-true}"
local install_docker="${LAB_RPI_INSTALL_DOCKER:-false}"
local pihole_webpassword="${PIHOLE_WEBPASSWORD:-}"
local source_dir="${REPO_ROOT}/infra/rpi-services"
local value_name
local value
require_debian_server "rpi-services"
if disabled_value "${mode}"; then
return 0
fi
if [[ ! -d "${source_dir}" ]]; then
echo "Missing ${source_dir}" >&2
exit 1
fi
for value_name in install_dir data_dir docker_nvme_root docker_fallback_root stop_legacy_pihole install_docker pihole_webpassword; do
value="${!value_name}"
if [[ "${value}" == *"'"* ]]; then
echo "${value_name} cannot contain a single quote." >&2
exit 1
fi
done
echo "Deploying RPi services on ${rpi_user}@${rpi_host}..."
ssh -i "${rpi_key}" -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new "${rpi_user}@${rpi_host}" "rm -rf /tmp/homelab-rpi-services && mkdir -p /tmp/homelab-rpi-services"
scp -i "${rpi_key}" -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new \
"${source_dir}/docker-compose.yml" \
"${source_dir}/adlists.txt" \
"${source_dir}/local-dns-records.txt" \
"${source_dir}/cname-records.txt" \
"${source_dir}/static-dhcp-hosts.txt" \
"${source_dir}/uptime-kuma-monitors.json" \
"${source_dir}/seed-uptime-kuma.js" \
"${source_dir}/bootstrap.sh" \
"${rpi_user}@${rpi_host}:/tmp/homelab-rpi-services/"
ssh -i "${rpi_key}" -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new "${rpi_user}@${rpi_host}" "
LAB_RPI_SERVICES_INSTALL_DIR='${install_dir}' \
LAB_RPI_SERVICES_DATA_DIR='${data_dir}' \
LAB_RPI_DOCKER_ROOT='${docker_nvme_root}' \
LAB_RPI_DOCKER_NVME_ROOT='${docker_nvme_root}' \
LAB_RPI_DOCKER_FALLBACK_ROOT='${docker_fallback_root}' \
LAB_RPI_STOP_LEGACY_PIHOLE='${stop_legacy_pihole}' \
LAB_RPI_INSTALL_DOCKER='${install_docker}' \
PIHOLE_WEBPASSWORD='${pihole_webpassword}' \
bash /tmp/homelab-rpi-services/bootstrap.sh"
}
gitea_bootstrap_password() {
if command -v openssl >/dev/null 2>&1; then
openssl rand -hex 32
return 0
fi
python3 - <<'PY'
import secrets
print(secrets.token_hex(32))
PY
}
gitea_api_base_url() {
local gitea_host="$1"
local http_port="$2"
local candidate
local api_base_override="${LAB_GITEA_API_BASE_URL:-}"
if [[ -n "${api_base_override}" ]]; then
printf '%s\n' "${api_base_override%/}"
return 0
fi
for candidate in "http://${gitea_host}:${http_port}/api/v1" "http://${gitea_host}:${http_port}/git/api/v1"; do
if curl -fsS "${candidate}/version" >/dev/null 2>&1; then
printf '%s\n' "${candidate}"
return 0
fi
done
echo "Could not reach the Gitea API on ${gitea_host}:${http_port}." >&2
exit 1
}
gitea_repo_exists() {
local api_base="$1"
local auth_user="$2"
local auth_password="$3"
local owner="$4"
local repo_name="$5"
local status
status="$(curl -sS -o /dev/null -w '%{http_code}' -u "${auth_user}:${auth_password}" "${api_base}/repos/${owner}/${repo_name}")"
case "${status}" in
200)
return 0
;;
404)
return 1
;;
401 | 403)
echo "Gitea API authentication failed for ${auth_user} while checking ${owner}/${repo_name}." >&2
exit 1
;;
*)
echo "Unexpected Gitea API response ${status} while checking ${owner}/${repo_name}." >&2
exit 1
;;
esac
}
gitea_branch_exists() {
local api_base="$1"
local auth_user="$2"
local auth_password="$3"
local owner="$4"
local repo_name="$5"
local branch="$6"
local status
status="$(curl -sS -o /dev/null -w '%{http_code}' -u "${auth_user}:${auth_password}" "${api_base}/repos/${owner}/${repo_name}/branches/${branch}")"
case "${status}" in
200)
return 0
;;
404)
return 1
;;
401 | 403)
echo "Gitea API authentication failed for ${auth_user} while checking ${owner}/${repo_name}:${branch}." >&2
exit 1
;;
*)
echo "Unexpected Gitea API response ${status} while checking ${owner}/${repo_name}:${branch}." >&2
exit 1
;;
esac
}
create_gitea_repo() {
local api_base="$1"
local auth_user="$2"
local auth_password="$3"
local repo_name="$4"
local default_branch="$5"
local payload
payload="$(python3 - "${repo_name}" "${default_branch}" <<'PY'
import json
import sys
repo_name, default_branch = sys.argv[1:3]
print(json.dumps({
"name": repo_name,
"private": False,
"auto_init": False,
"default_branch": default_branch,
"description": "Homelab infrastructure configuration",
}))
PY
)"
curl -fsS \
-u "${auth_user}:${auth_password}" \
-H "Content-Type: application/json" \
-X POST \
-d "${payload}" \
"${api_base}/user/repos" >/dev/null
}
gitea_public_key_registered() {
local api_base="$1"
local auth_user="$2"
local auth_password="$3"
local owner="$4"
local repo_name="$5"
local public_key_path="$6"
local repo_keys
local user_keys
user_keys="$(curl -fsS -u "${auth_user}:${auth_password}" "${api_base}/user/keys?limit=100")"
repo_keys="$(curl -fsS -u "${auth_user}:${auth_password}" "${api_base}/repos/${owner}/${repo_name}/keys?limit=100")"
GITEA_PUBLIC_KEY="$(<"${public_key_path}")" \
GITEA_USER_KEYS="${user_keys}" \
GITEA_REPO_KEYS="${repo_keys}" \
python3 - <<'PY'
import json
import os
import sys
public_key = os.environ["GITEA_PUBLIC_KEY"].strip()
for env_name in ("GITEA_USER_KEYS", "GITEA_REPO_KEYS"):
for key in json.loads(os.environ[env_name]) or []:
if key.get("key", "").strip() == public_key:
sys.exit(0)
sys.exit(1)
PY
}
create_gitea_repo_deploy_key() {
local api_base="$1"
local auth_user="$2"
local auth_password="$3"
local owner="$4"
local repo_name="$5"
local title="$6"
local public_key_path="$7"
local read_only="$8"
local payload
payload="$(
GITEA_DEPLOY_KEY_TITLE="${title}" \
GITEA_PUBLIC_KEY="$(<"${public_key_path}")" \
GITEA_DEPLOY_KEY_READ_ONLY="${read_only}" \
python3 - <<'PY'
import json
import os
print(json.dumps({
"title": os.environ["GITEA_DEPLOY_KEY_TITLE"],
"key": os.environ["GITEA_PUBLIC_KEY"].strip(),
"read_only": os.environ["GITEA_DEPLOY_KEY_READ_ONLY"] == "true",
}))
PY
)"
curl -fsS \
-u "${auth_user}:${auth_password}" \
-H "Content-Type: application/json" \
-X POST \
-d "${payload}" \
"${api_base}/repos/${owner}/${repo_name}/keys" >/dev/null
}
ensure_gitea_repo_ssh_access() {
local api_base="$1"
local auth_user="$2"
local auth_password="$3"
local owner="$4"
local repo_name="$5"
local ssh_host="$6"
local ssh_port="$7"
local key_path="$8"
local key_title="$9"
local key_read_only="${10}"
local key_dir
local known_hosts
local public_key_path
local read_only_json="false"
local ssh_repo_url
if [[ "${key_path}" =~ [[:space:]] || "${key_path}" == *"'"* ]]; then
echo "LAB_GITEA_REPO_SSH_KEY_PATH cannot contain whitespace or single quotes." >&2
exit 1
fi
key_dir="$(dirname "${key_path}")"
public_key_path="${key_path}.pub"
mkdir -p "${key_dir}"
chmod 0700 "${key_dir}"
if [[ ! -s "${key_path}" && ! -s "${public_key_path}" ]]; then
ssh-keygen -t ed25519 -N "" -f "${key_path}" -C "${key_title}" >/dev/null
elif [[ -s "${key_path}" && ! -s "${public_key_path}" ]]; then
ssh-keygen -y -f "${key_path}" >"${public_key_path}"
elif [[ ! -s "${key_path}" ]]; then
echo "Public key ${public_key_path} exists, but private key ${key_path} is missing." >&2
exit 1
fi
chmod 0600 "${key_path}"
chmod 0644 "${public_key_path}"
if truthy "${key_read_only}"; then
read_only_json="true"
fi
if gitea_public_key_registered "${api_base}" "${auth_user}" "${auth_password}" "${owner}" "${repo_name}" "${public_key_path}"; then
echo "Gitea already has Debian host SSH key ${public_key_path}."
else
create_gitea_repo_deploy_key "${api_base}" "${auth_user}" "${auth_password}" "${owner}" "${repo_name}" "${key_title}" "${public_key_path}" "${read_only_json}"
echo "Added Debian host SSH key ${public_key_path} to ${owner}/${repo_name}."
fi
known_hosts="${HOME}/.ssh/known_hosts"
touch "${known_hosts}"
chmod 0644 "${known_hosts}"
if ! ssh-keygen -F "[${ssh_host}]:${ssh_port}" -f "${known_hosts}" >/dev/null 2>&1; then
ssh-keyscan -p "${ssh_port}" "${ssh_host}" >>"${known_hosts}" 2>/dev/null
fi
ssh_repo_url="ssh://git@${ssh_host}:${ssh_port}/${owner}/${repo_name}.git"
git -C "${REPO_ROOT}" remote set-url gitea "${ssh_repo_url}" 2>/dev/null ||
git -C "${REPO_ROOT}" remote add gitea "${ssh_repo_url}"
git -C "${REPO_ROOT}" config core.sshCommand "ssh -i ${key_path} -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new"
git -C "${REPO_ROOT}" ls-remote gitea HEAD >/dev/null
echo "Gitea SSH remote: ${ssh_repo_url}"
}
bootstrap_gitea_repo() {
local mode="${LAB_GITEA_REPO_BOOTSTRAP:-true}"
local gitea_host="${LAB_GITEA_HOST:-192.168.100.73}"
local gitea_user="${LAB_GITEA_USER:-jv}"
local gitea_key="${LAB_GITEA_SSH_KEY_PATH:-${LAB_RASPBERRY_SSH_KEY_PATH:-/home/jv/.ssh/id_ed25519}}"
local container_name="${LAB_GITEA_CONTAINER_NAME:-homelab-gitea}"
local http_port="${LAB_GITEA_HTTP_PORT:-3000}"
local ssh_port="${LAB_GITEA_SSH_PORT:-32222}"
local root_url="${LAB_GITEA_ROOT_URL:?LAB_GITEA_ROOT_URL is required from homelab.yml}"
local repo_owner="${LAB_GITEA_REPO_OWNER:-jv}"
local repo_name="${LAB_GITEA_REPO_NAME:-my-homelab-configs}"
local default_branch="${LAB_GITEA_REPO_DEFAULT_BRANCH:-main}"
local bootstrap_user="${LAB_GITEA_BOOTSTRAP_USER:-${repo_owner}}"
local bootstrap_email="${LAB_GITEA_BOOTSTRAP_EMAIL:-${bootstrap_user}@homelab.local}"
local credentials_file="${LAB_GITEA_BOOTSTRAP_CREDENTIALS_FILE:-${HOME}/.config/homelab/gitea-bootstrap.env}"
local bootstrap_password="${LAB_GITEA_BOOTSTRAP_PASSWORD:-}"
local allow_dirty="${LAB_GITEA_BOOTSTRAP_ALLOW_DIRTY:-false}"
local ssh_bootstrap="${LAB_GITEA_REPO_SSH_BOOTSTRAP:-true}"
local ssh_key_path="${LAB_GITEA_REPO_SSH_KEY_PATH:-/home/jv/.ssh/id_ed25519}"
local ssh_key_title="${LAB_GITEA_REPO_DEPLOY_KEY_TITLE:-debian-host-${repo_name}}"
local ssh_key_read_only="${LAB_GITEA_REPO_DEPLOY_KEY_READ_ONLY:-false}"
local api_base
local public_repo_url
local direct_repo_url
local push_url
local askpass
local credentials_dir
local remote_status
local worktree_status
require_debian_server "bootstrap-gitea-repo"
if disabled_value "${mode}"; then
return 0
fi
ensure_python3
for value_name in repo_owner repo_name default_branch bootstrap_user; do
local value="${!value_name}"
if ! [[ "${value}" =~ ^[A-Za-z0-9_.-]+$ ]]; then
echo "${value_name} contains unsupported characters." >&2
exit 1
fi
done
if [[ "${bootstrap_email}" == *"'"* ]]; then
echo "LAB_GITEA_BOOTSTRAP_EMAIL cannot contain a single quote." >&2
exit 1
fi
if ! [[ "${ssh_port}" =~ ^[0-9]+$ ]]; then
echo "LAB_GITEA_SSH_PORT must be numeric." >&2
exit 1
fi
if [[ -z "${bootstrap_password}" && -r "${credentials_file}" ]]; then
# shellcheck disable=SC1090
source "${credentials_file}"
bootstrap_user="${GITEA_BOOTSTRAP_USER:-${bootstrap_user}}"
bootstrap_email="${GITEA_BOOTSTRAP_EMAIL:-${bootstrap_email}}"
bootstrap_password="${GITEA_BOOTSTRAP_PASSWORD:-}"
fi
if [[ -z "${bootstrap_password}" ]]; then
bootstrap_password="$(gitea_bootstrap_password)"
credentials_dir="$(dirname "${credentials_file}")"
mkdir -p "${credentials_dir}"
chmod 0700 "${credentials_dir}"
{
printf "GITEA_BOOTSTRAP_USER='%s'\n" "${bootstrap_user}"
printf "GITEA_BOOTSTRAP_EMAIL='%s'\n" "${bootstrap_email}"
printf "GITEA_BOOTSTRAP_PASSWORD='%s'\n" "${bootstrap_password}"
} > "${credentials_file}"
chmod 0600 "${credentials_file}"
echo "Generated Gitea bootstrap credentials at ${credentials_file}."
fi
for value_name in repo_owner repo_name default_branch bootstrap_user; do
local value="${!value_name}"
if ! [[ "${value}" =~ ^[A-Za-z0-9_.-]+$ ]]; then
echo "${value_name} contains unsupported characters." >&2
exit 1
fi
done
for value_name in bootstrap_email bootstrap_password; do
local value="${!value_name}"
if [[ "${value}" == *"'"* ]]; then
echo "${value_name} cannot contain a single quote." >&2
exit 1
fi
done
echo "Bootstrapping Gitea repository ${repo_owner}/${repo_name}..."
# shellcheck disable=SC2087
ssh -i "${gitea_key}" -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new "${gitea_user}@${gitea_host}" "bash -s" <<EOF
set -euo pipefail
container_name='${container_name}'
bootstrap_user='${bootstrap_user}'
bootstrap_email='${bootstrap_email}'
bootstrap_password='${bootstrap_password}'
if ! sudo docker inspect "\${container_name}" >/dev/null 2>&1; then
echo "Gitea container \${container_name} is not running on ${gitea_host}." >&2
exit 1
fi
for attempt in \$(seq 1 60); do
if curl -fsS http://127.0.0.1:3000/api/v1/version >/dev/null 2>&1 ||
curl -fsS http://127.0.0.1:3000/git/api/v1/version >/dev/null 2>&1; then
break
fi
if [ "\${attempt}" = "60" ]; then
echo "Timed out waiting for Gitea API inside \${container_name}." >&2
exit 1
fi
sleep 2
done
if ! sudo docker exec -u git "\${container_name}" gitea -c /data/gitea/conf/app.ini admin user create \
--username "\${bootstrap_user}" \
--password "\${bootstrap_password}" \
--email "\${bootstrap_email}" \
--admin \
--must-change-password=false >/tmp/homelab-gitea-user-create.log 2>&1; then
if sudo docker exec -u git "\${container_name}" gitea -c /data/gitea/conf/app.ini admin user list | awk -v user="\${bootstrap_user}" 'NR > 1 && \$2 == user { found = 1 } END { exit found ? 0 : 1 }'; then
sudo docker exec -u git "\${container_name}" gitea -c /data/gitea/conf/app.ini admin user change-password \
--username "\${bootstrap_user}" \
--password "\${bootstrap_password}" >/tmp/homelab-gitea-user-password.log 2>&1 || {
cat /tmp/homelab-gitea-user-password.log >&2
exit 1
}
else
cat /tmp/homelab-gitea-user-create.log >&2
exit 1
fi
fi
EOF
api_base="$(gitea_api_base_url "${gitea_host}" "${http_port}")"
if gitea_repo_exists "${api_base}" "${bootstrap_user}" "${bootstrap_password}" "${repo_owner}" "${repo_name}"; then
echo "Gitea repository ${repo_owner}/${repo_name} already exists."
else
if [[ "${repo_owner}" != "${bootstrap_user}" ]]; then
echo "Gitea repository owner ${repo_owner} does not exist yet; only user-owned bootstrap repos are supported." >&2
exit 1
fi
create_gitea_repo "${api_base}" "${bootstrap_user}" "${bootstrap_password}" "${repo_name}" "${default_branch}"
echo "Created Gitea repository ${repo_owner}/${repo_name}."
fi
public_repo_url="${root_url%/}/${repo_owner}/${repo_name}.git"
if [[ "${api_base}" == */git/api/v1 ]]; then
direct_repo_url="http://${gitea_host}:${http_port}/git/${repo_owner}/${repo_name}.git"
else
direct_repo_url="http://${gitea_host}:${http_port}/${repo_owner}/${repo_name}.git"
fi
push_url="${LAB_GITEA_BOOTSTRAP_PUSH_URL:-${direct_repo_url}}"
git -C "${REPO_ROOT}" rev-parse --is-inside-work-tree >/dev/null
git -C "${REPO_ROOT}" remote set-url gitea "${public_repo_url}" 2>/dev/null ||
git -C "${REPO_ROOT}" remote add gitea "${public_repo_url}"
if gitea_branch_exists "${api_base}" "${bootstrap_user}" "${bootstrap_password}" "${repo_owner}" "${repo_name}" "${default_branch}"; then
echo "Gitea branch ${default_branch} already exists; leaving existing history unchanged."
else
worktree_status="$(git -C "${REPO_ROOT}" status --porcelain)"
if [[ -n "${worktree_status}" ]] && ! truthy "${allow_dirty}"; then
echo "Refusing to seed Gitea from a dirty working tree; commit or stash changes first." >&2
echo "Set LAB_GITEA_BOOTSTRAP_ALLOW_DIRTY=true to push committed HEAD anyway." >&2
exit 1
fi
askpass="$(mktemp)"
trap 'rm -f "${askpass}" "${BUILDX_CONFIG}"' EXIT
cat > "${askpass}" <<ASKPASS_EOT
#!/usr/bin/env bash
case "\$1" in
*Username*) printf '%s\n' '${bootstrap_user}' ;;
*Password*) printf '%s\n' '${bootstrap_password}' ;;
*) printf '\n' ;;
esac
ASKPASS_EOT
chmod 0700 "${askpass}"
GIT_ASKPASS="${askpass}" GIT_TERMINAL_PROMPT=0 \
git -C "${REPO_ROOT}" push "${push_url}" "HEAD:refs/heads/${default_branch}"
rm -f "${askpass}"
trap 'rm -f "${BUILDX_CONFIG}"' EXIT
echo "Pushed current HEAD to Gitea branch ${default_branch}."
fi
remote_status="$(git -C "${REPO_ROOT}" remote get-url gitea)"
echo "Gitea remote: ${remote_status}"
if ! disabled_value "${ssh_bootstrap}"; then
ensure_gitea_repo_ssh_access \
"${api_base}" \
"${bootstrap_user}" \
"${bootstrap_password}" \
"${repo_owner}" \
"${repo_name}" \
"${gitea_host}" \
"${ssh_port}" \
"${ssh_key_path}" \
"${ssh_key_title}" \
"${ssh_key_read_only}"
fi
}
install_gitea_backup_timer() {
local gitea_host="${LAB_GITEA_HOST:-192.168.100.73}"
local gitea_user="${LAB_GITEA_USER:-jv}"
local gitea_key="${LAB_GITEA_SSH_KEY_PATH:-${LAB_RASPBERRY_SSH_KEY_PATH:-/home/jv/.ssh/id_ed25519}}"
local gitea_container="${LAB_GITEA_CONTAINER_NAME:-homelab-gitea}"
local backup_dir="${LAB_GITEA_BACKUP_DIR:-/home/jv/backups/gitea}"
local backup_script="/usr/local/sbin/homelab-gitea-backup.sh"
local restore_drill_script="/usr/local/sbin/homelab-gitea-restore-drill.sh"
sudo tee "${backup_script}" >/dev/null <<BACKUP_SCRIPT_EOT
#!/usr/bin/env bash
set -euo pipefail
GITEA_HOST="\${GITEA_HOST:-${gitea_host}}"
GITEA_USER="\${GITEA_USER:-${gitea_user}}"
GITEA_SSH_KEY_PATH="\${GITEA_SSH_KEY_PATH:-${gitea_key}}"
GITEA_CONTAINER="\${GITEA_CONTAINER:-${gitea_container}}"
GITEA_BACKUP_DIR="\${GITEA_BACKUP_DIR:-${backup_dir}}"
GITEA_BACKUP_RETENTION_DAYS="\${GITEA_BACKUP_RETENTION_DAYS:-30}"
REMOTE_ARCHIVE="/tmp/homelab-gitea-dump.zip"
timestamp="\$(date -u +%Y%m%dT%H%M%SZ)"
tmp_archive="\$(mktemp "/tmp/gitea-\${timestamp}.XXXXXX.zip")"
backup_archive="\${GITEA_BACKUP_DIR}/gitea-\${timestamp}.zip"
remote_host_archive="/tmp/gitea-\${timestamp}.zip"
ssh_gitea() {
ssh -i "\${GITEA_SSH_KEY_PATH}" -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new "\${GITEA_USER}@\${GITEA_HOST}" "\$@"
}
cleanup() {
rm -f "\${tmp_archive}"
ssh_gitea "rm -f '\${remote_host_archive}'; sudo docker exec -u git '\${GITEA_CONTAINER}' rm -f '\${REMOTE_ARCHIVE}' >/dev/null 2>&1 || true" >/dev/null 2>&1 || true
}
trap cleanup EXIT
ssh_gitea "set -eu
sudo docker exec -u git '\${GITEA_CONTAINER}' rm -f '\${REMOTE_ARCHIVE}' >/dev/null 2>&1 || true
sudo docker exec -u git '\${GITEA_CONTAINER}' sh -c 'mkdir -p /data/git/repositories'
sudo docker exec -u git '\${GITEA_CONTAINER}' gitea dump -c /data/gitea/conf/app.ini --file '\${REMOTE_ARCHIVE}'
sudo docker cp '\${GITEA_CONTAINER}:\${REMOTE_ARCHIVE}' '\${remote_host_archive}'
sudo chown '\${GITEA_USER}:\${GITEA_USER}' '\${remote_host_archive}'
sudo docker exec -u git '\${GITEA_CONTAINER}' rm -f '\${REMOTE_ARCHIVE}' >/dev/null 2>&1 || true"
scp -i "\${GITEA_SSH_KEY_PATH}" -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new \
"\${GITEA_USER}@\${GITEA_HOST}:\${remote_host_archive}" "\${tmp_archive}"
sudo mkdir -p "\${GITEA_BACKUP_DIR}"
sudo chown jv:jv "\${GITEA_BACKUP_DIR}"
sudo install -m 0640 -o jv -g jv "\${tmp_archive}" "\${backup_archive}"
sudo find "\${GITEA_BACKUP_DIR}" -type f -name 'gitea-*.zip' -mtime +"\${GITEA_BACKUP_RETENTION_DAYS}" -delete
echo "Created \${backup_archive}"
BACKUP_SCRIPT_EOT
sudo chmod 0755 "${backup_script}"
sudo tee /etc/systemd/system/homelab-gitea-backup.service >/dev/null <<'SERVICE_EOT'
[Unit]
Description=Back up external Homelab Gitea to Debian host storage
After=network-online.target
Wants=network-online.target
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/homelab-gitea-backup.sh
SERVICE_EOT
sudo tee /etc/systemd/system/homelab-gitea-backup.timer >/dev/null <<'TIMER_EOT'
[Unit]
Description=Run daily Homelab Gitea backups
[Timer]
OnCalendar=*-*-* 02:35:00
RandomizedDelaySec=20m
Persistent=true
[Install]
WantedBy=timers.target
TIMER_EOT
sudo tee "${restore_drill_script}" >/dev/null <<'RESTORE_DRILL_SCRIPT_EOT'
#!/usr/bin/env bash
set -euo pipefail
GITEA_BACKUP_DIR="${GITEA_BACKUP_DIR:-/home/jv/backups/gitea}"
GITEA_RESTORE_DRILL_DIR="${GITEA_RESTORE_DRILL_DIR:-/home/jv/backups/gitea-restore-drills}"
GITEA_RESTORE_DRILL_RETENTION_DAYS="${GITEA_RESTORE_DRILL_RETENTION_DAYS:-90}"
if ! command -v python3 >/dev/null 2>&1; then
echo "python3 is required for Gitea restore drills." >&2
exit 1
fi
latest_archive="$(
{ find "${GITEA_BACKUP_DIR}" -maxdepth 1 -type f -name 'gitea-*.zip' -printf '%T@ %p\n' 2>/dev/null || true; } |
sort -nr |
awk 'NR == 1 { sub(/^[^ ]+ /, ""); print }'
)"
if [[ -z "${latest_archive}" ]]; then
echo "Skipping Gitea restore drill: no backup archive found in ${GITEA_BACKUP_DIR}."
exit 0
fi
timestamp="$(date -u +%Y%m%dT%H%M%SZ)"
tmp_dir="$(mktemp -d "/tmp/gitea-restore-drill-${timestamp}.XXXXXX")"
tmp_report="$(mktemp "/tmp/gitea-restore-drill-${timestamp}.XXXXXX.txt")"
report_path="${GITEA_RESTORE_DRILL_DIR}/gitea-restore-drill-${timestamp}.txt"
cleanup() {
rm -rf "${tmp_dir}"
rm -f "${tmp_report}"
}
trap cleanup EXIT
python3 - "${latest_archive}" "${tmp_dir}" "${tmp_report}" <<'PY'
import os
import sys
import zipfile
archive_path, extract_dir, report_path = sys.argv[1:4]
with zipfile.ZipFile(archive_path) as archive:
bad_member = archive.testzip()
if bad_member:
raise SystemExit(f"ZIP integrity check failed at {bad_member}")
members = archive.infolist()
if not members:
raise SystemExit("ZIP archive is empty")
extract_root = os.path.abspath(extract_dir)
for member in members:
target = os.path.abspath(os.path.join(extract_root, member.filename))
if target != extract_root and not target.startswith(extract_root + os.sep):
raise SystemExit(f"Unsafe archive path: {member.filename}")
archive.extractall(extract_root)
file_count = 0
total_bytes = 0
for root, _, files in os.walk(extract_dir):
for name in files:
file_count += 1
total_bytes += os.path.getsize(os.path.join(root, name))
if file_count == 0:
raise SystemExit("Archive extracted no files")
with open(report_path, "w", encoding="utf-8") as handle:
handle.write("Gitea restore drill report\n")
handle.write(f"archive={archive_path}\n")
handle.write(f"archive_size_bytes={os.path.getsize(archive_path)}\n")
handle.write(f"extracted_files={file_count}\n")
handle.write(f"extracted_bytes={total_bytes}\n")
handle.write("result=ok\n")
PY
sudo mkdir -p "${GITEA_RESTORE_DRILL_DIR}"
sudo install -m 0640 -o root -g root "${tmp_report}" "${report_path}"
sudo find "${GITEA_RESTORE_DRILL_DIR}" -type f -name 'gitea-restore-drill-*.txt' -mtime +"${GITEA_RESTORE_DRILL_RETENTION_DAYS}" -delete
echo "Created ${report_path}"
RESTORE_DRILL_SCRIPT_EOT
sudo chmod 0755 "${restore_drill_script}"
sudo tee /etc/systemd/system/homelab-gitea-restore-drill.service >/dev/null <<'RESTORE_DRILL_SERVICE_EOT'
[Unit]
Description=Run a non-destructive Gitea backup restore drill
After=network-online.target homelab-gitea-backup.service
Wants=network-online.target
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/homelab-gitea-restore-drill.sh
RESTORE_DRILL_SERVICE_EOT
sudo tee /etc/systemd/system/homelab-gitea-restore-drill.timer >/dev/null <<'RESTORE_DRILL_TIMER_EOT'
[Unit]
Description=Run monthly Homelab Gitea restore drills
[Timer]
OnCalendar=monthly
RandomizedDelaySec=2h
Persistent=true
[Install]
WantedBy=timers.target
RESTORE_DRILL_TIMER_EOT
sudo systemctl daemon-reload
sudo systemctl enable --now homelab-gitea-backup.timer >/dev/null
sudo systemctl enable --now homelab-gitea-restore-drill.timer >/dev/null
}
backup_gitea() {
require_debian_server "backup-gitea"
install_gitea_backup_timer
sudo /usr/local/sbin/homelab-gitea-backup.sh
}
drill_gitea_restore() {
require_debian_server "drill-gitea-restore"
install_gitea_backup_timer
sudo /usr/local/sbin/homelab-gitea-restore-drill.sh
}
install_gitea_runner() {
local runner_arch
local runner_home="${GITEA_RUNNER_HOME:-/home/jv/.local/share/gitea-runner/my-homelab-configs}"
local runner_instance="${GITEA_RUNNER_INSTANCE_URL:-https://lab2025.duckdns.org/git/}"
local runner_labels="${GITEA_RUNNER_LABELS:-homelab-debian:host}"
local runner_name="${GITEA_RUNNER_NAME:-homelab-debian-my-homelab-configs}"
local runner_token="${GITEA_RUNNER_REGISTRATION_TOKEN:-${1:-}}"
local runner_user="${GITEA_RUNNER_USER:-jv}"
local runner_version="${GITEA_ACT_RUNNER_VERSION:-0.2.11}"
local missing_packages=()
require_debian_server "install-gitea-runner"
case "$(dpkg --print-architecture)" in
amd64)
runner_arch="linux-amd64"
;;
arm64)
runner_arch="linux-arm64"
;;
*)
echo "Unsupported Debian architecture: $(dpkg --print-architecture)" >&2
exit 1
;;
esac
for package in ca-certificates curl git nodejs python3 python3-yaml; do
if ! dpkg-query -W -f='${Status}' "$package" 2>/dev/null | grep -q "install ok installed"; then
missing_packages+=("$package")
fi
done
if [[ ${#missing_packages[@]} -gt 0 ]]; then
sudo apt-get update
sudo apt-get install -y --no-install-recommends "${missing_packages[@]}"
fi
sudo curl -fsSL \
-o /usr/local/bin/act_runner \
"https://gitea.com/gitea/act_runner/releases/download/v${runner_version}/act_runner-${runner_version}-${runner_arch}"
sudo chmod 0755 /usr/local/bin/act_runner
sudo chown root:root /usr/local/bin/act_runner
sudo -u "${runner_user}" mkdir -p "${runner_home}"
if [[ ! -f "${runner_home}/.runner" ]]; then
if [[ -z "${runner_token}" ]]; then
echo "Set GITEA_RUNNER_REGISTRATION_TOKEN to the repository-level runner token from Gitea." >&2
exit 1
fi
sudo -u "${runner_user}" env \
HOME="/home/${runner_user}" \
GITEA_RUNNER_HOME="${runner_home}" \
GITEA_RUNNER_INSTANCE_URL="${runner_instance}" \
GITEA_RUNNER_REGISTRATION_TOKEN="${runner_token}" \
GITEA_RUNNER_NAME="${runner_name}" \
GITEA_RUNNER_LABELS="${runner_labels}" \
bash -lc 'cd "${GITEA_RUNNER_HOME}" && /usr/local/bin/act_runner register --no-interactive --instance "${GITEA_RUNNER_INSTANCE_URL}" --token "${GITEA_RUNNER_REGISTRATION_TOKEN}" --name "${GITEA_RUNNER_NAME}" --labels "${GITEA_RUNNER_LABELS}"'
else
echo "Existing runner registration found at ${runner_home}/.runner; keeping it."
fi
sudo tee /etc/systemd/system/homelab-gitea-runner.service >/dev/null <<SERVICE_EOT
[Unit]
Description=Homelab Gitea Actions runner for my-homelab-configs
After=network-online.target docker.service
Wants=network-online.target
[Service]
Type=simple
User=${runner_user}
Group=${runner_user}
WorkingDirectory=${runner_home}
Environment=HOME=/home/${runner_user}
Environment=PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
ExecStart=/usr/local/bin/act_runner daemon
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
SERVICE_EOT
sudo systemctl daemon-reload
sudo systemctl enable --now homelab-gitea-runner.service >/dev/null
sudo systemctl status homelab-gitea-runner.service --no-pager -l
}
ensure_deployment_container_image() {
local namespace="$1"
local deployment="$2"
local container="$3"
local image_ref="$4"
local app="$5"
local current_image
current_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 "${current_image}" ]]; then
echo "Could not read image for container ${container} in deployment/${deployment} in namespace ${namespace}." >&2
dump_argocd_debug "${app}"
dump_namespace_debug "${namespace}"
exit 1
fi
if [[ "${current_image}" == "${image_ref}" ]]; then
return 0
fi
echo "Updating deployment/${deployment} container ${container} image from ${current_image} to ${image_ref}."
kubectl --kubeconfig "${KUBECONFIG_PATH}" -n "${namespace}" set image "deployment/${deployment}" "${container}=${image_ref}"
}
refresh_argocd_application() {
local app="$1"
kubectl --kubeconfig "${KUBECONFIG_PATH}" patch application "${app}" -n argocd --type merge -p '{"metadata":{"annotations":{"argocd.argoproj.io/refresh":"hard"}}}' >/dev/null
}
website_translation_model() {
local model_name="${WEBSITE_TRANSLATION_MODEL:-website-translator}"
local modelfile="${WEBSITE_TRANSLATION_MODELFILE:-${REPO_ROOT}/apps/website/ollama/Modelfile}"
require_debian_server "website-translation-model"
if ! command -v ollama >/dev/null 2>&1; then
echo "ollama is not installed or not in PATH on this Debian server." >&2
exit 1
fi
if [[ ! -r "${modelfile}" ]]; then
echo "Ollama Modelfile is not readable: ${modelfile}" >&2
exit 1
fi
echo "Creating or updating Ollama model ${model_name} from ${modelfile}..."
ollama create "${model_name}" -f "${modelfile}"
if ! ollama list | awk -v model="${model_name}" 'NR > 1 && ($1 == model || $1 == model ":latest") { found = 1 } END { exit found ? 0 : 1 }'; then
echo "Ollama model ${model_name} was not found after creation." >&2
exit 1
fi
echo "Ollama model ${model_name} is ready."
}
website_ollama_listen() {
local bind_address="${WEBSITE_OLLAMA_BIND_ADDRESS:-${LAB_OLLAMA_BIND_ADDRESS:-0.0.0.0:11434}}"
local models_dir="${LAB_OLLAMA_MODELS_DIR:-/data/ollama/models}"
local igpu_enable="${LAB_OLLAMA_IGPU_ENABLE:-false}"
local dropin_dir="/etc/systemd/system/ollama.service.d"
local dropin_file="${dropin_dir}/homelab.conf"
local waited=0
require_debian_server "website-ollama-listen"
bind_address="${bind_address#http://}"
bind_address="${bind_address#https://}"
if ! systemctl cat ollama.service >/dev/null 2>&1; then
echo "ollama.service was not found on this Debian server." >&2
exit 1
fi
echo "Configuring ollama.service to listen on ${bind_address}..."
sudo mkdir -p "${dropin_dir}"
sudo mkdir -p "${models_dir}"
if id ollama >/dev/null 2>&1; then
sudo chown ollama:ollama "${models_dir}"
fi
printf '[Service]\nEnvironment="OLLAMA_HOST=%s"\nEnvironment="OLLAMA_MODELS=%s"\nEnvironment="OLLAMA_IGPU_ENABLE=%s"\n' "${bind_address}" "${models_dir}" "${igpu_enable}" |
sudo tee "${dropin_file}" >/dev/null
sudo systemctl daemon-reload
sudo systemctl restart ollama.service
sudo systemctl is-active --quiet ollama.service
echo "Ollama service is active. Waiting for http://127.0.0.1:11434/api/tags..."
until curl -fsS --connect-timeout 2 --max-time 5 "http://127.0.0.1:11434/api/tags" >/dev/null 2>&1; do
waited=$((waited + 2))
if ((waited >= 60)); then
echo "Ollama service did not expose the local API after ${waited}s." >&2
echo "Recent service logs:" >&2
sudo journalctl -u ollama.service -n 80 --no-pager >&2 || true
exit 1
fi
sleep 2
done
echo "Ollama API is reachable on the Debian host."
}
ollama_linux_arch() {
case "$(uname -m)" in
x86_64 | amd64)
printf 'amd64\n'
;;
aarch64 | arm64)
printf 'arm64\n'
;;
*)
echo "Unsupported Ollama Linux architecture: $(uname -m)" >&2
return 1
;;
esac
}
ollama_write_systemd_service() {
sudo tee /etc/systemd/system/ollama.service >/dev/null <<'EOF'
[Unit]
Description=Ollama Service
After=network-online.target
[Service]
ExecStart=/usr/bin/ollama serve
User=ollama
Group=ollama
Restart=always
RestartSec=3
Environment="PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
[Install]
WantedBy=default.target
EOF
}
ollama_install_from_tgz() {
local tarball="$1"
if [[ ! -r "${tarball}" ]]; then
echo "Ollama tarball is not readable: ${tarball}" >&2
exit 1
fi
echo "Installing Ollama from local tarball ${tarball}..."
sudo tar -C /usr -xzf "${tarball}"
if ! id ollama >/dev/null 2>&1; then
sudo useradd -r -s /bin/false -U -m -d /usr/share/ollama ollama
fi
if getent group render >/dev/null 2>&1; then
sudo usermod -aG render ollama
fi
if getent group video >/dev/null 2>&1; then
sudo usermod -aG video ollama
fi
ollama_write_systemd_service
}
ollama_setup() {
local bind_address="${LAB_OLLAMA_BIND_ADDRESS:-0.0.0.0:11434}"
local models_dir="${LAB_OLLAMA_MODELS_DIR:-/data/ollama/models}"
local model="${LAB_AI_GATEWAY_MODEL:-qwen2.5:0.5b}"
local installer_url="${LAB_OLLAMA_INSTALL_URL:-https://ollama.com/install.sh}"
local connect_timeout="${LAB_OLLAMA_INSTALL_CONNECT_TIMEOUT:-15}"
local max_time="${LAB_OLLAMA_INSTALL_MAX_TIME:-120}"
local curl_ip_version="${LAB_OLLAMA_INSTALL_CURL_IP_VERSION:--4}"
local local_tarball="${LAB_OLLAMA_TARBALL_FILE:-}"
local arch
local tmp_installer
local curl_ip_args=()
require_debian_server "ollama-setup"
if ! command -v curl >/dev/null 2>&1; then
echo "curl is required to install Ollama." >&2
exit 1
fi
if [[ -n "${curl_ip_version}" ]]; then
curl_ip_args+=("${curl_ip_version}")
fi
if ! command -v ollama >/dev/null 2>&1; then
if [[ -n "${local_tarball}" ]]; then
ollama_install_from_tgz "${local_tarball}"
else
echo "Installing Ollama from ${installer_url}..."
tmp_installer="$(mktemp)"
if ! curl "${curl_ip_args[@]}" -fsSL --connect-timeout "${connect_timeout}" --max-time "${max_time}" "${installer_url}" -o "${tmp_installer}"; then
rm -f "${tmp_installer}"
arch="$(ollama_linux_arch || true)"
cat >&2 <<EOF
Could not download the Ollama installer from ${installer_url}.
If this Debian host cannot reach ollama.com, download the Linux tarball from a
machine with internet access and copy it to the Debian host:
curl -L https://ollama.com/download/ollama-linux-${arch:-amd64}.tgz -o /tmp/ollama-linux-${arch:-amd64}.tgz
scp /tmp/ollama-linux-${arch:-amd64}.tgz jv@${LAB_DEBIAN_LAN_IP:-192.168.100.73}:/tmp/
Then run on Debian:
LAB_OLLAMA_TARBALL_FILE=/tmp/ollama-linux-${arch:-amd64}.tgz ./jeannie ollama-setup
EOF
exit 1
fi
sudo sh "${tmp_installer}"
rm -f "${tmp_installer}"
fi
else
echo "Ollama is already installed: $(command -v ollama)"
fi
website_ollama_listen
echo "Ensuring Ollama model ${model} is available..."
if ollama list | awk -v model="${model}" 'NR > 1 && ($1 == model || $1 == model ":latest") { found = 1 } END { exit found ? 0 : 1 }'; then
echo "Ollama model ${model} is already present."
else
OLLAMA_HOST=http://127.0.0.1:11434 ollama pull "${model}"
fi
echo "Ollama homelab setup is ready."
}
require_argocd_application_controller() {
local namespace="${TF_VAR_argocd_namespace:-argocd}"
local expected_resources="10m|1|2Gi"
local actual_resources
local timeout_seconds="${LAB_ARGOCD_READY_WAIT_SECONDS:-600}"
if ! [[ "${timeout_seconds}" =~ ^[1-9][0-9]*$ ]]; then
echo "LAB_ARGOCD_READY_WAIT_SECONDS must be a positive number of seconds." >&2
return 2
fi
echo "Waiting up to ${timeout_seconds}s for the Argo CD application-controller rollout..."
if ! kubectl --kubeconfig "${KUBECONFIG_PATH}" -n "${namespace}" rollout status statefulset/argocd-application-controller --timeout="${timeout_seconds}s"; then
echo "Argo CD application controller did not become ready; refusing to start application deployment." >&2
kubectl --kubeconfig "${KUBECONFIG_PATH}" --request-timeout=10s -n "${namespace}" \
get statefulset argocd-application-controller \
-o custom-columns='NAME:.metadata.name,GEN:.metadata.generation,OBSERVED:.status.observedGeneration,DESIRED:.spec.replicas,READY:.status.readyReplicas,UPDATED:.status.updatedReplicas,CURRENT-REV:.status.currentRevision,TARGET-REV:.status.updateRevision' >&2 || true
kubectl --kubeconfig "${KUBECONFIG_PATH}" --request-timeout=10s -n "${namespace}" get pods \
-l app.kubernetes.io/name=argocd-application-controller \
-o custom-columns='NAME:.metadata.name,PHASE:.status.phase,READY:.status.containerStatuses[*].ready,RESTARTS:.status.containerStatuses[*].restartCount,WAITING:.status.containerStatuses[*].state.waiting.reason,REVISION:.metadata.labels.controller-revision-hash' >&2 || true
kubectl --kubeconfig "${KUBECONFIG_PATH}" --request-timeout=10s -n "${namespace}" get events \
--field-selector type=Warning --sort-by=.lastTimestamp \
-o custom-columns='REASON:.reason,OBJECT:.involvedObject.name,MESSAGE:.message' 2>/dev/null |
tail -6 | cut -c1-280 >&2 || true
exit 1
fi
actual_resources="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" -n "${namespace}" get statefulset argocd-application-controller \
-o jsonpath='{.spec.template.spec.containers[0].resources.requests.cpu}{"|"}{.spec.template.spec.containers[0].resources.limits.cpu}{"|"}{.spec.template.spec.containers[0].resources.limits.memory}')"
if [[ "${actual_resources}" != "${expected_resources}" ]]; then
echo "Argo CD application controller resources are '${actual_resources:-missing}', expected '${expected_resources}'. Refusing to start application deployment." >&2
echo "Run ./jeannie platform after correcting bootstrap/platform/main.tf." >&2
exit 1
fi
}
require_pimox_app_worker_capacity() {
local scope="${1:-all}"
local enabled="${LAB_PIMOX_APP_DEPLOY_REQUIRE_CAPACITY:-true}"
local spec_file="${REPO_ROOT}/.lab/pimox-workers.tsv"
local worker_key
local worker_host
local worker_user
local worker_node
local worker_key_path
local capacity
local ready
local failures=0
local eligible_workers=0
# The generated inventory describes kubeadm workers, not the selected
# cluster's live topology. Direct k3s bootstrap does not join these VMs;
# stale files from a previous deployment must not make them mandatory.
if [[ "${LAB_CLUSTER_RUNTIME:-kubeadm}" == k3s ]]; then
echo "Direct k3s runtime uses live scheduling preflight; ignoring the generated kubeadm/Pimox worker inventory."
return 0
fi
if disabled_value "${enabled}"; then
echo "Skipping Pimox worker readiness gate because LAB_PIMOX_APP_DEPLOY_REQUIRE_CAPACITY=${enabled}. Scheduling preflight still runs before apply."
return 0
fi
if [[ ! -s "${spec_file}" ]]; then
echo "No generated Pimox worker inventory exists; scheduling preflight will inspect live nodes before apply."
return 0
fi
while IFS=$'\t' read -r worker_key worker_host worker_user worker_node worker_key_path; do
[[ -n "${worker_node}" ]] || continue
capacity="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" get node "${worker_node}" -o jsonpath='{.status.capacity.cpu}' 2>/dev/null || true)"
ready="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" get node "${worker_node}" -o jsonpath='{.status.conditions[?(@.type=="Ready")].status}' 2>/dev/null || true)"
if [[ "${ready}" == "True" ]] && [[ "${capacity}" =~ ^[0-9]+$ ]] && ((capacity >= 1)); then
eligible_workers=$((eligible_workers + 1))
elif [[ "${scope}" == "all" ]]; then
echo "Pimox worker ${worker_node} must be Ready with positive CPU capacity; Ready=${ready:-missing}, capacity=${capacity:-missing}." >&2
failures=$((failures + 1))
fi
done <"${spec_file}"
if [[ "${scope}" == "all" ]] && ((failures > 0)); then
echo "Refusing to deploy applications until Pimox workers are Ready; scheduling feasibility is checked separately." >&2
kubectl --kubeconfig "${KUBECONFIG_PATH}" get nodes -o custom-columns='NAME:.metadata.name,CPUS:.status.capacity.cpu,READY:.status.conditions[?(@.type=="Ready")].status' >&2 || true
exit 1
fi
if [[ "${scope}" != "all" ]] && ((eligible_workers == 0)); then
echo "Refusing to deploy ${scope}: no Ready Pimox worker exposes positive CPU capacity." >&2
kubectl --kubeconfig "${KUBECONFIG_PATH}" get nodes -o custom-columns='NAME:.metadata.name,CPUS:.status.capacity.cpu,READY:.status.conditions[?(@.type=="Ready")].status' >&2 || true
exit 1
fi
}
ensure_pimox_kubeconfig() {
local kubeconfig="${KUBECONFIG_PATH}"
local control_plane_host="${LAB_CLUSTER_CONTROL_PLANE_LAN_IP:-${LAB_PIMOX_CONTROL_PLANE_IP:-}}"
local control_plane_user="${LAB_CLUSTER_CONTROL_PLANE_USER:-${LAB_PIMOX_CONTROL_PLANE_USER:-jv}}"
local control_plane_key="${LAB_CLUSTER_CONTROL_PLANE_SSH_KEY_PATH:-${LAB_PIMOX_CONTROL_PLANE_SSH_KEY_PATH:-/home/jv/.ssh/id_ed25519}}"
local tmp_file
if [[ -s "${kubeconfig}" ]] &&
kubectl --kubeconfig "${kubeconfig}" get --raw=/readyz >/dev/null 2>&1; then
return 0
fi
if [[ "${LAB_CLUSTER_PROFILE:-debian}" != "pimox" ]]; then
echo "Kubeconfig is missing or API is unreachable: ${kubeconfig}" >&2
echo "Set LAB_CLUSTER_PROFILE=pimox for Pimox pullback, or run ./jeannie rebuild-cluster for the Debian profile." >&2
exit 1
fi
if [[ -z "${control_plane_host}" ]]; then
echo "LAB_CLUSTER_CONTROL_PLANE_LAN_IP is required to rebuild the Pimox kubeconfig." >&2
exit 1
fi
echo "Refreshing Pimox kubeconfig ${kubeconfig} from ${control_plane_user}@${control_plane_host}..."
tmp_file="$(mktemp "${TMPDIR:-/tmp}/homelab-pimox-kubeconfig.XXXXXX")"
trap 'rm -f "${tmp_file}"' RETURN
mkdir -p "$(dirname "${kubeconfig}")"
if ! ssh -i "${control_plane_key}" \
-o BatchMode=yes \
-o ConnectTimeout=10 \
-o IdentitiesOnly=yes \
-o StrictHostKeyChecking=accept-new \
"${control_plane_user}@${control_plane_host}" \
"sudo cat /etc/kubernetes/admin.conf" >"${tmp_file}"; then
echo "Could not read /etc/kubernetes/admin.conf from Pimox control-plane ${control_plane_host}." >&2
exit 1
fi
python3 - "${tmp_file}" "${control_plane_host}" <<'PY'
import re
import sys
from pathlib import Path
path = Path(sys.argv[1])
host = sys.argv[2]
text = path.read_text(encoding="utf-8")
replacement = rf"\1https://{host}:6443"
text, count = re.subn(r"(^\s*server:\s*)https://[^\s]+:6443", replacement, text, count=1, flags=re.MULTILINE)
if count == 0:
raise SystemExit("admin.conf did not contain a Kubernetes API server URL")
path.write_text(text, encoding="utf-8")
PY
install -m 0600 "${tmp_file}" "${kubeconfig}"
if ! kubectl --kubeconfig "${kubeconfig}" get --raw=/readyz >/dev/null 2>&1; then
echo "Refreshed kubeconfig ${kubeconfig}, but the Kubernetes API is still unreachable." >&2
kubectl --kubeconfig "${kubeconfig}" get nodes -o wide >&2 || true
exit 1
fi
}
pimox_primary_worker_inventory() {
local spec_file="${REPO_ROOT}/.lab/pimox-workers.tsv"
local worker_key
local worker_host
local worker_user
local worker_node
local worker_key_path
if [[ -s "${spec_file}" ]]; then
while IFS=$'\t' read -r worker_key worker_host worker_user worker_node worker_key_path; do
if [[ -n "${worker_host}" && -n "${worker_user}" && -n "${worker_node}" && -n "${worker_key_path}" ]]; then
printf '%s\t%s\t%s\t%s\n' "${worker_host}" "${worker_user}" "${worker_node}" "${worker_key_path}"
return 0
fi
done <"${spec_file}"
fi
worker_host="${LAB_PIMOX_REGISTRY_WORKER_IP:-${LAB_PIMOX_WORKER_STATIC_IPS:-}}"
worker_host="${worker_host%% *}"
worker_user="${LAB_PIMOX_WORKER_USER:-jv}"
worker_node="${LAB_PIMOX_REGISTRY_WORKER_NODE:-pimox-worker-01}"
worker_key_path="${LAB_PIMOX_WORKER_SSH_KEY_PATH:-/home/jv/.ssh/id_ed25519}"
if [[ -n "${worker_host}" ]]; then
printf '%s\t%s\t%s\t%s\n' "${worker_host}" "${worker_user}" "${worker_node}" "${worker_key_path}"
return 0
fi
return 1
}
reconcile_app_registry_storage() {
local inventory source_host source_user source_node source_key result
cluster_context_require || return 1
inventory="$(pimox_primary_worker_inventory)" || {
echo "Cannot discover the previous registry host; refusing to assume its data is absent." >&2
return 1
}
IFS=$'\t' read -r source_host source_user source_node source_key <<<"${inventory}"
result="$(mktemp "${TMPDIR:-/tmp}/jeannie-registry-placement.XXXXXX")" || return 1
if ! python3 "${REPO_ROOT}/scripts/registry-storage-reconcile.py" \
--kubeconfig "${KUBECONFIG_PATH}" \
--destination-node "${LAB_CLUSTER_CONTROL_PLANE_NODE_NAME}" \
--destination-host "${LAB_CLUSTER_CONTROL_PLANE_LAN_IP}" \
--destination-user "${LAB_CLUSTER_CONTROL_PLANE_USER}" \
--destination-key "${LAB_CLUSTER_CONTROL_PLANE_SSH_KEY_PATH}" \
--required-data-mount "${LAB_CLUSTER_REQUIRED_DATA_MOUNT:-}" \
--destination-path "${LAB_REGISTRY_STORAGE_PATH:-/data/openebs/local/registry}" \
--source-host "${source_host}" --source-user "${source_user}" --source-key "${source_key}" \
--source-node "${source_node}" --source-path "${LAB_PIMOX_REGISTRY_STORAGE_PATH:-/data/openebs/local/registry}" \
--hypervisor-host "${LAB_CLUSTER_PIMOX_HOST:-${LAB_PIMOX_HOST:-192.168.100.80}}" \
--hypervisor-user "${LAB_CLUSTER_PIMOX_USER:-jv}" \
--hypervisor-key "${LAB_PIMOX_SSH_KEY_PATH:-${LAB_CLUSTER_CONTROL_PLANE_SSH_KEY_PATH:-/home/jv/.ssh/id_ed25519}}" \
--source-vmid "${LAB_PIMOX_REGISTRY_SOURCE_VMID:-${LAB_PIMOX_WORKER_BASE_VMID:-9010}}" \
--registry-endpoint "${TF_VAR_registry_endpoint:-${LAB_REGISTRY_ENDPOINT}}" \
--state-dir "${HOMELAB_STATE_DIR}/clusters/${LAB_CLUSTER_PROFILE}" --result "${result}"; then
rm -f "${result}"
return 1
fi
TF_VAR_registry_placement="$(<"${result}")"
export TF_VAR_registry_placement
rm -f "${result}"
}
ensure_pimox_registry_storage_path() {
local enabled="${LAB_PIMOX_REGISTRY_PREPARE_STORAGE:-true}"
local inventory
local worker_host
local worker_user
local worker_node
local worker_key_path
local registry_path="${LAB_PIMOX_REGISTRY_STORAGE_PATH:-/data/openebs/local/registry}"
if [[ "${LAB_CLUSTER_PROFILE:-debian}" != "pimox" ]]; then
return 0
fi
if disabled_value "${enabled}"; then
echo "Skipping Pimox registry storage preparation because LAB_PIMOX_REGISTRY_PREPARE_STORAGE=${enabled}."
return 0
fi
if ! truthy "${enabled}"; then
echo "LAB_PIMOX_REGISTRY_PREPARE_STORAGE must be true or false." >&2
exit 1
fi
inventory="$(pimox_primary_worker_inventory)" || {
echo "Could not resolve a Pimox worker for registry storage preparation." >&2
exit 1
}
IFS=$'\t' read -r worker_host worker_user worker_node worker_key_path <<<"${inventory}"
echo "Ensuring local registry storage exists on ${worker_node} (${worker_user}@${worker_host}:${registry_path})..."
refresh_lab_ssh_known_host "${worker_host}"
ssh -i "${worker_key_path}" -o BatchMode=yes -o ConnectTimeout=10 -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new "${worker_user}@${worker_host}" "set -eu
sudo mkdir -p '${registry_path}'
sudo chown 1000:1000 '${registry_path}'
sudo chmod 0750 '${registry_path}'
"
}
ensure_pimox_registry_endpoint_forwarding() {
local enabled="${LAB_PIMOX_REGISTRY_FORWARDING:-true}"
local registry_endpoint="$1"
local inventory
local registry_host
local registry_port
local target_host
local target_port
local _worker_user
local _worker_node
local _worker_key_path
if disabled_value "${enabled}"; then
echo "Skipping Pimox registry endpoint forwarding because LAB_PIMOX_REGISTRY_FORWARDING=${enabled}."
return 0
fi
if ! truthy "${enabled}"; then
echo "LAB_PIMOX_REGISTRY_FORWARDING must be true or false." >&2
exit 1
fi
if [[ "${registry_endpoint}" != *:* ]]; then
echo "Registry endpoint '${registry_endpoint}' must include host:port." >&2
exit 1
fi
registry_host="${registry_endpoint%:*}"
registry_port="${registry_endpoint##*:}"
target_port="${LAB_PIMOX_REGISTRY_TARGET_PORT:-${registry_port}}"
if [[ -n "${TF_VAR_registry_placement:-}" ]]; then
_worker_node="$(python3 -c 'import json,sys; print(json.loads(sys.argv[1])["node"])' "${TF_VAR_registry_placement}")" || return 1
target_host="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" --request-timeout=15s get node "${_worker_node}" \
-o jsonpath='{.status.addresses[?(@.type=="InternalIP")].address}')" || return 1
else
inventory="$(pimox_primary_worker_inventory)" || {
echo "Could not resolve the registry node for endpoint forwarding." >&2
return 1
}
IFS=$'\t' read -r target_host _worker_user _worker_node _worker_key_path <<<"${inventory}"
fi
if ! validate_ipv4_cidr_or_host "${registry_host}" || [[ "${registry_host}" == */* ]]; then
echo "Invalid registry host '${registry_host}'." >&2
exit 1
fi
if ! validate_ipv4_cidr_or_host "${target_host}" || [[ "${target_host}" == */* ]]; then
echo "Invalid Pimox registry target host '${target_host}'." >&2
exit 1
fi
if ! [[ "${registry_port}" =~ ^[0-9]+$ && "${target_port}" =~ ^[0-9]+$ ]]; then
echo "Registry ports must be numeric, got ${registry_port} -> ${target_port}." >&2
exit 1
fi
# Remove only our tagged rules, including those pointing at a previously
# selected profile. Otherwise old DNAT rules can win after a later restart.
if ! python3 - "${REPO_ROOT}/scripts/registry-storage-reconcile.py" <<'REGISTRY_RETIRE_PY'
import importlib.util
import sys
spec = importlib.util.spec_from_file_location("registry_forwarding", sys.argv[1])
helper = importlib.util.module_from_spec(spec)
spec.loader.exec_module(helper)
helper.retire_legacy_forwarding()
REGISTRY_RETIRE_PY
then
return 1
fi
if [[ "${registry_host}:${registry_port}" == "${target_host}:${target_port}" ]]; then
return 0
fi
echo "Ensuring ${registry_host}:${registry_port} forwards to selected registry NodePort ${target_host}:${target_port}..."
sudo tee /usr/local/sbin/homelab-pimox-registry-forward.sh >/dev/null <<REGISTRY_FORWARD_SCRIPT_EOF
#!/usr/bin/env bash
set -euo pipefail
registry_host='${registry_host}'
registry_port='${registry_port}'
target_host='${target_host}'
target_port='${target_port}'
comment='homelab-pimox-registry-forward'
sysctl_bin="\$(command -v sysctl 2>/dev/null || true)"
if [ -z "\$sysctl_bin" ] && [ -x /usr/sbin/sysctl ]; then
sysctl_bin=/usr/sbin/sysctl
fi
if [ -n "\$sysctl_bin" ]; then
"\$sysctl_bin" -w net.ipv4.ip_forward=1 >/dev/null
fi
iptables_bin="\$(command -v iptables 2>/dev/null || true)"
if [ -z "\$iptables_bin" ] && [ -x /usr/sbin/iptables ]; then
iptables_bin=/usr/sbin/iptables
fi
if [ -z "\$iptables_bin" ]; then
echo 'iptables is required to forward the Pimox registry endpoint.' >&2
exit 1
fi
iptables_cmd() {
"\$iptables_bin" "\$@"
}
route_line="\$(ip route get "\$target_host")"
lan_if="\$(printf '%s\n' "\$route_line" | awk '{for (i = 1; i < NF; i++) if (\$i == "dev") {print \$(i + 1); exit}}')"
if [ -z "\$lan_if" ]; then
echo "Could not resolve LAN interface for \$target_host." >&2
exit 1
fi
while iptables_cmd -t nat -D PREROUTING -p tcp -d "\$registry_host" --dport "\$registry_port" -m comment --comment "\$comment" -j DNAT --to-destination "\$target_host:\$target_port" 2>/dev/null; do :; done
while iptables_cmd -t nat -D OUTPUT -p tcp -d "\$registry_host" --dport "\$registry_port" -m comment --comment "\$comment" -j DNAT --to-destination "\$target_host:\$target_port" 2>/dev/null; do :; done
while iptables_cmd -t nat -D POSTROUTING -p tcp -d "\$target_host" --dport "\$target_port" -m comment --comment "\$comment" -j MASQUERADE 2>/dev/null; do :; done
while iptables_cmd -D FORWARD -p tcp -d "\$target_host" --dport "\$target_port" -m comment --comment "\$comment" -j ACCEPT 2>/dev/null; do :; done
iptables_cmd -t nat -I PREROUTING 1 -p tcp -d "\$registry_host" --dport "\$registry_port" -m comment --comment "\$comment" -j DNAT --to-destination "\$target_host:\$target_port"
iptables_cmd -t nat -I OUTPUT 1 -p tcp -d "\$registry_host" --dport "\$registry_port" -m comment --comment "\$comment" -j DNAT --to-destination "\$target_host:\$target_port"
iptables_cmd -t nat -I POSTROUTING 1 -p tcp -d "\$target_host" --dport "\$target_port" -m comment --comment "\$comment" -j MASQUERADE
iptables_cmd -I FORWARD 1 -p tcp -d "\$target_host" --dport "\$target_port" -m comment --comment "\$comment" -j ACCEPT
REGISTRY_FORWARD_SCRIPT_EOF
sudo chmod 0755 /usr/local/sbin/homelab-pimox-registry-forward.sh
sudo tee /etc/systemd/system/homelab-pimox-registry-forward.service >/dev/null <<'REGISTRY_FORWARD_SERVICE_EOF'
[Unit]
Description=Forward legacy Debian registry endpoint to Pimox registry NodePort
After=network-online.target
Wants=network-online.target
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/homelab-pimox-registry-forward.sh
RemainAfterExit=yes
[Install]
WantedBy=multi-user.target
REGISTRY_FORWARD_SERVICE_EOF
sudo systemctl daemon-reload
sudo systemctl enable homelab-pimox-registry-forward.service >/dev/null
sudo systemctl restart homelab-pimox-registry-forward.service
}
ensure_pimox_containerd_registry_refresh() {
local enabled="${LAB_PIMOX_REGISTRY_REFRESH_CONTAINERD:-true}"
local registry_endpoint="$1"
local cp_host="${LAB_CLUSTER_CONTROL_PLANE_LAN_IP:-}"
local cp_user="${LAB_CLUSTER_CONTROL_PLANE_USER:-jv}"
local cp_node="${LAB_CLUSTER_CONTROL_PLANE_NODE_NAME:-pimox-cp-01}"
local cp_key="${LAB_CLUSTER_CONTROL_PLANE_SSH_KEY_PATH:-/home/jv/.ssh/id_ed25519}"
local spec_file="${REPO_ROOT}/.lab/pimox-workers.tsv"
local -a node_entries=()
local worker_key
local worker_host
local worker_user
local worker_node
local worker_key_path
local node_entry
local node_host
local node_user
local node_name
local node_key_path
if [[ "${LAB_CLUSTER_PROFILE:-debian}" != "pimox" ]]; then
return 0
fi
if disabled_value "${enabled}"; then
echo "Skipping Pimox containerd registry refresh because LAB_PIMOX_REGISTRY_REFRESH_CONTAINERD=${enabled}."
return 0
fi
if ! truthy "${enabled}"; then
echo "LAB_PIMOX_REGISTRY_REFRESH_CONTAINERD must be true or false." >&2
exit 1
fi
if [[ "${registry_endpoint}" != *:* || ! "${registry_endpoint}" =~ ^[A-Za-z0-9_.:-]+$ ]]; then
echo "Registry endpoint '${registry_endpoint}' must be a simple host:port value for remote containerd configuration." >&2
exit 1
fi
if [[ -n "${cp_host}" ]]; then
node_entries+=("${cp_host}"$'\t'"${cp_user}"$'\t'"${cp_node}"$'\t'"${cp_key}")
fi
if [[ -s "${spec_file}" ]]; then
while IFS=$'\t' read -r worker_key worker_host worker_user worker_node worker_key_path; do
[[ -n "${worker_host}" && -n "${worker_user}" && -n "${worker_node}" && -n "${worker_key_path}" ]] || continue
node_entries+=("${worker_host}"$'\t'"${worker_user}"$'\t'"${worker_node}"$'\t'"${worker_key_path}")
done <"${spec_file}"
fi
if ((${#node_entries[@]} == 0)); then
echo "Could not resolve Pimox nodes for containerd registry refresh." >&2
exit 1
fi
for node_entry in "${node_entries[@]}"; do
IFS=$'\t' read -r node_host node_user node_name node_key_path <<<"${node_entry}"
echo "Refreshing containerd local-registry config on ${node_name} (${node_user}@${node_host})..."
refresh_lab_ssh_known_host "${node_host}"
ssh -i "${node_key_path}" -o BatchMode=yes -o ConnectTimeout=10 -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new "${node_user}@${node_host}" \
"REGISTRY_ENDPOINT='${registry_endpoint}' bash -s" <<'PIMOX_CONTAINERD_EOF'
set -eu
registry_endpoint="${REGISTRY_ENDPOINT:?}"
changed=0
config_bootstrapped=0
hosts_changed=0
original_config_tmp=""
containerd_config_version() {
awk -F= '
/^[[:space:]]*version[[:space:]]*=/ {
gsub(/[[:space:]]/, "", $2)
print $2
exit
}
' /etc/containerd/config.toml
}
containerd_uses_cri_v1_images() {
local containerd_version
containerd_version="$(containerd --version 2>/dev/null | awk '{print $3}')"
case "${containerd_version}" in
v2.*|2.*)
return 0
;;
esac
[ "$(containerd_config_version)" = "3" ]
}
reset_containerd_registry_tables() {
sudo awk '
function is_registry_table(line) {
return line ~ /^[[:space:]]*\[plugins\./ &&
line ~ /[.]registry([.\]]|$)/ &&
(line ~ /io[.]containerd[.]grpc[.]v1[.]cri/ ||
line ~ /io[.]containerd[.]cri[.]v1[.]images/)
}
is_registry_table($0) { skip = 1; next }
skip && /^[[:space:]]*\[/ { skip = 0 }
!skip { print }
' /etc/containerd/config.toml | sudo tee /etc/containerd/config.toml.homelab >/dev/null
if ! sudo cmp -s /etc/containerd/config.toml.homelab /etc/containerd/config.toml; then
sudo mv /etc/containerd/config.toml.homelab /etc/containerd/config.toml
changed=1
else
sudo rm -f /etc/containerd/config.toml.homelab
fi
}
ensure_containerd_registry_config_path() {
plugin="$1"
append_section="$2"
sudo awk -v plugin="$plugin" -v append_section="$append_section" '
function is_table(line) {
return line ~ /^[[:space:]]*\[/
}
function is_target_registry(line) {
return is_table(line) &&
index(line, plugin) > 0 &&
line ~ /[.]registry[[:space:]]*\]/
}
BEGIN {
in_target = 0
found = 0
wrote = 0
}
is_target_registry($0) {
if (in_target && !wrote) {
print " config_path = \"/etc/containerd/certs.d\""
}
in_target = 1
wrote = 0
found = 1
print
next
}
in_target && is_table($0) {
if (!wrote) {
print " config_path = \"/etc/containerd/certs.d\""
}
in_target = 0
wrote = 0
}
in_target && $0 ~ /^[[:space:]]*config_path[[:space:]]*=/ {
print " config_path = \"/etc/containerd/certs.d\""
wrote = 1
next
}
{ print }
END {
if (in_target && !wrote) {
print " config_path = \"/etc/containerd/certs.d\""
}
if (!found) {
print ""
print append_section
print " config_path = \"/etc/containerd/certs.d\""
}
}
' /etc/containerd/config.toml | sudo tee /etc/containerd/config.toml.homelab >/dev/null
if ! sudo cmp -s /etc/containerd/config.toml.homelab /etc/containerd/config.toml; then
sudo mv /etc/containerd/config.toml.homelab /etc/containerd/config.toml
changed=1
else
sudo rm -f /etc/containerd/config.toml.homelab
fi
}
sudo mkdir -p /etc/containerd "/etc/containerd/certs.d/${registry_endpoint}"
if ! sudo test -s /etc/containerd/config.toml; then
sudo containerd config default | sudo tee /etc/containerd/config.toml >/dev/null
config_bootstrapped=1
fi
original_config_tmp="$(mktemp)"
sudo cp /etc/containerd/config.toml "${original_config_tmp}"
reset_containerd_registry_tables
hosts_tmp="$(mktemp)"
cat >"${hosts_tmp}" <<REGISTRY_HOSTS_EOF
server = "http://${registry_endpoint}"
[host."http://${registry_endpoint}"]
capabilities = ["pull", "resolve", "push"]
skip_verify = true
REGISTRY_HOSTS_EOF
if ! sudo test -f "/etc/containerd/certs.d/${registry_endpoint}/hosts.toml" ||
! sudo cmp -s "${hosts_tmp}" "/etc/containerd/certs.d/${registry_endpoint}/hosts.toml"; then
sudo cp "${hosts_tmp}" "/etc/containerd/certs.d/${registry_endpoint}/hosts.toml"
hosts_changed=1
fi
rm -f "${hosts_tmp}"
if containerd_uses_cri_v1_images; then
ensure_containerd_registry_config_path "io.containerd.cri.v1.images" '[plugins."io.containerd.cri.v1.images".registry]'
else
ensure_containerd_registry_config_path "io.containerd.grpc.v1.cri" '[plugins."io.containerd.grpc.v1.cri".registry]'
fi
sudo tee /etc/crictl.yaml >/dev/null <<'CRICTL_EOF'
runtime-endpoint: unix:///run/containerd/containerd.sock
image-endpoint: unix:///run/containerd/containerd.sock
timeout: 10
debug: false
CRICTL_EOF
sudo containerd config dump >/dev/null
changed=0
if [ "${config_bootstrapped}" = "1" ] ||
[ "${hosts_changed}" = "1" ] ||
! sudo cmp -s "${original_config_tmp}" /etc/containerd/config.toml; then
changed=1
fi
rm -f "${original_config_tmp}"
if [ "${changed}" = "1" ]; then
sudo systemctl restart containerd
sudo systemctl restart kubelet
else
echo "containerd local-registry config already current for ${registry_endpoint}"
fi
PIMOX_CONTAINERD_EOF
done
}
ensure_pimox_node_ephemeral_storage_headroom() {
local enabled="${LAB_PIMOX_NODE_STORAGE_CLEANUP:-true}"
local cp_host="${LAB_CLUSTER_CONTROL_PLANE_LAN_IP:-}"
local cp_user="${LAB_CLUSTER_CONTROL_PLANE_USER:-jv}"
local cp_node="${LAB_CLUSTER_CONTROL_PLANE_NODE_NAME:-pimox-cp-01}"
local cp_key="${LAB_CLUSTER_CONTROL_PLANE_SSH_KEY_PATH:-/home/jv/.ssh/id_ed25519}"
local spec_file="${REPO_ROOT}/.lab/pimox-workers.tsv"
local max_log_size="${LAB_PIMOX_NODE_LOG_MAX_SIZE:-200M}"
local journal_size="${LAB_PIMOX_NODE_JOURNAL_MAX_SIZE:-200M}"
local -a node_entries=()
local worker_key
local worker_host
local worker_user
local worker_node
local worker_key_path
local node_entry
local node_host
local node_user
local node_name
local node_key_path
if [[ "${LAB_CLUSTER_PROFILE:-debian}" != "pimox" ]]; then
return 0
fi
if disabled_value "${enabled}"; then
echo "Skipping Pimox node ephemeral-storage cleanup because LAB_PIMOX_NODE_STORAGE_CLEANUP=${enabled}."
return 0
fi
if ! truthy "${enabled}"; then
echo "LAB_PIMOX_NODE_STORAGE_CLEANUP must be true or false." >&2
exit 1
fi
if [[ ! "${max_log_size}" =~ ^[0-9]+[KMG]?$ || ! "${journal_size}" =~ ^[0-9]+[KMG]?$ ]]; then
echo "LAB_PIMOX_NODE_LOG_MAX_SIZE and LAB_PIMOX_NODE_JOURNAL_MAX_SIZE must be size values like 200M." >&2
exit 1
fi
if [[ -n "${cp_host}" ]]; then
node_entries+=("${cp_host}"$'\t'"${cp_user}"$'\t'"${cp_node}"$'\t'"${cp_key}")
fi
if [[ -s "${spec_file}" ]]; then
while IFS=$'\t' read -r worker_key worker_host worker_user worker_node worker_key_path; do
[[ -n "${worker_host}" && -n "${worker_user}" && -n "${worker_node}" && -n "${worker_key_path}" ]] || continue
node_entries+=("${worker_host}"$'\t'"${worker_user}"$'\t'"${worker_node}"$'\t'"${worker_key_path}")
done <"${spec_file}"
fi
if ((${#node_entries[@]} == 0)); then
echo "Could not resolve Pimox nodes for ephemeral-storage cleanup." >&2
exit 1
fi
for node_entry in "${node_entries[@]}"; do
IFS=$'\t' read -r node_host node_user node_name node_key_path <<<"${node_entry}"
echo "Ensuring ephemeral-storage headroom on ${node_name} (${node_user}@${node_host})..."
refresh_lab_ssh_known_host "${node_host}"
ssh -i "${node_key_path}" -o BatchMode=yes -o ConnectTimeout=10 -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new "${node_user}@${node_host}" \
"LAB_PIMOX_NODE_LOG_MAX_SIZE='${max_log_size}' LAB_PIMOX_NODE_JOURNAL_MAX_SIZE='${journal_size}' bash -s" <<'PIMOX_NODE_STORAGE_EOF'
set -eu
echo "-- before --"
df -h / /var/lib/containerd 2>/dev/null || df -h /
if command -v crictl >/dev/null 2>&1; then
sudo crictl ps -a --state Exited -q 2>/dev/null | xargs -r sudo crictl rm 2>/dev/null || true
sudo crictl rmi --prune 2>/dev/null || true
fi
if command -v journalctl >/dev/null 2>&1; then
sudo journalctl --vacuum-size="${LAB_PIMOX_NODE_JOURNAL_MAX_SIZE:-200M}" >/dev/null 2>&1 || true
fi
for log_dir in /var/log/pods /var/log/containers; do
if [ -d "${log_dir}" ]; then
sudo find "${log_dir}" -type f -name '*.log' -size +"${LAB_PIMOX_NODE_LOG_MAX_SIZE:-200M}" -print -exec truncate -s 0 {} \; 2>/dev/null || true
fi
done
echo "-- after --"
df -h / /var/lib/containerd 2>/dev/null || df -h /
PIMOX_NODE_STORAGE_EOF
done
}
apps() (
local app_selector="${1:-all}"
local app_ready_wait_seconds="${LAB_APPS_READY_WAIT_SECONDS:-600}"
local app_resource_wait_seconds="${LAB_APPS_RESOURCE_WAIT_SECONDS:-120}"
local buildx_builder_ready=false
local demos_image_built=false
local demos_image_ref
local demos_image_state_file
local demos_platforms
local demos_registry_endpoint
local demos_source_hash
local registry_endpoint
local website_image_built=false
local website_image_ref
local website_image_state_file
local website_platforms
local website_source_hash
local website_build_root=""
local -a app_targets=()
local deploy_demos=false
local deploy_registry=false
local deploy_supply_chain=false
local deploy_website=false
case "${app_selector}" in
all)
deploy_demos=true
deploy_website=true
;;
website)
deploy_website=true
app_targets=('kubernetes_manifest.argocd_application["website-production"]')
;;
demos-static)
deploy_demos=true
app_targets=('kubernetes_manifest.argocd_application["demos-static"]')
;;
container-registry)
deploy_registry=true
app_targets=('kubernetes_manifest.argocd_application["container-registry"]')
;;
supply-chain-policy)
deploy_supply_chain=true
app_targets=('kubernetes_manifest.argocd_application["supply-chain-policy"]')
;;
heimdall)
app_targets=('kubernetes_manifest.argocd_application["heimdall"]')
;;
n8n)
app_targets=('kubernetes_manifest.argocd_application["n8n"]')
;;
gitea-runner)
app_targets=('kubernetes_manifest.argocd_application["gitea-runner"]')
;;
*)
echo "Unknown app '${app_selector}'. Use all, website, demos-static, container-registry, supply-chain-policy, heimdall, n8n, or gitea-runner." >&2
return 2
;;
esac
require_debian_server "apps"
if [[ "${deploy_website}" == "true" ]]; then
website_build_root="$(mktemp -d "${TMPDIR:-/tmp}/jeannie-website.XXXXXXXX")" || return 1
trap 'rm -rf -- "${website_build_root}"' EXIT
mkdir -p "${website_build_root}/apps" || return 1
cp -a "${REPO_ROOT}/apps/website" "${website_build_root}/apps/website" || return 1
python3 "${REPO_ROOT}/scripts/render-website-architecture.py" --output "${website_build_root}/apps/website/architecture/homelab.svg" || return 1
python3 "${REPO_ROOT}/scripts/render-website-tree.py" --output "${website_build_root}/apps/website/architecture/tree-data.json" || return 1
fi
registry_endpoint="$(apps_registry_endpoint)"
demos_registry_endpoint="$(demos_registry_endpoint)"
demos_image_state_file="${REPO_ROOT}/.lab/demos-static-image.state"
demos_platforms="${DEMOS_IMAGE_PLATFORMS:-linux/amd64,linux/arm64}"
demos_source_hash="$(demos_source_hash)"
demos_image_ref="${registry_endpoint}/demos-static:${DEMOS_IMAGE_TAG:-$(demos_image_tag "${demos_source_hash}")}"
website_image_state_file="${REPO_ROOT}/.lab/php-website-image.state"
website_platforms="${WEBSITE_IMAGE_PLATFORMS:-linux/amd64,linux/arm64}"
website_source_hash="$(website_source_hash "${website_build_root:-${REPO_ROOT}}")"
website_image_ref="${registry_endpoint}/php-website:${WEBSITE_IMAGE_TAG:-$(website_image_tag "${website_source_hash}")}"
export TF_VAR_registry_endpoint="${TF_VAR_registry_endpoint:-${registry_endpoint}}"
export TF_VAR_website_image_ref="${TF_VAR_website_image_ref:-${website_image_ref}}"
export TF_VAR_demos_image_ref="${TF_VAR_demos_image_ref:-${demos_image_ref}}"
export TF_VAR_kubeconfig_path="${TF_VAR_kubeconfig_path:-${KUBECONFIG_PATH}}"
export KUBECONFIG_PATH="${TF_VAR_kubeconfig_path}"
ensure_pimox_kubeconfig
cluster_context_require || return 1
# This exact policy must not prevent its registry/verifier from recovering
# when admission or image storage is unavailable. Preserve all other scope.
python3 "${REPO_ROOT}/scripts/supply-chain-bootstrap-reconcile.py" \
--kubeconfig "${KUBECONFIG_PATH}" \
--state-dir "${HOMELAB_STATE_DIR}/clusters/${LAB_CLUSTER_PROFILE}" || return 1
require_argocd_application_controller || return 1
require_pimox_app_worker_capacity "${app_selector}"
if [[ "${deploy_website}" == "true" || "${deploy_demos}" == "true" || "${deploy_registry}" == "true" ]]; then
reconcile_app_registry_storage || return 1
ensure_pimox_registry_storage_path
ensure_pimox_registry_endpoint_forwarding "${registry_endpoint}"
ensure_pimox_containerd_registry_refresh "${registry_endpoint}"
ensure_pimox_node_ephemeral_storage_headroom
ensure_cosign_keypair
publish_cosign_public_key_config_map
fi
if [[ "${TF_VAR_registry_endpoint}" != "${registry_endpoint}" ]]; then
echo "TF_VAR_registry_endpoint changed after registry endpoint resolution (${registry_endpoint})" >&2
exit 1
fi
if [[ "${deploy_website}" == "true" || "${deploy_demos}" == "true" ]]; then
if [[ "${TF_VAR_website_image_ref}" != "${website_image_ref}" ]]; then
echo "TF_VAR_website_image_ref must match the buildx website image ref (${website_image_ref})" >&2
exit 1
fi
if [[ "${TF_VAR_demos_image_ref}" != "${demos_image_ref}" ]]; then
echo "TF_VAR_demos_image_ref must match the buildx demos image ref (${demos_image_ref})" >&2
exit 1
fi
if [[ "${demos_registry_endpoint}" != "${registry_endpoint}" ]]; then
echo "apps/demos-static/web-app.yaml registry endpoint (${demos_registry_endpoint}) must match app registry endpoint (${registry_endpoint})" >&2
exit 1
fi
if [[ "${deploy_website}" == "true" && "$(image_ref_tag "${website_image_ref}")" == "latest" ]]; then
echo "apps/website/web-app.yaml must use an immutable php-website image tag, not latest." >&2
exit 1
fi
if [[ "${deploy_demos}" == "true" && "$(image_ref_tag "${demos_image_ref}")" == "latest" ]]; then
echo "apps/demos-static/web-app.yaml must use an immutable demos-static image tag, not latest." >&2
exit 1
fi
if [[ "${deploy_website}" == "true" ]]; then
ensure_website_image_tag_not_reused "${website_image_state_file}" "${website_source_hash}" "${website_image_ref}"
fi
fi
echo "Deploying homelab applications..."
if ((${#app_targets[@]})); then
run_tofu_stack "bootstrap/apps" "${app_targets[@]}" || return 1
else
run_tofu_stack "bootstrap/apps" || return 1
fi
if [[ "${app_selector}" == "all" || "${deploy_registry}" == "true" || "${deploy_supply_chain}" == "true" ]]; then
if [[ "${app_selector}" == "all" || "${deploy_registry}" == "true" ]]; then
refresh_argocd_application container-registry
fi
if [[ "${app_selector}" == "all" || "${deploy_supply_chain}" == "true" ]]; then
refresh_argocd_application supply-chain-policy
fi
fi
if [[ "${app_selector}" == "all" || "${deploy_registry}" == "true" || "${deploy_supply_chain}" == "true" || "${deploy_website}" == "true" || "${deploy_demos}" == "true" ]]; then
wait_for_cluster_resource imagevalidatingpolicies.policies.kyverno.io homelab-local-registry-supply-chain supply-chain-policy "${app_resource_wait_seconds}"
fi
if [[ "${app_selector}" == "all" || "${deploy_registry}" == "true" || "${deploy_website}" == "true" || "${deploy_demos}" == "true" ]]; then
wait_for_namespace container-registry container-registry "${app_resource_wait_seconds}"
wait_for_namespaced_resource container-registry deployment local-registry container-registry "${app_resource_wait_seconds}"
wait_for_deployment_ready container-registry local-registry container-registry "${app_ready_wait_seconds}"
fi
if [[ "${deploy_website}" == "true" ]]; then
if website_image_is_current "${website_image_state_file}" "${website_source_hash}" "${website_platforms}" "${website_image_ref}" "${registry_endpoint}" &&
image_supply_chain_metadata_exists "${website_image_ref}" "${registry_endpoint}"; then
echo "Website image ${website_image_ref} is already current (${website_source_hash}); skipping build."
else
echo "Building website image ${website_image_ref} for ${website_platforms} (${website_source_hash})..."
ensure_docker_build_space
if [[ "${buildx_builder_ready}" != "true" ]]; then
prepare_buildx_builder "${registry_endpoint}"
buildx_builder_ready=true
fi
if ! docker buildx build \
--network host \
--platform "${website_platforms}" \
--provenance=false \
--sbom=true \
--label "dev.homelab.website.source-hash=${website_source_hash}" \
-t "${website_image_ref}" \
-f "${website_build_root}/apps/website/Dockerfile" \
"${website_build_root}/apps/website/" \
--push; then
echo "Website image build failed for ${website_image_ref}; not publishing supply-chain metadata." >&2
return 1
fi
website_image_built=true
fi
publish_image_supply_chain_metadata "${website_image_ref}" "${registry_endpoint}" "${website_source_hash}"
fi
if [[ "${deploy_demos}" == "true" ]]; then
if demos_image_is_current "${demos_image_state_file}" "${demos_source_hash}" "${demos_platforms}" "${demos_image_ref}" "${registry_endpoint}" &&
image_supply_chain_metadata_exists "${demos_image_ref}" "${registry_endpoint}"; then
echo "Demos image ${demos_image_ref} is already current (${demos_source_hash}); skipping build."
else
echo "Building demos image ${demos_image_ref} for ${demos_platforms} (${demos_source_hash})..."
ensure_docker_build_space
if [[ "${buildx_builder_ready}" != "true" ]]; then
prepare_buildx_builder "${registry_endpoint}"
buildx_builder_ready=true
fi
if ! docker buildx build \
--network host \
--platform "${demos_platforms}" \
--provenance=false \
--sbom=true \
--label "dev.homelab.demos.source-hash=${demos_source_hash}" \
-t "${demos_image_ref}" \
-f "${REPO_ROOT}/apps/demos-static/Dockerfile" \
"${REPO_ROOT}/apps/demos-static/" \
--push; then
echo "Demos image build failed for ${demos_image_ref}; not publishing supply-chain metadata." >&2
return 1
fi
demos_image_built=true
fi
publish_image_supply_chain_metadata "${demos_image_ref}" "${registry_endpoint}" "${demos_source_hash}"
fi
if [[ "${deploy_website}" == "true" ]]; then
refresh_argocd_application website-production
wait_for_namespace website-production website-production "${app_resource_wait_seconds}"
wait_for_namespaced_resource website-production deployment php-website-deployment website-production "${app_resource_wait_seconds}"
ensure_deployment_container_image website-production php-website-deployment php-app "${website_image_ref}" website-production
# Immutable image changes already trigger the Deployment rolling update.
# Keep healthy pods in place when retrying an unchanged app deployment.
wait_for_deployment_ready website-production php-website-deployment website-production "${app_ready_wait_seconds}"
if [[ "${website_image_built}" == "true" ]]; then
write_website_image_state "${website_image_state_file}" "${website_source_hash}" "${website_platforms}" "${website_image_ref}"
fi
fi
if [[ "${deploy_demos}" == "true" ]]; then
refresh_argocd_application demos-static
wait_for_namespace demos-static demos-static "${app_resource_wait_seconds}"
wait_for_namespaced_resource demos-static deployment demos-static demos-static "${app_resource_wait_seconds}"
ensure_deployment_container_image demos-static demos-static demos-static "${demos_image_ref}" demos-static
wait_for_deployment_ready demos-static demos-static demos-static "${app_ready_wait_seconds}"
if [[ "${demos_image_built}" == "true" ]]; then
write_demos_image_state "${demos_image_state_file}" "${demos_source_hash}" "${demos_platforms}" "${demos_image_ref}"
fi
fi
if [[ "${app_selector}" == "all" || "${app_selector}" == "heimdall" ]]; then
refresh_argocd_application heimdall
wait_for_namespaced_resource monitoring ingress grafana heimdall "${app_resource_wait_seconds}"
wait_for_namespaced_resource monitoring ingress prometheus heimdall "${app_resource_wait_seconds}"
wait_for_namespaced_resource monitoring ingress alertmanager heimdall "${app_resource_wait_seconds}"
wait_for_namespaced_resource argocd ingress argocd-server heimdall "${app_resource_wait_seconds}"
fi
if [[ "${app_selector}" == "all" || "${app_selector}" == "n8n" ]]; then
refresh_argocd_application n8n
wait_for_namespace n8n n8n "${app_resource_wait_seconds}"
wait_for_namespaced_resource n8n deployment n8n n8n "${app_resource_wait_seconds}"
wait_for_deployment_ready n8n n8n n8n "${app_ready_wait_seconds}"
fi
if [[ "${app_selector}" == "all" || "${app_selector}" == "gitea-runner" ]]; then
refresh_argocd_application gitea-runner
wait_for_namespace gitea-runner gitea-runner "${app_resource_wait_seconds}"
wait_for_namespaced_resource gitea-runner deployment gitea-runner gitea-runner "${app_resource_wait_seconds}"
local runner_replicas
runner_replicas="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" -n gitea-runner get deployment gitea-runner -o jsonpath='{.spec.replicas}')" || return 1
if [[ "${runner_replicas}" == 0 ]]; then
echo "Gitea Kubernetes runner is disabled (zero replicas); readiness wait skipped."
else
apply_gitea_runner_secret_file
wait_for_deployment_ready gitea-runner gitea-runner gitea-runner "${app_ready_wait_seconds}"
fi
fi
echo "Application deployment successfully completed."
remember_cluster_profile || return 1
)
platform_apply() {
require_debian_server "platform"
# OCI foundation persists discovered VM addresses after apply. Load those
# values before rendering the monitoring scrape configuration.
if declare -F oci_foundation_load_config >/dev/null 2>&1; then
oci_foundation_load_config
unset TF_VAR_oci_edge_metrics_target TF_VAR_oci_edge_container_metrics_target TF_VAR_oci_email_metrics_target
export_homelab_inventory_tf_vars
fi
local component="${1:-all}"
local -a targets=()
if [[ "${component}" == "all" || "${component}" == "monitoring" ]]; then
cluster_runtime_require || return 1
cluster_context_require || return 1
if truthy "${LAB_MONITORING_MANAGE_HOST_EXPORTERS:-true}"; then
echo "Preparing node exporters on Debian and the Orange Pi host..."
if ! bash "${REPO_ROOT}/scripts/monitoring-host-exporter.sh"; then
echo "Debian node exporter setup failed; its monitoring target may be down." >&2
fi
if ! ssh -T -i "${LAB_PIMOX_SSH_KEY_PATH:-${HOME}/.ssh/id_ed25519}" \
-o BatchMode=yes -o IdentitiesOnly=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new \
"${LAB_PIMOX_USER:-jv}@${LAB_PIMOX_HOST:-192.168.100.80}" \
'bash -s' <"${REPO_ROOT}/scripts/monitoring-host-exporter.sh"; then
echo "Orange Pi node exporter setup failed; its monitoring target may be down." >&2
fi
if ! bash "${REPO_ROOT}/scripts/monitoring-compose-exporter.sh" "${LAB_DEBIAN_LAN_IP:-192.168.100.73}"; then
echo "Debian Docker Compose metrics setup failed; its monitoring target may be down." >&2
fi
local rpi_metrics_ip="${LAB_RPI_HOST:-192.168.100.89}"
if [[ ! "${rpi_metrics_ip}" =~ ^[0-9.]+$ ]] || ! ssh -T -i "${LAB_RPI_SSH_KEY_PATH:-${LAB_RASPBERRY_SSH_KEY_PATH:-${HOME}/.ssh/id_ed25519}}" \
-o BatchMode=yes -o IdentitiesOnly=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new \
"${LAB_RPI_USER:-jv}@${rpi_metrics_ip}" \
"bash -s -- '${rpi_metrics_ip}'" <"${REPO_ROOT}/scripts/monitoring-compose-exporter.sh"; then
echo "RPi Docker Compose metrics setup failed; its monitoring target may be down." >&2
fi
fi
fi
case "${component}" in
all)
;;
calico)
targets=(
helm_release.calico_crds
null_resource.calico_helm_recovery
helm_release.calico
null_resource.calico_ready
)
;;
metrics)
targets=(helm_release.metrics_server null_resource.metrics_server_ready)
;;
dns)
targets=(
kubernetes_manifest.nodelocal_dns_service_account
kubernetes_manifest.nodelocal_dns_upstream_service
kubernetes_manifest.nodelocal_dns_config_map
kubernetes_manifest.nodelocal_dns_daemonset
kubernetes_manifest.nodelocal_dns_metrics_service
)
;;
metallb)
targets=(helm_release.metallb null_resource.metallb_l2_config)
;;
ingress)
targets=(helm_release.traefik)
;;
storage)
targets=(helm_release.openebs kubernetes_storage_class_v1.openebs_hostpath_retain)
;;
argocd)
targets=(helm_release.argocd null_resource.argocd_ready null_resource.argocd_private_repo)
;;
security)
targets=(
null_resource.kyverno_helm_recovery
helm_release.kyverno
helm_release.kyverno_policies
)
;;
logging)
targets=(helm_release.loki helm_release.promtail)
;;
monitoring)
targets=(
kubernetes_namespace_v1.monitoring
helm_release.mimir
null_resource.prometheus_stack_helm_recovery
helm_release.prometheus_stack
null_resource.prometheus_stack_readiness
kubernetes_config_map.grafana_dashboards
)
;;
tools)
targets=(helm_release.extra_tools)
;;
*)
echo "Unknown platform component '${component}'. Use all, calico, metrics, dns, metallb, ingress, storage, argocd, security, logging, monitoring, or tools." >&2
return 2
;;
esac
run_tofu_stack "bootstrap/platform" "${targets[@]}" || return 1
# Provisioners only execute when their triggers change. Verify live
# monitoring health even when OpenTofu reports an unchanged stack.
if [[ "${component}" == "all" || "${component}" == "monitoring" ]]; then
local monitoring_namespace
monitoring_namespace="$(tofu -chdir="${REPO_ROOT}/bootstrap/platform" output -raw monitoring_namespace)" || return 1
local -a monitoring_flags=()
if truthy "${LAB_MONITORING_EXTERNAL:-false}"; then monitoring_flags=(--external); fi
python3 "${REPO_ROOT}/scripts/monitoring-readiness.py" \
--kubeconfig "${KUBECONFIG_PATH}" --namespace "${monitoring_namespace}" \
--recover-stale-pending "${monitoring_flags[@]}" || return 1
if truthy "${LAB_MONITORING_EXTERNAL:-false}"; then monitoring_debian apply || return 1; fi
fi
remember_cluster_profile || return 1
}
prepare_edge_connection() {
# The remote API is a long-lived service and does not inherit the shell's
# OCI exports. Load the persisted foundation inputs before endpoint
# discovery so recreated instances are resolved before any SSH connection.
if declare -F oci_foundation_load_config >/dev/null 2>&1; then
oci_foundation_load_config
fi
local requested_transport="${LAB_EDGE_SSH_TRANSPORT:-auto}"
local configured_edge_key="${LAB_EDGE_SSH_KEY_PATH:-${LAB_OCI_SSH_PRIVATE_KEY:-}}"
if [[ -n "${configured_edge_key}" ]]; then
export TF_VAR_edge_ssh_key_path="${configured_edge_key}"
fi
refresh_oci_edge_endpoint || return 1
if [[ "${LAB_EDGE_RESOLVED_SSH_TRANSPORT:-${requested_transport}}" == "bastion" ]]; then
oci_ensure_edge_bastion_ingress || return 1
prepare_oci_edge_bastion || return 1
fi
edge_require_ssh_transport || return 1
edge_ssh_args
local ssh_host="${TF_VAR_edge_ssh_host}" ssh_user="${TF_VAR_edge_user:-${LAB_EDGE_USER:-ubuntu}}"
# One bounded authentication check gives a useful error before OpenTofu
# can retry the same inaccessible host for several minutes.
if ! ssh "${EDGE_SSH_ARGS[@]}" "${ssh_user}@${ssh_host}" true; then
if [[ "${requested_transport}" != auto || "${LAB_EDGE_RESOLVED_SSH_TRANSPORT:-}" != tailscale ]]; then
return 1
fi
echo "Tailscale SSH preflight failed; trying OCI Bastion private access." >&2
local resolved_bastion
resolved_bastion="$(LAB_EDGE_SSH_TRANSPORT=bastion python3 "${REPO_ROOT}/scripts/oci-foundation-resolve.py" edge --repo "${REPO_ROOT}")" || return 1
eval "${resolved_bastion}"
oci_ensure_edge_bastion_ingress || return 1
prepare_oci_edge_bastion || return 1
edge_require_ssh_transport || return 1
edge_ssh_args
ssh_host="${TF_VAR_edge_ssh_host}"
ssh "${EDGE_SSH_ARGS[@]}" "${ssh_user}@${ssh_host}" true || return 1
fi
}
edge_apply() {
require_debian_server "edge"
local LAB_EDGE_DEFER_TAILSCALE_ROUTES=false
export LAB_EDGE_DEFER_TAILSCALE_ROUTES
prepare_edge_connection || return 1
local ssh_host="${TF_VAR_edge_ssh_host}" ssh_user="${TF_VAR_edge_user:-${LAB_EDGE_USER:-ubuntu}}"
if ! ssh "${EDGE_SSH_ARGS[@]}" "${ssh_user}@${ssh_host}" \
'command -v tailscale >/dev/null 2>&1 && test -n "$(tailscale ip -4 2>/dev/null)"'; then
echo "Edge Tailscale is not ready; route reconciliation will follow bootstrap."
LAB_EDGE_DEFER_TAILSCALE_ROUTES=true
if ssh "${EDGE_SSH_ARGS[@]}" "${ssh_user}@${ssh_host}" 'command -v tailscale >/dev/null 2>&1'; then
local edge_auth_key="${TF_VAR_edge_tailscale_auth_key:-}"
local edge_tag="${TF_VAR_edge_tailscale_tag:-tag:homelab-edge}"
if [[ -z "${edge_auth_key}" ]]; then
echo "Tailscale is installed but not connected. Provide LAB_EDGE_TAILSCALE_AUTH_KEY or the configured OAuth credential file." >&2
return 1
fi
if [[ ! "${edge_tag}" =~ ^tag:[a-zA-Z0-9-]+$ ]]; then
echo "Invalid edge Tailscale tag." >&2
return 1
fi
echo "Reconnecting edge Tailscale through the authenticated private management path..."
if ! printf '%s' "${edge_auth_key}" | ssh "${EDGE_SSH_ARGS[@]}" "${ssh_user}@${ssh_host}" \
"sudo -n sh -c 'set -eu; umask 077; key_file=\$(mktemp /run/jeannie-edge-ts.XXXXXX); trap '\''rm -f \"\$key_file\"'\'' EXIT; cat >\"\$key_file\"; systemctl start tailscaled; tailscale up --auth-key=\"file:\$key_file\" --hostname=homelab-oci-edge --advertise-tags=\"\$1\" --accept-routes' sh '${edge_tag}'"; then
echo "Could not reconnect edge Tailscale; check the private management path and auth key." >&2
return 1
fi
fi
fi
run_tofu_stack "bootstrap/edge" || return 1
if [[ "${LAB_EDGE_DEFER_TAILSCALE_ROUTES}" == true ]]; then
ensure_edge_tailscale_routes || return 1
fi
# OpenTofu does not rerun provisioners when inputs are unchanged. Reconcile
# stopped containers and check the deployed proxy without recreating them.
edge_ssh_args
local install_dir="${TF_VAR_edge_install_dir:-${LAB_EDGE_INSTALL_DIR:-/opt/homelab-edge}}"
local edge_server_name="${TF_VAR_server_name:-${LAB_DOMAIN:-}}"
if [[ "${install_dir}" == *"'"* ]]; then
echo "Invalid edge install directory." >&2
return 1
fi
if [[ ! "${edge_server_name}" =~ ^[a-zA-Z0-9][a-zA-Z0-9.-]*$ ]]; then
echo "A valid edge server hostname is required for the HTTPS health check." >&2
return 1
fi
ssh "${EDGE_SSH_ARGS[@]}" "${ssh_user}@${ssh_host}" \
"cd '${install_dir}' && sudo docker compose up -d --no-recreate &&
sudo docker compose exec -T nginx-dev nginx -t &&
status=\$(curl --noproxy '*' -kfsS --connect-timeout 5 --max-time 10 \
--resolve '${edge_server_name}:443:127.0.0.1' \
-o /dev/null -w '%{http_code}' 'https://${edge_server_name}/edge-health') &&
printf 'edge-health=%s\n' \"\$status\" &&
test \"\$status\" = 204" || return 1
local edge_host="${TF_VAR_edge_host:-${LAB_EDGE_HOST:-}}"
if [[ -n "${edge_host}" ]] && declare -F update_duckdns_edge_ip >/dev/null 2>&1; then
update_duckdns_edge_ip "${edge_host}"
fi
# Flushing caches restarts services on otherwise unchanged applies.
if truthy "${LAB_EDGE_FLUSH_CACHES_AFTER_APPLY:-false}"; then
edge_flush_caches
fi
return 0
}
refresh_oci_edge_endpoint() {
local resolved
unset LAB_EDGE_RESOLVED_SSH_TRANSPORT
unset TF_VAR_edge_ssh_host TF_VAR_edge_bastion_host TF_VAR_edge_bastion_user
unset TF_VAR_edge_bastion_port TF_VAR_edge_bastion_private_key_path
unset LAB_OCI_EDGE_BASTION_PROXY_COMMAND LAB_OCI_EDGE_BASTION_SESSION_ID
resolved="$(python3 "${REPO_ROOT}/scripts/oci-foundation-resolve.py" edge \
--repo "${REPO_ROOT}")" || return 1
eval "${resolved}"
oci_foundation_save_config
}
oci_ensure_edge_bastion_ingress() {
local oci_bin=""
local edge_instance="${LAB_OCI_EDGE_INSTANCE_ID:-}"
local edge_compartment="${LAB_OCI_EDGE_COMPARTMENT_ID:-${LAB_OCI_COMPARTMENT_ID:-}}"
local vnic_id=""
local nsg_ids=""
local bastion_subnet="${LAB_OCI_BASTION_TARGET_SUBNET_ID:-}"
local source_cidr="${LAB_OCI_BASTION_SSH_SOURCE_CIDR:-}"
local nsg rule_file has_rule
if [[ "${LAB_OCI_BASTION_ENABLED:-true}" == "false" || -z "${LAB_OCI_BASTION_ID:-}" ]]; then
return 0
fi
if [[ -z "${edge_instance}" || -z "${edge_compartment}" ]]; then
echo "Cannot ensure Bastion ingress: edge instance compartment is unknown." >&2
return 1
fi
oci_bin="$(oci_cli_resolve 2>/dev/null || true)"
if [[ -z "${oci_bin}" ]]; then
echo "OCI CLI is required to ensure Bastion ingress." >&2
return 1
fi
if [[ -z "${bastion_subnet}" ]]; then
bastion_subnet="$("${oci_bin}" bastion bastion get \
--bastion-id "${LAB_OCI_BASTION_ID}" \
--query 'data."target-subnet-id"' --raw-output 2>/dev/null || true)"
fi
if [[ -z "${source_cidr}" && "${bastion_subnet}" != "null" ]]; then
source_cidr="$("${oci_bin}" network subnet get \
--subnet-id "${bastion_subnet}" \
--query 'data."cidr-block"' --raw-output 2>/dev/null || true)"
fi
if [[ -z "${source_cidr}" || "${source_cidr}" == "null" ]]; then
echo "Cannot ensure Bastion ingress: target subnet CIDR is unavailable." >&2
return 1
fi
if ! python3 -c 'import ipaddress,sys
try:
n=ipaddress.ip_network(sys.argv[1], strict=True)
ranges=[ipaddress.ip_network(x) for x in ("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16")]
sys.exit(0 if n.version==4 and any(n.subnet_of(r) for r in ranges) else 1)
except ValueError:
sys.exit(1)' "${source_cidr}"; then
echo "Refusing Bastion SSH ingress: source must be a private IPv4 subnet, not ${source_cidr}." >&2
return 1
fi
vnic_id="$("${oci_bin}" compute vnic-attachment list \
--compartment-id "${edge_compartment}" \
--instance-id "${edge_instance}" \
--query 'data[0]."vnic-id"' --raw-output 2>/dev/null || true)"
if [[ -z "${vnic_id}" || "${vnic_id}" == "null" ]]; then
echo "Cannot ensure Bastion ingress: edge VNIC was not found." >&2
return 1
fi
nsg_ids="$("${oci_bin}" network vnic get --vnic-id "${vnic_id}" --output json 2>/dev/null \
| python3 -c 'import json,sys
data=json.load(sys.stdin).get("data", {})
print("\\n".join(data.get("nsg-ids") or []))' 2>/dev/null || true)"
if [[ -z "${nsg_ids}" ]]; then
echo "Cannot ensure Bastion ingress: edge VNIC has no NSG." >&2
return 1
fi
while IFS= read -r nsg; do
[[ -n "${nsg}" ]] || continue
has_rule="$("${oci_bin}" network nsg rules list \
--nsg-id "${nsg}" --direction INGRESS --all --output json 2>/dev/null \
| SOURCE_CIDR="${source_cidr}" python3 -c 'import json,os,sys
for rule in json.load(sys.stdin).get("data", []):
tcp=rule.get("tcp-options") or rule.get("tcpOptions") or {}
port=tcp.get("destination-port-range") or tcp.get("destinationPortRange") or {}
if (rule.get("direction") == "INGRESS" and rule.get("protocol") == "6" and
rule.get("source") in (os.environ["SOURCE_CIDR"], "0.0.0.0/0") and
str(port.get("min")) == "22" and str(port.get("max")) == "22"):
print("yes")
break' 2>/dev/null || true)"
[[ "${has_rule}" == yes ]] && continue
rule_file="$(mktemp)"
printf '[{"description":"Jeannie Bastion SSH access","direction":"INGRESS","protocol":"6","source":"%s","sourceType":"CIDR_BLOCK","tcpOptions":{"destinationPortRange":{"min":22,"max":22}}}]\n' \
"${source_cidr}" >"${rule_file}"
if ! "${oci_bin}" network nsg rules add --nsg-id "${nsg}" \
--security-rules "file://${rule_file}" >/dev/null 2>&1; then
rm -f "${rule_file}"
echo "Failed to add Bastion TCP/22 ingress to NSG ${nsg}." >&2
return 1
fi
rm -f "${rule_file}"
printf 'Added Bastion TCP/22 ingress to edge NSG %s from %s.\n' "${nsg}" "${source_cidr}"
done <<<"${nsg_ids}"
}
oci_reconcile_bastion_client_access() {
local oci_bin="$1" bastion_id="$2" public_ip current etag updated match
LAB_BASTION_ALLOWLIST_CHANGED=false
public_ip="$(curl --noproxy '*' -4 -fsS --connect-timeout 5 --max-time 10 https://api.ipify.org)" || {
echo "Cannot determine Debian's public IPv4 address for OCI Bastion." >&2; return 1;
}
if ! python3 -c 'import ipaddress,sys
try:
ip=ipaddress.ip_address(sys.argv[1]); sys.exit(0 if ip.version==4 and ip.is_global else 1)
except ValueError: sys.exit(1)' "${public_ip}"; then
echo "Bastion client address is not a public IPv4 address." >&2; return 1
fi
current="$("${oci_bin}" bastion bastion get --bastion-id "${bastion_id}" --output json)" || return 1
match="$(printf '%s' "${current}" | python3 -c 'import ipaddress,json,sys
d=json.load(sys.stdin)["data"]; ip=ipaddress.ip_address(sys.argv[1]); networks=d.get("client-cidr-block-allow-list") or []
print("yes" if any(ip in ipaddress.ip_network(n, strict=False) for n in networks) else "no")' "${public_ip}")" || return 1
if [[ "${match}" == yes ]]; then
printf 'Bastion already permits Debian public IP %s.\n' "${public_ip}"
return 0
fi
etag="$(printf '%s' "${current}" | python3 -c 'import json,sys; print(json.load(sys.stdin).get("etag") or "")')" || return 1
[[ -n "${etag}" ]] || { echo "Bastion response has no ETag; refusing to overwrite its allowlist." >&2; return 1; }
updated="$(printf '%s' "${current}" | python3 -c 'import json,sys
d=json.load(sys.stdin)["data"]; cidrs=d.get("client-cidr-block-allow-list") or []
cidrs.append(sys.argv[1]+"/32"); print(json.dumps(cidrs))' "${public_ip}")" || return 1
printf 'Adding Debian public IP %s/32 to OCI Bastion; preserving existing ranges.\n' "${public_ip}"
"${oci_bin}" bastion bastion update --bastion-id "${bastion_id}" \
--client-cidr-list "${updated}" --if-match "${etag}" --force \
--wait-for-state SUCCEEDED --max-wait-seconds 180 >/dev/null || return 1
export LAB_OCI_BASTION_CLIENT_CIDRS_JSON="${updated}"
oci_foundation_save_config || {
echo "Bastion was updated, but saving its allowlist to Jeannie config failed." >&2; return 1;
}
LAB_BASTION_ALLOWLIST_CHANGED=true
echo "Bastion allowlist updated; a new session is required. Review old ranges when convenient."
}
prepare_oci_edge_bastion() {
local bastion_id="${LAB_OCI_BASTION_ID:-}"
local target_id="${LAB_OCI_EDGE_INSTANCE_ID:-}"
local target_host="${TF_VAR_edge_ssh_host:-}"
local edge_key="${TF_VAR_edge_ssh_key_path:-${LAB_EDGE_SSH_KEY_PATH:-${LAB_OCI_SSH_PRIVATE_KEY:-${HOME}/.ssh/id_ed25519}}}"
local public_key="${edge_key}.pub"
local region="${LAB_OCI_REGION:-}"
local session_ttl="${LAB_OCI_BASTION_SESSION_TTL:-3600}"
local bastion_host
local oci_bin
local session_json=""
local session_id=""
local session_error
local attempt
local session_name
local proxy_command
unset TF_VAR_edge_bastion_host TF_VAR_edge_bastion_user TF_VAR_edge_bastion_port
unset TF_VAR_edge_bastion_private_key_path LAB_OCI_EDGE_BASTION_PROXY_COMMAND
unset LAB_OCI_EDGE_BASTION_SESSION_ID
if [[ "${LAB_OCI_BASTION_ENABLED:-true}" == "false" || -z "${bastion_id}" ]]; then
return 0
fi
if [[ "${bastion_id}" != ocid1.bastion.* ]]; then
echo "Invalid OCI Bastion OCID '${bastion_id}'; refusing direct public SSH fallback." >&2
return 1
fi
if [[ -z "${target_id}" || -z "${target_host}" ]]; then
echo "OCI Bastion is enabled, but the managed edge instance/private address was not discovered." >&2
return 1
fi
if [[ -z "${region}" ]]; then
echo "LAB_OCI_REGION is required to create an OCI Bastion session for edge SSH." >&2
return 1
fi
if [[ ! -r "${edge_key}" || ! -r "${public_key}" ]]; then
echo "OCI Bastion edge SSH key pair is not readable: ${edge_key}" >&2
return 1
fi
if ! python3 -c 'import ipaddress,sys
try:
a=ipaddress.ip_address(sys.argv[1]); networks=[ipaddress.ip_network(x) for x in ("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16")]
sys.exit(0 if a.version==4 and any(a in n for n in networks) else 1)
except ValueError:
sys.exit(1)' "${target_host}"; then
echo "Refusing Bastion forwarding to a non-private IPv4 address." >&2
return 1
fi
local key_digest
key_digest="$(sha256sum "${public_key}" | cut -c1-12)" || return 1
session_name="jeannie-pf-${target_id##*.}-${target_host//./-}-${key_digest}"
if ! declare -F oci_cli_resolve >/dev/null 2>&1 || ! oci_bin="$(oci_cli_resolve 2>/dev/null)"; then
echo "OCI CLI is required to create the edge Bastion session." >&2
return 1
fi
oci_reconcile_bastion_client_access "${oci_bin}" "${bastion_id}" || return 1
if [[ "${LAB_BASTION_ALLOWLIST_CHANGED}" == true ]]; then
session_name="${session_name}-$(date +%s)"
fi
bastion_host="host.bastion.${region}.oci.oraclecloud.com"
session_error="$(mktemp)"
for attempt in 1 2 3 4 5 6; do
# The CLI can return the asynchronous work-request OCID even after
# waiting for SUCCEEDED. Reuse the active session created for this
# target before creating another one.
session_id="$(${oci_bin} bastion session list \
--bastion-id "${bastion_id}" \
--display-name "${session_name}" \
--session-lifecycle-state ACTIVE --all \
--query 'data[0].id' --raw-output 2>/dev/null || true)"
if [[ "${session_id}" == ocid1.bastionsession.* ]]; then
break
fi
session_id=""
session_json="$(${oci_bin} bastion session create-port-forwarding \
--bastion-id "${bastion_id}" \
--display-name "${session_name}" \
--target-private-ip "${target_host}" \
--target-port 22 \
--ssh-public-key-file "${public_key}" \
--session-ttl "${session_ttl}" \
--wait-for-state SUCCEEDED --output json 2>"${session_error}" || true)"
if [[ -n "${session_json}" ]]; then
session_id="$(printf '%s' "${session_json}" | python3 -c 'import json,sys; print(json.load(sys.stdin)["data"]["id"])' 2>/dev/null || true)"
fi
if [[ "${session_id}" == ocid1.bastionsession.* ]]; then
break
fi
# A successful work request may need a short delay before the
# resulting session appears in the list API.
session_id=""
if (( attempt < 6 )); then
printf 'Waiting for OCI Bastion forwarding session readiness (retry %d/6)...\n' "${attempt}" >&2
sleep 10
fi
done
if [[ -z "${session_id}" || "${session_id}" == "null" ||
"${session_id}" != ocid1.bastionsession.* ]]; then
echo "Unable to create an OCI Bastion port-forwarding session for the edge instance." >&2
sed -n '1,80p' "${session_error}" >&2 || true
rm -f "${session_error}"
return 1
fi
rm -f "${session_error}"
export TF_VAR_edge_bastion_host="${bastion_host}"
export TF_VAR_edge_bastion_user="${session_id}"
export TF_VAR_edge_bastion_port=22
export TF_VAR_edge_bastion_private_key_path="${edge_key}"
printf -v proxy_command 'ssh -i %q -o ProxyCommand=none -o ProxyJump=none -o BatchMode=yes -o ConnectTimeout=10 -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new -W %%h:%%p -p 22 %s@%s' \
"${edge_key}" "${session_id}" "${bastion_host}"
export LAB_OCI_EDGE_BASTION_PROXY_COMMAND="${proxy_command}"
export LAB_OCI_EDGE_BASTION_SESSION_ID="${session_id}"
printf 'Using OCI Bastion session %s for edge SSH via %s (target %s).\n' \
"${session_id}" "${bastion_host}" "${target_host}"
}
refresh_oci_edge_host_key() {
local edge_host="${LAB_EDGE_HOST:-${TF_VAR_edge_host:-}}"
local edge_private_host="${TF_VAR_edge_ssh_host:-}"
local known_hosts="${HOME}/.ssh/known_hosts"
# OCI instances may be destroyed and recreated with the same public IP.
# Remove only the managed OCI edge address so accept-new can record the
# replacement fingerprint; unrelated homelab host keys remain untouched.
if [[ -z "${edge_host}" || "${LAB_OCI_FOUNDATION_ENABLED:-false}" != "true" ]]; then
return 0
fi
if [[ -f "${known_hosts}" ]] && command -v ssh-keygen >/dev/null 2>&1; then
ssh-keygen -R "${edge_host}" -f "${known_hosts}" >/dev/null 2>&1 || true
if [[ -n "${edge_private_host}" && "${edge_private_host}" != "${edge_host}" ]]; then
ssh-keygen -R "${edge_private_host}" -f "${known_hosts}" >/dev/null 2>&1 || true
fi
fi
}
edge_require_ssh_transport() {
case "${LAB_EDGE_RESOLVED_SSH_TRANSPORT:-${LAB_EDGE_SSH_TRANSPORT:-tailscale}}" in
tailscale)
if [[ -z "${TF_VAR_edge_ssh_host:-}" ||
"${TF_VAR_edge_ssh_host}" != "${LAB_EDGE_TAILSCALE_IP:-}" ]]; then
echo "The edge Tailscale SSH endpoint has not been resolved." >&2
return 1
fi
;;
bastion)
if [[ -z "${TF_VAR_edge_ssh_host:-}" ||
-z "${LAB_OCI_EDGE_BASTION_PROXY_COMMAND:-}" ]]; then
echo "Bastion SSH was selected but its private route/session is not ready." >&2
return 1
fi
;;
*)
echo "Edge SSH transport is unresolved; choose auto, tailscale, or bastion." >&2
return 1
;;
esac
}
edge_ssh_args() {
local edge_key="${TF_VAR_edge_ssh_key_path:-${LAB_EDGE_SSH_KEY_PATH:-${LAB_OCI_SSH_PRIVATE_KEY:-${HOME}/.ssh/id_ed25519}}}"
EDGE_SSH_ARGS=(-i "${edge_key}" -o BatchMode=yes -o ConnectTimeout="${LAB_EDGE_SSH_PREFLIGHT_SECONDS:-10}" -o ConnectionAttempts=1 -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new)
if [[ "${LAB_EDGE_RESOLVED_SSH_TRANSPORT:-${LAB_EDGE_SSH_TRANSPORT:-tailscale}}" == "tailscale" ]]; then
# Direct tailnet SSH must also bypass ProxyJump/ProxyCommand inherited
# from an operator's SSH config or a previous Bastion invocation.
EDGE_SSH_ARGS+=( -o ProxyCommand=none -o ProxyJump=none )
elif [[ -n "${LAB_OCI_EDGE_BASTION_PROXY_COMMAND:-}" ]]; then
if [[ "${LAB_OCI_EDGE_BASTION_PROXY_COMMAND}" == *'%h:%p'* ]]; then
EDGE_SSH_ARGS+=( -o "ProxyCommand=${LAB_OCI_EDGE_BASTION_PROXY_COMMAND}" )
else
EDGE_SSH_ARGS+=( -o "ProxyCommand=${LAB_OCI_EDGE_BASTION_PROXY_COMMAND} %h %p" )
fi
fi
}
edge_remote_failure_report() {
local edge_host="${TF_VAR_edge_ssh_host:-${TF_VAR_edge_host:-${LAB_EDGE_HOST:-}}}"
local edge_user="${TF_VAR_edge_user:-${LAB_EDGE_USER:-ubuntu}}"
if [[ -z "${edge_host}" ]]; then
return 0
fi
local install_dir="${TF_VAR_edge_install_dir:-${LAB_EDGE_INSTALL_DIR:-/opt/homelab-edge}}"
if [[ "${install_dir}" == *"'"* ]]; then
echo "Invalid edge install directory." >&2
return 1
fi
edge_ssh_args
echo "Remote edge bootstrap diagnostics:"
ssh "${EDGE_SSH_ARGS[@]}" "${edge_user}@${edge_host}" \
"bash -s -- '${install_dir}'" <"${REPO_ROOT}/scripts/edge-diagnostics" ||
{ echo "Unable to retrieve the remote edge diagnostics." >&2; return 1; }
}
edge_diagnose() {
require_debian_server "edge diagnose"
prepare_edge_connection || return 1
edge_remote_failure_report
}
edge_flush_caches() {
local edge_host="${TF_VAR_edge_ssh_host:-${TF_VAR_edge_host:-${LAB_EDGE_HOST:-}}}"
local edge_user="${TF_VAR_edge_user:-${LAB_EDGE_USER:-ubuntu}}"
local edge_key="${TF_VAR_edge_ssh_key_path:-${LAB_EDGE_SSH_KEY_PATH:-/home/jv/.ssh/id_ed25519}}"
local edge_install_dir="${TF_VAR_edge_install_dir:-${LAB_EDGE_INSTALL_DIR:-/opt/homelab-edge}}"
require_debian_server "edge-cache-flush"
if [[ -z "${edge_host}" || "${edge_install_dir}" == *"'"* ]]; then
echo "LAB_EDGE_HOST and LAB_EDGE_INSTALL_DIR are required to flush edge caches." >&2
exit 1
fi
echo "Flushing edge caches on ${edge_user}@${edge_host}:${edge_install_dir}..."
edge_ssh_args
ssh "${EDGE_SSH_ARGS[@]}" "${edge_user}@${edge_host}" "set -eu
cd '${edge_install_dir}'
if ! sudo docker compose ps >/dev/null 2>&1; then
echo 'Edge docker compose stack is not available.' >&2
exit 1
fi
if sudo docker compose ps --services --filter status=running | grep -qx nginx-dev; then
sudo docker compose exec -T nginx-dev sh -lc 'find /var/cache/nginx /var/cache/nginx_dynamic -type f -delete 2>/dev/null || true'
sudo docker compose exec -T nginx-dev nginx -s reload || sudo docker compose restart nginx-dev >/dev/null
fi
if sudo docker compose ps --services --filter status=running | grep -qx varnish-dev; then
sudo docker compose restart varnish-dev >/dev/null
fi
if sudo docker compose ps --services --filter status=running | grep -qx squid-dev; then
sudo docker compose exec -T squid-dev sh -lc 'find /var/spool/squid -type f -delete 2>/dev/null || true'
sudo docker compose restart squid-dev >/dev/null
fi
"
echo "Edge caches flushed."
}
edge_haproxy_stats_password_valid() {
local password="${1:-}"
[[ -n "${password}" ]] && ((${#password} >= 12)) && [[ "${password}" != "adminpassword" ]]
}
ensure_edge_tailscale_routes() {
local enabled="${LAB_EDGE_CONFIGURE_TAILSCALE_ROUTES:-true}"
local route="${LAB_EDGE_TAILSCALE_SUBNET_ROUTE:-${LAB_LAN_CIDR:-192.168.100.0/24}}"
local router="${LAB_EDGE_TAILSCALE_ROUTER:-debian}"
local traefik_ip="${LAB_TRAEFIK_LB_IP:-}"
local tailscale_cidr="${LAB_TAILSCALE_CGNAT_CIDR:-100.64.0.0/10}"
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 edge_host="${TF_VAR_edge_ssh_host:-${TF_VAR_edge_host:-${LAB_EDGE_HOST:-}}}"
local edge_user="${TF_VAR_edge_user:-${LAB_EDGE_USER:-ubuntu}}"
local edge_key="${TF_VAR_edge_ssh_key_path:-${LAB_EDGE_SSH_KEY_PATH:-/home/jv/.ssh/id_ed25519}}"
if disabled_value "${enabled}"; then
return 0
fi
if [[ -f "${HOMELAB_STATE_DIR}/clusters/${LAB_CLUSTER_PROFILE}/identity.json" ]]; then
retire_debian_service_hooks || return 1
fi
if ! truthy "${enabled}"; then
echo "LAB_EDGE_CONFIGURE_TAILSCALE_ROUTES must be true or false." >&2
exit 1
fi
if ! validate_ipv4_cidr_or_host "${route}"; then
echo "Invalid LAB_EDGE_TAILSCALE_SUBNET_ROUTE '${route}'." >&2
exit 1
fi
if [[ -z "${traefik_ip}" ]]; then
echo "LAB_TRAEFIK_LB_IP is required to configure edge-to-Traefik routing." >&2
exit 1
fi
if ! validate_ipv4_cidr_or_host "${traefik_ip}" || [[ "${traefik_ip}" == */* ]]; then
echo "Invalid LAB_TRAEFIK_LB_IP '${traefik_ip}'." >&2
exit 1
fi
if ! validate_ipv4_cidr_or_host "${tailscale_cidr}" || [[ "${tailscale_cidr}" != */* ]]; then
echo "Invalid LAB_TAILSCALE_CGNAT_CIDR '${tailscale_cidr}'." >&2
exit 1
fi
if [[ -z "${edge_host}" ]]; then
echo "LAB_EDGE_HOST or TF_VAR_edge_host is required to configure edge Tailscale routes." >&2
exit 1
fi
edge_require_ssh_transport || return 1
case "${router}" in
debian)
echo "Ensuring Debian advertises ${route} and OCI edge accepts Tailscale routes..."
if ! command -v tailscale >/dev/null 2>&1; then
echo "tailscale is not installed on the Debian subnet router." >&2
exit 1
fi
sudo mkdir -p /etc/sysctl.d
printf '%s\n' 'net.ipv4.ip_forward = 1' | sudo tee /etc/sysctl.d/99-homelab-tailscale-subnet-router.conf >/dev/null
sudo sysctl -w net.ipv4.ip_forward=1 >/dev/null
sudo tailscale set --advertise-routes="${route}"
sudo tee /usr/local/sbin/homelab-edge-traefik-route.sh >/dev/null <<ROUTE_SCRIPT_EOF
#!/usr/bin/env bash
set -euo pipefail
traefik_ip='${traefik_ip}'
tailscale_cidr='${tailscale_cidr}'
sysctl_bin="\$(command -v sysctl 2>/dev/null || true)"
if [ -z "\$sysctl_bin" ] && [ -x /usr/sbin/sysctl ]; then
sysctl_bin=/usr/sbin/sysctl
fi
if [ -n "\$sysctl_bin" ]; then
"\$sysctl_bin" -w net.ipv4.ip_forward=1 >/dev/null
fi
route_line="\$(ip route get "\$traefik_ip")"
lan_if="\$(printf '%s\n' "\$route_line" | awk '{for (i = 1; i < NF; i++) if (\$i == "dev") {print \$(i + 1); exit}}')"
route_src="\$(printf '%s\n' "\$route_line" | awk '{for (i = 1; i < NF; i++) if (\$i == "src") {print \$(i + 1); exit}}')"
if [ -z "\$lan_if" ]; then
echo "Could not resolve LAN interface for \$traefik_ip." >&2
exit 1
fi
iptables_bin="\$(command -v iptables 2>/dev/null || true)"
if [ -z "\$iptables_bin" ] && [ -x /usr/sbin/iptables ]; then
iptables_bin=/usr/sbin/iptables
fi
if [ -z "\$iptables_bin" ]; then
echo 'iptables is required to configure edge-to-Traefik forwarding.' >&2
exit 1
fi
iptables_cmd() {
"\$iptables_bin" "\$@"
}
if [ -n "\$route_src" ] && [ "\$route_src" != "\$lan_if" ]; then
while iptables_cmd -D FORWARD -i tailscale0 -o "\$route_src" -s "\$tailscale_cidr" -d "\$traefik_ip" -m comment --comment homelab-edge-traefik-route -j ACCEPT 2>/dev/null; do :; done
while iptables_cmd -D FORWARD -i "\$route_src" -o tailscale0 -s "\$traefik_ip" -d "\$tailscale_cidr" -m comment --comment homelab-edge-traefik-route -j ACCEPT 2>/dev/null; do :; done
while iptables_cmd -t nat -D POSTROUTING -s "\$tailscale_cidr" -d "\$traefik_ip" -o "\$route_src" -m comment --comment homelab-edge-traefik-route -j MASQUERADE 2>/dev/null; do :; done
fi
iptables_cmd -C FORWARD -i tailscale0 -o "\$lan_if" -s "\$tailscale_cidr" -d "\$traefik_ip" -m comment --comment homelab-edge-traefik-route -j ACCEPT 2>/dev/null ||
iptables_cmd -I FORWARD 1 -i tailscale0 -o "\$lan_if" -s "\$tailscale_cidr" -d "\$traefik_ip" -m comment --comment homelab-edge-traefik-route -j ACCEPT
iptables_cmd -C FORWARD -i "\$lan_if" -o tailscale0 -s "\$traefik_ip" -d "\$tailscale_cidr" -m comment --comment homelab-edge-traefik-route -j ACCEPT 2>/dev/null ||
iptables_cmd -I FORWARD 1 -i "\$lan_if" -o tailscale0 -s "\$traefik_ip" -d "\$tailscale_cidr" -m comment --comment homelab-edge-traefik-route -j ACCEPT
iptables_cmd -t nat -C POSTROUTING -s "\$tailscale_cidr" -d "\$traefik_ip" -o "\$lan_if" -m comment --comment homelab-edge-traefik-route -j MASQUERADE 2>/dev/null ||
iptables_cmd -t nat -I POSTROUTING 1 -s "\$tailscale_cidr" -d "\$traefik_ip" -o "\$lan_if" -m comment --comment homelab-edge-traefik-route -j MASQUERADE
ROUTE_SCRIPT_EOF
sudo chmod 0755 /usr/local/sbin/homelab-edge-traefik-route.sh
sudo tee /etc/systemd/system/homelab-edge-traefik-route.service >/dev/null <<'ROUTE_SERVICE_EOF'
[Unit]
Description=Homelab edge Tailscale route to Traefik MetalLB
After=network-online.target tailscaled.service
Wants=network-online.target
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/homelab-edge-traefik-route.sh
RemainAfterExit=yes
[Install]
WantedBy=multi-user.target
ROUTE_SERVICE_EOF
sudo systemctl daemon-reload
sudo systemctl enable homelab-edge-traefik-route.service >/dev/null
sudo systemctl restart homelab-edge-traefik-route.service
;;
rpi | rpi4 | raspberrypi)
echo "Ensuring RPi advertises ${route} and OCI edge accepts Tailscale routes..."
ssh -i "${rpi_key}" -o BatchMode=yes -o ConnectTimeout=10 -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new "${rpi_user}@${rpi_host}" "set -eu
if ! command -v tailscale >/dev/null 2>&1; then
echo 'tailscale is not installed on the RPi subnet router.' >&2
exit 1
fi
sysctl_bin=\"\$(command -v sysctl 2>/dev/null || true)\"
if [ -z \"\$sysctl_bin\" ] && [ -x /usr/sbin/sysctl ]; then
sysctl_bin=/usr/sbin/sysctl
fi
if [ -z \"\$sysctl_bin\" ]; then
echo 'sysctl is not installed on the RPi subnet router.' >&2
exit 1
fi
sudo mkdir -p /etc/sysctl.d
printf '%s\n' 'net.ipv4.ip_forward = 1' | sudo tee /etc/sysctl.d/99-homelab-tailscale-subnet-router.conf >/dev/null
sudo \"\$sysctl_bin\" -w net.ipv4.ip_forward=1 >/dev/null
sudo tailscale set --advertise-routes='${route}'
"
;;
*)
echo "LAB_EDGE_TAILSCALE_ROUTER must be debian or rpi." >&2
exit 1
;;
esac
edge_ssh_args
if ! ssh "${EDGE_SSH_ARGS[@]}" "${edge_user}@${edge_host}" "set -eu
if ! command -v tailscale >/dev/null 2>&1; then
echo 'tailscale is not installed on the OCI edge host.' >&2
exit 1
fi
sudo tailscale set --accept-routes=true
"; then
echo "OCI edge SSH preflight failed via ${LAB_EDGE_RESOLVED_SSH_TRANSPORT:-unknown} (${edge_host})." >&2
return 1
fi
}
edge_haproxy_stats_credentials_file() {
printf '%s\n' "${LAB_EDGE_HAPROXY_STATS_CREDENTIALS_FILE:-${HOME}/.config/homelab/edge-haproxy.env}"
}
generate_edge_haproxy_stats_password() {
if command -v openssl >/dev/null 2>&1; then
openssl rand -hex 24
elif command -v python3 >/dev/null 2>&1; then
python3 - <<'PY'
import secrets
print(secrets.token_hex(24))
PY
else
echo "openssl or python3 is required to generate an edge HAProxy stats password." >&2
exit 1
fi
}
write_edge_haproxy_stats_credentials() {
local credentials_file="$1"
local password="$2"
local credentials_dir
credentials_dir="$(dirname "${credentials_file}")"
mkdir -p "${credentials_dir}"
chmod 0700 "${credentials_dir}"
{
printf 'TF_VAR_haproxy_stats_password='
printf '%q' "${password}"
printf '\n'
} > "${credentials_file}"
chmod 0600 "${credentials_file}"
}
recover_edge_haproxy_stats_password() {
local edge_host="${TF_VAR_edge_ssh_host:-${TF_VAR_edge_host:-${LAB_EDGE_HOST:-}}}"
local edge_user="${TF_VAR_edge_user:-${LAB_EDGE_USER:-ubuntu}}"
local edge_key="${TF_VAR_edge_ssh_key_path:-${LAB_EDGE_SSH_KEY_PATH:-/home/jv/.ssh/id_ed25519}}"
local edge_install_dir="${TF_VAR_edge_install_dir:-${LAB_EDGE_INSTALL_DIR:-/opt/homelab-edge}}"
local remote_auth
local remote_password
if [[ -z "${edge_host}" || "${edge_install_dir}" == *"'"* ]]; then
return 1
fi
edge_ssh_args
remote_auth="$(ssh "${EDGE_SSH_ARGS[@]}" "${edge_user}@${edge_host}" \
"sudo sed -n 's/^[[:space:]]*stats auth //p' '${edge_install_dir}/config_files/haproxy.cfg' | head -n 1" 2>/dev/null || true)"
remote_auth="${remote_auth//$'\r'/}"
if [[ "${remote_auth}" != *:* ]]; then
return 1
fi
remote_password="${remote_auth#*:}"
if ! edge_haproxy_stats_password_valid "${remote_password}"; then
return 1
fi
printf '%s\n' "${remote_password}"
}
ensure_edge_haproxy_stats_password() {
local credentials_file
local recovered_password
if edge_haproxy_stats_password_valid "${TF_VAR_haproxy_stats_password:-}"; then
export TF_VAR_haproxy_stats_password
return 0
fi
credentials_file="$(edge_haproxy_stats_credentials_file)"
if [[ -r "${credentials_file}" ]]; then
# shellcheck disable=SC1090
source "${credentials_file}"
if edge_haproxy_stats_password_valid "${TF_VAR_haproxy_stats_password:-}"; then
export TF_VAR_haproxy_stats_password
return 0
fi
echo "Ignoring invalid edge HAProxy stats credentials in ${credentials_file}." >&2
fi
if recovered_password="$(recover_edge_haproxy_stats_password)"; then
TF_VAR_haproxy_stats_password="${recovered_password}"
export TF_VAR_haproxy_stats_password
write_edge_haproxy_stats_credentials "${credentials_file}" "${TF_VAR_haproxy_stats_password}"
echo "Recovered edge HAProxy stats password from the live edge host and stored it at ${credentials_file}."
return 0
fi
TF_VAR_haproxy_stats_password="$(generate_edge_haproxy_stats_password)"
export TF_VAR_haproxy_stats_password
write_edge_haproxy_stats_credentials "${credentials_file}" "${TF_VAR_haproxy_stats_password}"
echo "Generated edge HAProxy stats password at ${credentials_file}."
}
ensure_cluster_worker_var_file() {
if [[ "${LAB_CLUSTER_RUNTIME:-kubeadm}" == "k3s" ]]; then
rm -f "${REPO_ROOT}/.lab/cluster-workers.auto.tfvars.json"
unset LAB_CLUSTER_VAR_FILE
return 0
fi
if [[ -z "${LAB_CLUSTER_VAR_FILE:-}" ]]; then
prepare_cluster_worker_var_file false
fi
if truthy "${TF_VAR_allow_empty_worker_nodes:-false}"; then
return 0
fi
if ! cluster_worker_var_file_has_workers "${LAB_CLUSTER_VAR_FILE}"; then
echo "Cluster worker var file has no worker_nodes: ${LAB_CLUSTER_VAR_FILE}" >&2
echo "Run the Pimox worker stage first or set LAB_PIMOX_WORKER_COUNT and LAB_PIMOX_WORKER_STATIC_IPS." >&2
return 1
fi
}
run_up_parallel_stage() {
local spec_file
local parallelism="${JEANNIE_UP_PARALLELISM:-4}"
local status
if ! [[ "${parallelism}" =~ ^[0-9]+$ ]] || ((parallelism < 1)); then
echo "JEANNIE_UP_PARALLELISM must be a positive integer." >&2
return 1
fi
spec_file="$(mktemp)"
python3 - "${spec_file}" "${REPO_ROOT}/jeannie" "${parallelism}" <<'PY'
import json
import sys
spec_file, jeannie, parallelism = sys.argv[1:4]
spec = {
"parallelism": int(parallelism),
"tasks": [
{
"id": "gitea-deploy",
"title": "Gitea deploy",
"command": [jeannie, "__up-task", "gitea-deploy"],
},
{
"id": "api-deploy",
"title": "Jeannie API deploy",
"command": [jeannie, "__up-task", "api-deploy"],
},
{
"id": "gitea-bootstrap",
"title": "Gitea repo bootstrap",
"needs": ["gitea-deploy"],
"command": [jeannie, "__up-task", "gitea-bootstrap"],
},
{
"id": "heimdall-deploy",
"title": "Heimdall deploy",
"command": [jeannie, "__up-task", "heimdall-deploy"],
},
{
"id": "searxng-deploy",
"title": "SearXNG deploy",
"command": [jeannie, "__up-task", "searxng-deploy"],
},
{
"id": "privatebin-deploy",
"title": "PrivateBin deploy",
"command": [jeannie, "__up-task", "privatebin-deploy"],
},
{
"id": "miniflux-deploy",
"title": "Miniflux deploy",
"command": [jeannie, "__up-task", "miniflux-deploy"],
},
{
"id": "dex-deploy",
"title": "Dex deploy",
"command": [jeannie, "__up-task", "dex-deploy"],
},
{
"id": "matrix-deploy",
"title": "Matrix deploy",
"command": [jeannie, "__up-task", "matrix-deploy"],
},
{
"id": "ai-stack-deploy",
"title": "AI stack deploy",
"command": [jeannie, "__up-task", "ai-stack-deploy"],
},
{
"id": "hermes-deploy",
"title": "Hermes deploy",
"needs": ["ai-stack-deploy", "matrix-deploy"],
"command": [jeannie, "__up-task", "hermes-deploy"],
},
{
"id": "ai-tools-deploy",
"title": "AI tools deploy",
"needs": ["ai-stack-deploy", "hermes-deploy"],
"command": [jeannie, "__up-task", "ai-tools-deploy"],
},
{
"id": "rpi-services",
"title": "RPi services",
"command": [jeannie, "__up-task", "rpi-services"],
},
{
"id": "pimox-workers",
"title": "Pimox provisioning and workers",
"command": [jeannie, "__up-task", "pimox-workers"],
},
{
"id": "edge-host",
"title": "OCI edge host check",
"command": [jeannie, "__up-task", "edge-host"],
},
],
}
with open(spec_file, "w", encoding="utf-8") as handle:
json.dump(spec, handle, indent=2)
handle.write("\n")
PY
set +e
"${REPO_ROOT}/scripts/jeannie-core" run-dag --spec "${spec_file}"
status=$?
set -e
rm -f "${spec_file}"
return "${status}"
}
graphiphy_map() {
if ! command -v graphiphy >/dev/null 2>&1; then
echo "graphiphy is not installed; skipping repo map generation."
return 0
fi
graphiphy "${REPO_ROOT}"
}
up_task() {
require_debian_server "__up-task"
case "${1:-}" in
gitea-deploy)
deploy_gitea
;;
api-deploy)
deploy_api
;;
gitea-bootstrap)
bootstrap_gitea_repo
;;
heimdall-deploy)
deploy_heimdall
;;
searxng-deploy)
deploy_searxng
;;
privatebin-deploy)
deploy_privatebin
;;
miniflux-deploy)
deploy_miniflux
;;
dex-deploy)
deploy_dex
;;
matrix-deploy)
deploy_matrix
;;
ai-stack-deploy)
deploy_ai_stack
;;
ai-tools-deploy)
deploy_ai_tools
;;
omniroute-deploy)
deploy_omniroute
;;
hermes-deploy)
deploy_hermes
;;
rpi-services)
deploy_rpi_services
;;
pimox-workers)
if [[ "${LAB_CLUSTER_RUNTIME:-kubeadm}" == "k3s" ]]; then
echo "Skipping Pimox worker provisioning for the direct-host K3s runtime."
return 0
fi
run_pimox_pipeline
;;
edge-host)
check_edge_ssh
;;
*)
echo "Unknown __up-task '${1:-}'." >&2
return 1
;;
esac
}
up() {
require_debian_server "up"
echo "Deploying the homelab infrastructure..."
jeannie_log_start "up"
local up_steps=13
if truthy "${LAB_RPI4_HOST_BOOTSTRAP_ENABLED:-false}"; then
up_steps=$((up_steps + 1))
fi
jeannie_step_plan "${up_steps}"
run_step "Early preflight" homelab_preflight early
run_step "Go toolchain" ensure_go_toolchain
run_step "Repo Map (Graphiphy)" graphiphy_map
if truthy "${LAB_RPI4_HOST_BOOTSTRAP_ENABLED:-false}"; then
run_step "RPi4 host bootstrap" host_bootstrap_manage rpi4 apply --yes
fi
run_step "Independent host services" run_up_parallel_stage
run_step "Full preflight" homelab_preflight full
run_step "Pre-apply doctor" doctor_preapply
run_step "Worker var file" ensure_cluster_worker_var_file
run_step "Start existing cluster if stopped" ensure_existing_cluster_started_for_up
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" edge_apply
run_step "Debian Kubernetes offload cleanup" cleanup_debian_k8s_after_pimox_offload
echo "Deployment successfully completed."
echo "Log: ${JEANNIE_LOG_FILE}"
}
tofu_stack_from_plan_target() {
case "$1" in
provisioning)
printf 'bootstrap/provisioning\n'
;;
cluster)
printf 'bootstrap/cluster\n'
;;
platform)
printf 'bootstrap/platform\n'
;;
apps)
printf 'bootstrap/apps\n'
;;
edge)
printf 'bootstrap/edge\n'
;;
*)
echo "Unknown plan target '$1'. Use all, provisioning, cluster, platform, apps, or edge." >&2
return 1
;;
esac
}