diff --git a/bootstrap/edge/main.tf b/bootstrap/edge/main.tf index 53f469b..8eff535 100644 --- a/bootstrap/edge/main.tf +++ b/bootstrap/edge/main.tf @@ -26,10 +26,12 @@ locals { office_server_name = var.office_server_name office_onlyoffice_server_name = var.office_onlyoffice_server_name matrix_server_names = var.matrix_enabled ? [var.matrix_server_name, var.element_server_name] : [] + monitoring_names = var.monitoring_backend_host != "" ? ["grafana.${var.server_name}", "prometheus.${var.server_name}", "alertmanager.${var.server_name}"] : [] server_names = distinct(concat([var.server_name, local.heimdall_server_name, local.homepage_server_name, local.oidc_server_name, local.jellyfin_server_name, local.jeannie_api_server_name, local.office_server_name, local.office_onlyoffice_server_name], local.matrix_server_names, var.additional_server_names)) - main_server_names = [for name in local.server_names : name if !contains([local.heimdall_server_name, local.homepage_server_name, local.oidc_server_name, local.jellyfin_server_name, local.jeannie_api_server_name, local.office_server_name, local.office_onlyoffice_server_name], name) && !contains(local.matrix_server_names, name)] + main_server_names = [for name in local.server_names : name if !contains([local.heimdall_server_name, local.homepage_server_name, local.oidc_server_name, local.jellyfin_server_name, local.jeannie_api_server_name, local.office_server_name, local.office_onlyoffice_server_name], name) && !contains(local.matrix_server_names, name) && !contains(local.monitoring_names, name)] default_conf = templatefile("${path.module}/templates/default.conf.tftpl", { server_name = var.server_name + monitoring_backend_host = var.monitoring_backend_host server_names = join(" ", local.server_names) main_server_names = join(" ", local.main_server_names) backend_host = var.backend_host @@ -132,6 +134,7 @@ resource "null_resource" "edge_services" { filesha256("${path.module}/files/oracle-agent-watchdog.timer"), ])) config_hash = local.config_hash + config_only = tostring(var.edge_config_only) } connection { @@ -266,6 +269,27 @@ install_missing_packages() { } edge_stage packages +if [ "${self.triggers.config_only}" = "true" ]; then + edge_stage nginx-config-only + if [ ! -f "$install_dir/docker-compose.yml" ]; then + echo "Edge is not bootstrapped; run ./jeannie edge apply first." >&2 + exit 1 + fi + previous_config="$(mktemp)" + sudo cp "$install_dir/config_files/default.conf" "$previous_config" + sudo cp /tmp/homelab-edge/config_files/default.conf "$install_dir/config_files/default.conf" + cd "$install_dir" + if ! sudo -n timeout --foreground -k 5s 30s docker compose exec -T nginx-dev nginx -t || + ! sudo -n timeout --foreground -k 5s 30s docker compose exec -T nginx-dev nginx -s reload; then + sudo cp "$previous_config" "$install_dir/config_files/default.conf" + rm -f "$previous_config" + echo "Nginx configuration update failed; previous configuration restored." >&2 + exit 1 + fi + rm -f "$previous_config" + edge_stage complete + exit 0 +fi install_missing_packages ca-certificates curl openssl prometheus-node-exporter edge_stage oracle-agent-watchdog @@ -567,7 +591,9 @@ run_compose_step() { shift edge_stage "compose-$step" command_log="$(mktemp)" - if "$@" >"$command_log" 2>&1; then + step_timeout=180 + if [ "$step" = pull ]; then step_timeout=600; fi + if timeout --foreground -k 5s "$step_timeout" "$@" >"$command_log" 2>&1; then sudo install -m 0600 "$command_log" "$install_dir/last-compose.log" rm -f "$command_log" else diff --git a/bootstrap/edge/templates/default.conf.tftpl b/bootstrap/edge/templates/default.conf.tftpl index 862d2aa..c8c30bd 100644 --- a/bootstrap/edge/templates/default.conf.tftpl +++ b/bootstrap/edge/templates/default.conf.tftpl @@ -1,3 +1,34 @@ +%{ if monitoring_backend_host != "" ~} +%{ for app, port in {grafana = 13000, prometheus = 19090, alertmanager = 19093} ~} +server { + listen 80; + listen 443 ssl; + http2 on; + server_name ${app}.${server_name}; + ssl_certificate /etc/nginx/certs/current.crt; + ssl_certificate_key /etc/nginx/certs/current.key; + client_max_body_size 20m; + location ^~ /.well-known/acme-challenge/ { + root /var/www/certbot; + default_type "text/plain"; + try_files $uri =404; + } + location / { + if ($scheme = http) { return 301 https://$host$request_uri; } + proxy_pass http://${monitoring_backend_host}:${port}; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto https; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection $connection_upgrade; + proxy_read_timeout 120s; + add_header Cache-Control "no-store"; + } +} +%{ endfor ~} +%{ endif ~} map $request_uri $blocked_uris { default 0; ~*(/\.env|/\.git|/\.aws|/wp-admin) 1; diff --git a/bootstrap/edge/variables.tf b/bootstrap/edge/variables.tf index 6d94392..2bfb7c4 100644 --- a/bootstrap/edge/variables.tf +++ b/bootstrap/edge/variables.tf @@ -149,6 +149,17 @@ variable "backend_host" { } } +variable "monitoring_backend_host" { + type = string + default = "" +} + +variable "edge_config_only" { + description = "Reload existing Nginx configuration without pulling or recreating edge containers." + type = bool + default = false +} + variable "backend_port" { type = number default = 80 diff --git a/bootstrap/platform/main.tf b/bootstrap/platform/main.tf index 5bd974d..a62f058 100644 --- a/bootstrap/platform/main.tf +++ b/bootstrap/platform/main.tf @@ -1934,6 +1934,11 @@ resource "helm_release" "prometheus_stack" { wait = false cleanup_on_fail = true + postrender { + binary_path = "${path.module}/../../scripts/monitoring-helm-postrender.py" + args = [var.external_monitoring_enabled ? var.external_monitoring_host : ""] + } + values = [ yamlencode({ additionalPrometheusRulesMap = { @@ -2076,6 +2081,7 @@ resource "helm_release" "prometheus_stack" { ] } alertmanagerSpec = { + replicas = var.external_monitoring_enabled ? 0 : 1 nodeSelector = local.prometheus_stack_node_selector resources = { requests = { @@ -2104,6 +2110,7 @@ resource "helm_release" "prometheus_stack" { } prometheus = { prometheusSpec = { + replicas = var.external_monitoring_enabled ? 0 : 1 externalLabels = { cluster_profile = var.cluster_profile, cluster_uid = var.cluster_identity_uid } priorityClassName = kubernetes_priority_class_v1.monitoring.metadata[0].name nodeSelector = local.prometheus_stack_node_selector @@ -2254,6 +2261,7 @@ resource "helm_release" "prometheus_stack" { } } grafana = { + replicas = var.external_monitoring_enabled ? 0 : 1 priorityClassName = kubernetes_priority_class_v1.monitoring.metadata[0].name nodeSelector = local.prometheus_stack_node_selector envValueFrom = var.grafana_sso_enabled ? { @@ -2383,6 +2391,7 @@ resource "null_resource" "prometheus_stack_readiness" { release_version = var.observability.prometheus.version readiness_check = "3" checker_sha = filesha256("${path.module}/../../scripts/monitoring-readiness.py") + external = tostring(var.external_monitoring_enabled) } provisioner "local-exec" { @@ -2392,7 +2401,7 @@ set -euo pipefail python3 "${path.module}/../../scripts/monitoring-readiness.py" \ --kubeconfig "${self.triggers.kubeconfig_path}" \ - --namespace "${self.triggers.namespace}" --recover-stale-pending + --namespace "${self.triggers.namespace}" --recover-stale-pending ${self.triggers.external == "true" ? "--external" : ""} EOT } } diff --git a/bootstrap/platform/variables.tf b/bootstrap/platform/variables.tf index 1612536..f460291 100644 --- a/bootstrap/platform/variables.tf +++ b/bootstrap/platform/variables.tf @@ -3,6 +3,16 @@ variable "kubeconfig_path" { default = "/home/jv/.kube/config" } +variable "external_monitoring_enabled" { + type = bool + default = false +} + +variable "external_monitoring_host" { + type = string + default = "" +} + variable "pod_network_cidr" { type = string default = "10.244.0.0/16" diff --git a/homelab.yml b/homelab.yml index f58c5cc..438059c 100644 --- a/homelab.yml +++ b/homelab.yml @@ -147,6 +147,11 @@ hosts: install_dir: /opt/homelab-edge services: + monitoring: + host: debian + external: true + install_dir: /data/homelab-monitoring + service_cidr: 10.43.0.0/16 gitea: host: debian install_dir: /data/homelab-gitea diff --git a/infra/monitoring-debian/README.md b/infra/monitoring-debian/README.md new file mode 100644 index 0000000..8f01a67 --- /dev/null +++ b/infra/monitoring-debian/README.md @@ -0,0 +1,58 @@ +# Debian monitoring + +Prometheus, Alertmanager and Grafana run in the `homelab-prometheus` Compose +project on Debian's local NVMe. The Prometheus Operator, kube-state-metrics, +node exporters and ServiceMonitor/PrometheusRule resources remain in K3s. +Loki and Tempo remain in the cluster. + +Run on Debian: + +```sh +./jeannie monitoring plan +./jeannie monitoring migrate +./jeannie monitoring status +``` + +`migrate` verifies the pinned cluster, validates exported configuration using +promtool/amtool, stops only the three backends using the existing Helm release, +then copies their offline volumes. It preserves the original PVCs and stores +compressed archives, PVC identities and original Helm values under +`/data/homelab-monitoring/backup`. Grafana's existing SQLite database is copied +using SQLite's backup API, preserving users, saved dashboards and Dex account +links. Existing seven-day Prometheus retention still applies; backup archives +remain independent of TSDB retention. + +The chart keeps the backend controllers intentionally at zero replicas. +A post-renderer retains their Service names and supplies Debian Endpoints, +preserving in-cluster URLs and ServiceMonitor discovery. It supports Helm 3 +executables and an isolated Helm 4 postrenderer plugin. OpenTofu uses the same +desired configuration, so a subsequent `./jeannie platform monitoring` keeps +the backends on Debian. + +The OCI edge forwards the three public hostnames directly to Debian through +Tailscale. Migration uses an Nginx-only validated reload, without pulling or +recreating the other containers on the small edge VM. ACME challenge paths are +retained for certificate renewal. Grafana retains its public URL, Dex client ID/secret and datasource +UIDs. The cluster Grafana OAuth secret remains the source consumed by the +existing SOPS/Dex deployment pipeline; this migration does not rotate it. + +`./jeannie monitoring apply` is idempotent after migration. `refresh` updates +Operator-generated discovery, alert rules, datasources and dashboard files. +The installed `homelab-monitoring-refresh.timer` runs every five minutes under +the Debian operator account, using a durable installed script rather than the +checkout used for migration. It refreshes an hour-lived token for the existing +Prometheus service account; containers do not receive the administrator +kubeconfig. Existing configuration remains running if the cluster API is down. +Dashboard files reload automatically; changes to Grafana OAuth configuration +or datasources restart Grafana. `grafana-dashboards apply` also refreshes the +external instance. + +Only routes for the declared cluster service CIDR and discovered Calico pools +are installed through the Orange Pi. Configuration and backups live in a +private installation directory. Docker memory caps are 1536 MiB for Prometheus, +512 MiB for Grafana and 256 MiB for Alertmanager. Coordinate LLM benchmarks +with the remaining Debian memory; moving monitoring does not reserve host RAM. + +The migration does not repair the Orange Pi SSD or migrate Loki. A down Loki +target remains a real failure, rather than being hidden by this move. Original +PVCs and backups should be retained until recovery requirements are reviewed. diff --git a/infra/monitoring-debian/compose.yaml b/infra/monitoring-debian/compose.yaml new file mode 100644 index 0000000..7a15c52 --- /dev/null +++ b/infra/monitoring-debian/compose.yaml @@ -0,0 +1,68 @@ +name: homelab-prometheus +services: + prometheus: + image: prom/prometheus:v3.11.3 + container_name: homelab-prometheus + network_mode: host + restart: unless-stopped + mem_limit: 1536m + cpus: 1.5 + healthcheck: + test: [CMD, wget, -q, -O, /dev/null, 'http://127.0.0.1:19090/-/ready'] + interval: 15s + timeout: 5s + retries: 3 + start_period: 120s + command: + - --config.file=/etc/prometheus/prometheus.yaml + - --storage.tsdb.path=/prometheus + - --storage.tsdb.retention.time=7d + - --storage.tsdb.retention.size=12GB + - --web.listen-address=:19090 + - --web.enable-lifecycle + volumes: + - ./config/prometheus:/etc/prometheus:ro + - ./config/k8s:/var/run/secrets/kubernetes.io/serviceaccount:ro + - ./data/prometheus:/prometheus + alertmanager: + image: prom/alertmanager:v0.32.1 + container_name: homelab-alertmanager + network_mode: host + restart: unless-stopped + mem_limit: 256m + cpus: 0.5 + healthcheck: + test: [CMD, wget, -q, -O, /dev/null, 'http://127.0.0.1:19093/-/ready'] + interval: 15s + timeout: 5s + retries: 3 + command: + - --config.file=/etc/alertmanager/alertmanager.yaml + - --storage.path=/alertmanager + - --web.listen-address=:19093 + - --cluster.listen-address= + volumes: + - ./config/alertmanager:/etc/alertmanager:ro + - ./data/alertmanager:/alertmanager + grafana: + image: grafana/grafana:13.0.1-security-01 + container_name: homelab-grafana + network_mode: host + restart: unless-stopped + mem_limit: 512m + cpus: 1 + healthcheck: + test: [CMD, wget, -q, -O, /dev/null, 'http://127.0.0.1:13000/api/health'] + interval: 15s + timeout: 5s + retries: 3 + start_period: 60s + environment: + GF_SERVER_HTTP_PORT: '13000' + GF_PATHS_CONFIG: /etc/grafana/grafana.ini + GF_PATHS_PROVISIONING: /etc/grafana/provisioning + GF_AUTH_GENERIC_OAUTH_CLIENT_SECRET__FILE: /etc/grafana/secrets/client-secret + volumes: + - ./config/grafana:/etc/grafana:ro + - ./data/grafana:/var/lib/grafana + - ./data/grafana-search:/var/lib/grafana-search diff --git a/jeannie b/jeannie index d43132f..ea189d4 100755 --- a/jeannie +++ b/jeannie @@ -80,6 +80,7 @@ Build And Bootstrap deploy-api Deploy the Temporal-backed Jeannie API on Debian. deploy-heimdall Deploy the Debian-hosted Heimdall dashboard. deploy-dex Deploy the Debian-hosted Dex SSO stack. + monitoring {plan|migrate|apply|refresh|status|validate} Manage Debian monitoring; preserve cluster discovery and Dex. deploy-office Deploy Nextcloud + ONLYOFFICE online office. deploy-matrix Deploy the Matrix homeserver (Synapse + Element + Postgres). deploy-ai-stack Deploy the Debian-hosted AI gateway stack. @@ -266,6 +267,7 @@ fi runtime_pipeline=false case "${1:-}" in up|cluster|platform|apps|start-cluster) runtime_pipeline=true ;; + monitoring) case "${2:-status}" in migrate|apply) runtime_pipeline=true ;; esac ;; start) [[ "${2:-plan}" != apply ]] || runtime_pipeline=true ;; gateway-lab) [[ "${2:-plan}" != apply ]] || runtime_pipeline=true ;; progressive-lab) case "${2:-plan}" in apply|run|rollback) runtime_pipeline=true ;; esac ;; @@ -622,6 +624,9 @@ case "${1:-}" in grafana-dashboards) grafana_dashboards "$@" ;; + monitoring) + monitoring_debian "${2:-status}" + ;; sso-grafana) grafana_sso "${2:-plan}" ;; diff --git a/lib/jeannie/commands.sh b/lib/jeannie/commands.sh index 54696ec..1a73e44 100644 --- a/lib/jeannie/commands.sh +++ b/lib/jeannie/commands.sh @@ -3088,7 +3088,11 @@ doctor_homelab() { report_ui_check fail "Platform" "Traefik deployment" "./jeannie platform" "" "" status_kubernetes_deployment_ready traefik traefik || failures=$((failures + 1)) report_ui_check fail "Platform" "Traefik LoadBalancer HTTP" "./jeannie edge apply" "" "" status_http_reachable "http://${LAB_TRAEFIK_LB_IP:?LAB_TRAEFIK_LB_IP is required from homelab.yml}/" || failures=$((failures + 1)) report_ui_check fail "Platform" "Argo CD server" "./jeannie platform" "" "" status_kubernetes_deployment_ready argocd argocd-server || failures=$((failures + 1)) - report_ui_check fail "Platform" "Grafana StatefulSet" "./jeannie platform" "" "" status_kubernetes_statefulset_ready monitoring prometheus-stack-grafana || failures=$((failures + 1)) + if truthy "${LAB_MONITORING_EXTERNAL:-false}"; then + report_ui_check fail "Debian Services" "Grafana" "./jeannie monitoring apply" "" "" status_http_ok "http://${LAB_DEBIAN_LAN_IP}:13000/api/health" || failures=$((failures + 1)) + else + report_ui_check fail "Platform" "Grafana StatefulSet" "./jeannie platform" "" "" status_kubernetes_statefulset_ready monitoring prometheus-stack-grafana || failures=$((failures + 1)) + fi report_ui_check fail "Applications" "Website deployment" "./jeannie apps" "" "" status_kubernetes_deployment_ready website-production php-website-deployment || failures=$((failures + 1)) report_ui_check fail "Applications" "Demos deployment" "./jeannie apps" "" "" status_kubernetes_deployment_ready demos-static demos-static || failures=$((failures + 1)) diff --git a/lib/jeannie/env.sh b/lib/jeannie/env.sh index 49c1ba6..0a83154 100644 --- a/lib/jeannie/env.sh +++ b/lib/jeannie/env.sh @@ -44,6 +44,9 @@ mapping = { "hosts.oci_edge.tailscale_ip": "LAB_EDGE_TAILSCALE_IP", "hosts.oci_edge.install_dir": "LAB_EDGE_INSTALL_DIR", "services.gitea.http_port": "LAB_GITEA_HTTP_PORT", + "services.monitoring.external": "LAB_MONITORING_EXTERNAL", + "services.monitoring.install_dir": "LAB_MONITORING_INSTALL_DIR", + "services.monitoring.service_cidr": "LAB_MONITORING_SERVICE_CIDR", "services.gitea.ssh_port": "LAB_GITEA_SSH_PORT", "services.gitea.root_url": "LAB_GITEA_ROOT_URL", "services.heimdall.install_dir": "LAB_HEIMDALL_INSTALL_DIR", @@ -325,6 +328,11 @@ export_homelab_inventory_tf_vars() { export_if_unset TF_VAR_oidc_backend_host "${LAB_DEX_BACKEND_HOST:-${LAB_DEBIAN_TAILSCALE_IP:-}}" export_if_unset TF_VAR_oidc_backend_port "${LAB_DEX_HTTP_PORT:-}" export_if_unset TF_VAR_grafana_oidc_url "${LAB_DEX_PUBLIC_URL:-}" + export_if_unset TF_VAR_external_monitoring_enabled "${LAB_MONITORING_EXTERNAL:-false}" + export_if_unset TF_VAR_external_monitoring_host "${LAB_DEBIAN_LAN_IP:-}" + case "${LAB_MONITORING_EXTERNAL:-false}" in + true|True|TRUE|1|yes|YES) export_if_unset TF_VAR_monitoring_backend_host "${LAB_DEBIAN_TAILSCALE_IP:-}" ;; + esac export_if_unset TF_VAR_grafana_public_url "https://grafana.${LAB_DOMAIN:-}" export_if_unset TF_VAR_gitea_public_url "${LAB_GITEA_ROOT_URL:-}" export_if_unset TF_VAR_gitea_auth_source_name "${LAB_GITEA_DEX_SOURCE_NAME:-dex}" diff --git a/lib/jeannie/pipeline.sh b/lib/jeannie/pipeline.sh index ca76716..c90ed9c 100644 --- a/lib/jeannie/pipeline.sh +++ b/lib/jeannie/pipeline.sh @@ -17,6 +17,62 @@ configure_platform_grafana_sso() { fi } +monitoring_debian() { + local action="${1:-status}" root="${LAB_MONITORING_INSTALL_DIR:-/data/homelab-monitoring}" + require_debian_server "monitoring" + case "${action}" in + plan) + echo "Move Prometheus, Alertmanager and Grafana 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|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 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 + 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) +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 && @@ -1389,7 +1445,8 @@ grafana_sso() { apply) deploy_dex configure_grafana_dex_secret - run_tofu_stack "bootstrap/platform" + 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 @@ -7962,9 +8019,12 @@ platform_apply() { 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 || return 1 + --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 } diff --git a/scripts/grafana-dashboards b/scripts/grafana-dashboards index d9ca30d..6daa5f1 100755 --- a/scripts/grafana-dashboards +++ b/scripts/grafana-dashboards @@ -47,6 +47,10 @@ apply_dashboards() { kubectl --kubeconfig "$KUBECONFIG_PATH" -n "$NAMESPACE" annotate configmap "$name" grafana_folder=Homelab --overwrite done < <(list_dashboards) + if [[ -f "${LAB_MONITORING_INSTALL_DIR:-/data/homelab-monitoring}/migration-complete.json" ]]; then + python3 "${LAB_MONITORING_INSTALL_DIR:-/data/homelab-monitoring}/manager.py" refresh --root "${LAB_MONITORING_INSTALL_DIR:-/data/homelab-monitoring}" + return + fi echo "Restarting Grafana so the sidecar reloads dashboards..." if kubectl --kubeconfig "$KUBECONFIG_PATH" -n "$NAMESPACE" get deployment prometheus-stack-grafana >/dev/null 2>&1; then grafana_workload="deployment/prometheus-stack-grafana" diff --git a/scripts/monitoring-debian.py b/scripts/monitoring-debian.py new file mode 100644 index 0000000..31199c6 --- /dev/null +++ b/scripts/monitoring-debian.py @@ -0,0 +1,480 @@ +#!/usr/bin/env python3 +"""Jeannie-managed migration and refresh of the Debian monitoring backends.""" +import argparse +import base64 +import configparser +import fcntl +import gzip +import hashlib +import ipaddress +import json +import os +from pathlib import Path +import shlex +import shutil +import re +import sqlite3 +import subprocess +import sys +import tarfile +import tempfile +import time +import urllib.error +import urllib.parse +import urllib.request +import yaml + +PROM = 'prometheus-stack-kube-prom-prometheus' +ALERT = 'prometheus-stack-kube-prom-alertmanager' +GRAFANA = 'prometheus-stack-grafana' +PORTS = {PROM: 19090, ALERT: 19093, GRAFANA: 13000} + + +def run(args, **kwargs): + result = subprocess.run([str(a) for a in args], capture_output=True, **kwargs) + if result.returncode: + # Commands can contain secrets or tokens; never include argv/stdout. + raise RuntimeError(f'{Path(str(args[0])).name} failed: ' + result.stderr.decode(errors='replace')[-1200:]) + return result.stdout + + +def write(path, content, mode=0o640): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(path.name + '.new') + temporary.write_bytes(content.encode() if isinstance(content, str) else content) + temporary.chmod(mode) + temporary.replace(path) + + +def external_config(config, api, services=None): + """Retain Operator discovery/relabeling and rules; use external API auth.""" + rendered = json.dumps(config).replace('$(SHARD)', '0').replace('$(POD_NAME)', 'debian-prometheus').replace('$(POD_NAMESPACE)', 'monitoring') + if re.search(r'\$\([A-Z_]+\)', rendered): + raise RuntimeError('Unknown Operator configuration substitution; refusing incomplete discovery') + config = json.loads(rendered) + for job in config.get('scrape_configs', []): + for group in job.get('static_configs', []): + group['targets'] = [service_url('http://' + target, services or {}).removeprefix('http://') + for target in group.get('targets', [])] + for sd in job.get('kubernetes_sd_configs', []): + sd.update(api_server=api, authorization={'credentials_file': '/var/run/secrets/kubernetes.io/serviceaccount/token'}, + tls_config={'ca_file': '/var/run/secrets/kubernetes.io/serviceaccount/ca.crt'}) + config.setdefault('alerting', {})['alertmanagers'] = [ + {'static_configs': [{'targets': ['127.0.0.1:19093']}], 'api_version': 'v2'}] + return config + + +def service_url(url, services): + parsed = urllib.parse.urlsplit(url) + host = parsed.hostname or '' + bits = host.split('.') + if len(bits) >= 2 and (bits[0], bits[1]) in services: + name, namespace = bits[:2] + if name in PORTS: + address, port = '127.0.0.1', PORTS[name] + else: + address, port = services[(name, namespace)], parsed.port + if address and address != 'None': + return urllib.parse.urlunsplit(parsed._replace(netloc=f'{address}:{port}' if port else address)) + return url + + +def validate_dex_client(config, secret, callback): + clients = [c for c in config.get('staticClients', []) if c.get('id') == 'grafana'] + if len(clients) != 1 or clients[0].get('secret') != secret or callback not in clients[0].get('redirectURIs', []): + raise RuntimeError('Deployed Dex client secret or callback does not match Grafana') + + +class Monitoring: + def __init__(self, root): + self.root = Path(root) + self.settings = json.loads((self.root / 'settings.json').read_text()) + self.k = ['kubectl', '--kubeconfig', self.settings['kubeconfig'], '--request-timeout=15s'] + + def get(self, resource, name=None, namespace='monitoring', labels=None): + args = self.k + ['get', resource] + (['-A'] if namespace == '*' else ['-n', namespace] if namespace else []) + if name: + args.append(name) + if labels: + args += ['-l', labels] + return json.loads(run(args + ['-o', 'json'])) + + def verify_identity(self): + uid = self.get('namespace', 'kube-system', None)['metadata']['uid'] + if uid != self.settings['cluster_uid']: + raise RuntimeError('Selected cluster identity changed; refusing monitoring reconciliation') + + def compose(self, *args): + return run(['sudo', '-n', 'docker', 'compose', '-f', self.root / 'compose.yaml', *args]) + + def routes(self): + for network in self.settings['networks']: + subnet = ipaddress.ip_network(network) + if (not subnet.is_private or subnet.prefixlen < 8 or + ipaddress.ip_address(self.settings['debian_ip']) in subnet or + ipaddress.ip_address(self.settings['node_ip']) in subnet): + raise RuntimeError('Refusing a cluster route that could replace host/LAN connectivity') + for network in self.settings['networks']: + run(['sudo', '-n', 'ip', 'route', 'replace', network, 'via', self.settings['node_ip']]) + + def refresh(self, reload=True): + protected = [self.root / 'config/prometheus', self.root / 'config/alertmanager'] + previous = {path: path.read_bytes() for directory in protected for path in directory.rglob('*') if path.is_file()} + try: + self._refresh(reload) + except Exception: + for directory in protected: + for path in directory.rglob('*'): + if path.is_file() and path not in previous: + path.unlink() + for path, content in previous.items(): + write(path, content, 0o644) + raise + + def _refresh(self, reload=True): + self.verify_identity() + self.routes() + root = self.root / 'config' + config_secret = self.get('secret', 'prometheus-' + PROM) + services = {(s['metadata']['name'], s['metadata']['namespace']): s['spec'].get('clusterIP') + for s in self.get('services', namespace='*')['items']} + config = yaml.safe_load(gzip.decompress(base64.b64decode(config_secret['data']['prometheus.yaml.gz']))) + config = external_config(config, self.settings['api'], services) + token = run(self.k + ['-n', 'monitoring', 'create', 'token', PROM, '--duration=1h']).strip() + write(root / 'k8s/token', token, 0o644) + write(root / 'k8s/ca.crt', base64.b64decode(self.settings['ca']), 0o644) + cms = self.get('configmaps')['items'] + rule_count = 0 + rule_files = set() + for cm in cms: + name = cm['metadata']['name'] + if name.startswith('prometheus-' + PROM + '-rulefiles-'): + for filename, value in cm.get('data', {}).items(): + if Path(filename).name != filename: + raise RuntimeError('Invalid rule filename') + destination = root / 'prometheus/rules' / name / filename + rule_files.add(destination) + write(destination, value, 0o644) + rule_count += 1 + for stale in (root / 'prometheus/rules').rglob('*'): + if stale.is_file() and stale not in rule_files: + stale.unlink() + write(root / 'prometheus/prometheus.yaml', yaml.safe_dump(config), 0o644) + secret = self.get('secret', 'alertmanager-' + ALERT) + write(root / 'alertmanager/alertmanager.yaml', base64.b64decode(secret['data']['alertmanager.yaml']), 0o644) + datasource_count = 0 + datasource_documents = [] + datasource_files = set() + for cm in cms: + if cm['metadata'].get('labels', {}).get('grafana_datasource') != '1': + continue + for filename, value in cm.get('data', {}).items(): + document = yaml.safe_load(value) + for ds in document.get('datasources', []): + if isinstance(ds.get('url'), str): + ds['url'] = service_url(ds['url'], services) + datasource_count += 1 + datasource_documents.append(document) + destination = root / 'grafana/provisioning/datasources' / (cm['metadata']['name'] + '-' + Path(filename).name) + datasource_files.add(destination) + write(destination, yaml.safe_dump(document), 0o644) + for stale in (root / 'grafana/provisioning/datasources').glob('*'): + if stale.is_file() and stale not in datasource_files: + stale.unlink() + dashboards = 0 + dashboard_files = set() + for cm in cms: + if cm['metadata'].get('labels', {}).get('grafana_dashboard') != '1': + continue + folder = cm['metadata'].get('annotations', {}).get('grafana_folder', 'General') + # A ConfigMap folder is display data, not a filesystem path. + folder = folder.replace('/', '_').replace('..', '_') + for filename, value in cm.get('data', {}).items(): + json.loads(value) + destination = root / 'grafana/dashboards' / folder / (cm['metadata']['name'] + '-' + Path(filename).name) + dashboard_files.add(destination) + write(destination, value, 0o644) + dashboards += 1 + for stale in (root / 'grafana/dashboards').rglob('*.json'): + if stale not in dashboard_files: + stale.unlink() + write(root / 'grafana/provisioning/dashboards/jeannie.yaml', yaml.safe_dump({ + 'apiVersion': 1, 'providers': [{'name': 'Jeannie', 'orgId': 1, 'type': 'file', + 'disableDeletion': True, 'allowUiUpdates': True, 'updateIntervalSeconds': 30, + 'options': {'path': '/etc/grafana/dashboards', 'foldersFromFilesStructure': True}}]}), 0o644) + ini = self.get('configmap', GRAFANA)['data']['grafana.ini'] + oauth = self.get('secret', 'grafana-dex-oauth')['data']['GF_AUTH_GENERIC_OAUTH_CLIENT_SECRET'] + parsed_ini = configparser.ConfigParser(interpolation=None) + parsed_ini.read_string(ini) + deployed_dex = yaml.safe_load(run(['sudo', '-n', 'cat', self.settings.get('dex_config', '/data/homelab-dex/config.yaml')])) + validate_dex_client(deployed_dex, base64.b64decode(oauth).decode(), + parsed_ini.get('server', 'root_url').rstrip('/') + '/login/generic_oauth') + write(root / 'grafana/grafana.ini', ini, 0o644) + fingerprint = hashlib.sha256((ini + oauth + json.dumps(datasource_documents, sort_keys=True)).encode()).hexdigest() + fingerprint_path = self.root / '.grafana-config.sha256' + previous_fingerprint = fingerprint_path.read_text() if fingerprint_path.exists() else '' + write(root / 'grafana/secrets/client-secret', base64.b64decode(oauth), 0o600) + run(['sudo', '-n', 'chown', '472:472', root / 'grafana/secrets/client-secret']) + if not datasource_count or not dashboards or not rule_count: + raise RuntimeError('Refusing empty dashboards, datasources or rules export') + for directory in [root, *root.rglob('*')]: + if directory.is_dir(): + directory.chmod(0o755) + self.compose('run', '--rm', '--no-deps', '--entrypoint', 'promtool', 'prometheus', 'check', 'config', '/etc/prometheus/prometheus.yaml') + self.compose('run', '--rm', '--no-deps', '--entrypoint', 'amtool', 'alertmanager', 'check-config', '/etc/alertmanager/alertmanager.yaml') + if reload: + for port in (19090, 19093): + self.http(f'http://127.0.0.1:{port}/-/reload', method='POST') + if fingerprint != previous_fingerprint: + self.compose('restart', 'grafana') + write(fingerprint_path, fingerprint) + print(json.dumps({'dashboards': dashboards, 'datasources': datasource_count, 'rule_files': rule_count})) + + @staticmethod + def http(url, method='GET', headers=None): + with urllib.request.urlopen(urllib.request.Request(url, method=method, headers=headers or {}), timeout=15) as response: + return response.read() + + def dashboard_manifest(self): + manifest = self.root / 'backup/grafana-dashboards.json' + if not manifest.exists(): + with tempfile.TemporaryDirectory(dir=self.root) as directory: + with tarfile.open(self.root / 'backup/grafana.tar.gz') as archive: + for member in archive: + name = member.name.removeprefix('./') + if name in ('grafana.db', 'grafana.db-wal', 'grafana.db-shm') and member.isfile(): + with archive.extractfile(member) as source, (Path(directory) / name).open('wb') as target: + shutil.copyfileobj(source, target) + database = sqlite3.connect((Path(directory) / 'grafana.db').as_uri() + '?mode=ro', uri=True) + original = [row[0] for row in database.execute('select uid from dashboard where is_folder=0')] + database.close() + write(manifest, json.dumps(original)) + return set(json.loads(manifest.read_text())) + + def inventory_volumes(self): + result = {} + for pvc in self.get('pvc')['items']: + name = pvc['metadata']['name'] + role = ('grafana' if name == 'storage-' + GRAFANA + '-0' else + 'prometheus' if name.startswith('prometheus-' + PROM + '-db-') else + 'alertmanager' if name.startswith('alertmanager-' + ALERT + '-db-') else None) + if not role: + continue + pv = self.get('pv', pvc['spec']['volumeName'], None) + ref = pv['spec']['claimRef'] + if ref['uid'] != pvc['metadata']['uid'] or ref['namespace'] != 'monitoring': + raise RuntimeError('PVC/PV identity mismatch') + path = pv['spec'].get('local', {}).get('path', '') + if not path.startswith('/data/') or '..' in path.split('/'): + raise RuntimeError('Only identified /data local volumes can be migrated') + result[role] = {'pvc': name, 'uid': pvc['metadata']['uid'], 'pv': pv['metadata']['name'], 'path': path} + if set(result) != {'grafana', 'prometheus', 'alertmanager'}: + raise RuntimeError('Expected exactly the three existing monitoring volumes') + return result + + def helm_external(self): + values = {'prometheus': {'prometheusSpec': {'replicas': 0}}, + 'alertmanager': {'alertmanagerSpec': {'replicas': 0}}, 'grafana': {'replicas': 0}} + write(self.root / 'external-values.yaml', yaml.safe_dump(values)) + release = json.loads(run(['helm', '--kubeconfig', self.settings['kubeconfig'], '-n', 'monitoring', + 'list', '--filter', '^prometheus-stack$', '-o', 'json']))[0] + version = release['chart'].removeprefix('kube-prometheus-stack-') + for name in PORTS: + service = self.get('service', name) + if service['metadata'].get('annotations', {}).get('meta.helm.sh/release-name') != 'prometheus-stack': + raise RuntimeError('Refusing to adopt endpoints of a service not owned by this Helm release') + existing = run(self.k + ['-n', 'monitoring', 'get', 'endpoints', name, '--ignore-not-found', '-o', 'json']) + if existing.strip(): + run(self.k + ['-n', 'monitoring', 'annotate', 'endpoints', name, + 'meta.helm.sh/release-name=prometheus-stack', 'meta.helm.sh/release-namespace=monitoring', '--overwrite']) + run(self.k + ['-n', 'monitoring', 'label', 'endpoints', name, + 'app.kubernetes.io/managed-by=Helm', '--overwrite']) + renderer = str(self.root / 'postrender.py') + environment = os.environ.copy() + if run(['helm', 'version', '--short']).decode().startswith('v4.'): + plugin = self.root / 'helm-plugins/jeannie-monitoring' + write(plugin / 'plugin.yaml', yaml.safe_dump({'apiVersion': 'v1', 'type': 'postrenderer/v1', + 'name': 'jeannie-monitoring', 'version': '1.0.0', 'runtime': 'subprocess', + 'runtimeConfig': {'platformCommand': [{'command': renderer}]}})) + environment['HELM_PLUGINS'] = str(plugin.parent) + renderer = 'jeannie-monitoring' + run(['helm', '--kubeconfig', self.settings['kubeconfig'], '-n', 'monitoring', 'upgrade', 'prometheus-stack', + 'kube-prometheus-stack', '--repo', 'https://prometheus-community.github.io/helm-charts', + '--version', version, '--reuse-values', '-f', self.root / 'external-values.yaml', + '--post-renderer', renderer, '--post-renderer-args', self.settings['debian_ip'], '--timeout', '10m'], env=environment) + + def migrate(self): + self.verify_identity() + run(['sudo', '-n', 'install', '-d', '-m', '750', '-o', '472', '-g', '472', self.root / 'data/grafana-search']) + if (self.root / 'migration-complete.json').exists(): + self.compose('up', '-d') + self.wait_for(self.http_ready) + self.refresh() + self.wait_for(self.validate) + self.install_timer() + return + volumes = self.inventory_volumes() + for role in volumes: + (self.root / 'data' / role).mkdir(parents=True, exist_ok=True) + backup = self.root / 'backup' + backup.mkdir(exist_ok=True) + write(backup / 'volumes.json', json.dumps(volumes, indent=2)) + if not (backup / 'helm-values.yaml').exists(): + write(backup / 'helm-values.yaml', run(['helm', '--kubeconfig', self.settings['kubeconfig'], '-n', 'monitoring', 'get', 'values', 'prometheus-stack', '-o', 'yaml'])) + self.compose('pull') + self.refresh(reload=False) + print('Configuration validated. Stopping only the three in-cluster monitoring backends.', flush=True) + self.helm_external() + deadline = time.monotonic() + 180 + while True: + remaining = [p['metadata']['name'] for p in self.get('pods')['items'] + if p['metadata']['name'] == GRAFANA + '-0' or + p['metadata']['name'].startswith(('prometheus-' + PROM + '-', 'alertmanager-' + ALERT + '-'))] + if not remaining: + break + if time.monotonic() > deadline: + raise RuntimeError('Old monitoring pods did not stop normally; refusing data copy') + time.sleep(3) + for role, volume in volumes.items(): + archive = backup / (role + '.tar.gz') + if not archive.exists(): + print('Backing up and transferring existing ' + role + ' data...', flush=True) + remote = 'findmnt -rn -M /data -o OPTIONS | grep -q "^rw" && sudo -n tar -C ' + shlex.quote(volume['path']) + ' -czf - .' + with archive.with_suffix('.partial').open('wb') as target: + process = subprocess.run(['ssh', '-T', self.settings['node_ssh'], remote], stdout=target, stderr=subprocess.PIPE) + if process.returncode: + raise RuntimeError('Volume backup failed; partial archive retained') + archive.with_suffix('.partial').replace(archive) + destination = self.root / 'data' / role + if not (backup / (role + '.copied')).exists(): + destination.mkdir(parents=True, exist_ok=True) + with tarfile.open(archive) as source: + source.extractall(destination, filter='data') + if role == 'grafana': + database = destination / 'grafana.db' + if not database.exists(): + raise RuntimeError('Existing Grafana database missing; refusing an empty installation') + original = sqlite3.connect(database.as_uri() + '?mode=ro', uri=True) + copied = sqlite3.connect(str(database) + '.consistent') + original.backup(copied) + copied.close(); original.close() + os.replace(str(database) + '.consistent', database) + for suffix in ('-wal', '-shm'): + Path(str(database) + suffix).unlink(missing_ok=True) + connection = sqlite3.connect(database.as_uri() + '?mode=ro', uri=True) + print('Preserved Grafana database dashboards:', connection.execute('select count(*) from dashboard').fetchone()[0]) + connection.close() + run(['sudo', '-n', 'chown', '-R', '472:472' if role == 'grafana' else '65534:65534', destination]) + write(backup / (role + '.copied'), 'copied\n') + self.compose('up', '-d', '--force-recreate') + self.wait_for(self.validate) + write(self.root / 'migration-complete.json', json.dumps({'volumes': volumes, 'cluster_uid': self.settings['cluster_uid']})) + self.install_timer() + + @staticmethod + def wait_for(check): + deadline = time.monotonic() + 180 + while True: + try: + check() + break + except (OSError, ValueError, RuntimeError, urllib.error.URLError): + if time.monotonic() > deadline: + raise + time.sleep(4) + + def install_timer(self): + user = self.settings['user'] + service = (f'[Unit]\nDescription=Refresh external homelab monitoring configuration\nAfter=network-online.target docker.service\n' + f'[Service]\nType=oneshot\nUser={user}\nEnvironment=HOME={self.settings["home"]}\n' + f'ExecStart=/usr/bin/python3 {self.root}/manager.py refresh --root {self.root}\n') + timer = '[Unit]\nDescription=Refresh monitoring discovery, rules and dashboards\n[Timer]\nOnBootSec=45\nOnUnitActiveSec=5min\n[Install]\nWantedBy=timers.target\n' + for filename, content in (('homelab-monitoring-refresh.service', service), ('homelab-monitoring-refresh.timer', timer)): + write(self.root / filename, content) + run(['sudo', '-n', 'install', '-m', '644', self.root / filename, '/etc/systemd/system/' + filename]) + run(['sudo', '-n', 'systemctl', 'daemon-reload']) + run(['sudo', '-n', 'systemctl', 'enable', '--now', 'homelab-monitoring-refresh.timer']) + + def http_ready(self): + for name, port, path in (('prometheus', 19090, '/-/ready'), ('alertmanager', 19093, '/-/ready'), ('grafana', 13000, '/api/health')): + self.http(f'http://127.0.0.1:{port}{path}') + + def validate(self): + self.verify_identity() + self.http_ready() + targets = json.loads(self.http('http://127.0.0.1:19090/api/v1/targets'))['data']['activeTargets'] + print('Prometheus targets:', len(targets), 'up:', sum(t['health'] == 'up' for t in targets)) + if not targets: + raise RuntimeError('Prometheus discovered no scrape targets') + if not any(t['health'] == 'up' and '/prometheus-stack-kube-state-metrics/' in t.get('scrapePool', '') for t in targets): + raise RuntimeError('No healthy kube-state-metrics ServiceMonitor target; discovery/network validation failed') + ini = configparser.ConfigParser(interpolation=None) + ini.read(self.root / 'config/grafana/grafana.ini') + if ini.get('auth.generic_oauth', 'client_id', fallback='') != 'grafana': + raise RuntimeError('Grafana Dex client configuration missing') + req = urllib.request.Request('http://127.0.0.1:13000/login/generic_oauth') + class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, *args, **kwargs): + return None + try: + urllib.request.build_opener(NoRedirect()).open(req, timeout=10) + raise RuntimeError('Grafana did not start an OAuth redirect') + except urllib.error.HTTPError as error: + location = error.headers.get('Location', '') + if error.code != 302 or not location.startswith(ini.get('auth.generic_oauth', 'auth_url')): + raise RuntimeError('Unexpected Grafana OAuth redirect') from None + print('Dex OAuth authorization redirect: verified') + deployed_dex = yaml.safe_load(run(['sudo', '-n', 'cat', self.settings.get('dex_config', '/data/homelab-dex/config.yaml')])) + secret = run(['sudo', '-n', 'cat', self.root / 'config/grafana/secrets/client-secret']).decode() + validate_dex_client(deployed_dex, secret, ini.get('server', 'root_url').rstrip('/') + '/login/generic_oauth') + print('Deployed Dex client secret and callback: match') + admin = self.get('secret', GRAFANA)['data'] + auth = base64.b64encode(base64.b64decode(admin['admin-user']) + b':' + base64.b64decode(admin['admin-password'])).decode() + headers = {'Authorization': 'Basic ' + auth} + dashboards = json.loads(self.http('http://127.0.0.1:13000/api/search?type=dash-db&limit=1000', headers=headers)) + expected = self.dashboard_manifest() + for filename in (self.root / 'config/grafana/dashboards').rglob('*.json'): + uid = json.loads(filename.read_text()).get('uid') + if uid: + expected.add(uid) + if not expected: + raise RuntimeError('No dashboard UID baseline available for preservation validation') + if expected - {d['uid'] for d in dashboards}: + raise RuntimeError('Grafana dashboard UIDs from the original database are missing') + sources = json.loads(self.http('http://127.0.0.1:13000/api/datasources', headers=headers)) + actual_sources = {s.get('uid'): s for s in sources} + for filename in (self.root / 'config/grafana/provisioning/datasources').glob('*'): + for desired in yaml.safe_load(filename.read_text()).get('datasources', []): + uid = desired.get('uid') + if uid and (uid not in actual_sources or + actual_sources[uid].get('url', '').rstrip('/') != desired.get('url', '').rstrip('/')): + raise RuntimeError('Expected datasource UID or backend URL was not preserved') + print(f'Backup/provisioned dashboard UIDs verified: {len(expected)}; current dashboards: {len(dashboards)}') + for name in ('prometheus', 'alertmanager', 'grafana'): + print(name + ': ready') + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('action', choices=['migrate', 'apply', 'refresh', 'validate', 'status']) + parser.add_argument('--root', default='/data/homelab-monitoring') + args = parser.parse_args() + os.umask(0o027) + manager = Monitoring(args.root) + with (manager.root / '.lock').open('w') as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + if args.action in ('migrate', 'apply'): + manager.migrate() + elif args.action == 'refresh': + manager.refresh() + else: + manager.validate() + + +if __name__ == '__main__': + try: + main() + except (OSError, ValueError, RuntimeError, urllib.error.URLError) as error: + print('Monitoring: ' + str(error), file=sys.stderr) + raise SystemExit(1) diff --git a/scripts/monitoring-helm-postrender.py b/scripts/monitoring-helm-postrender.py new file mode 100755 index 0000000..93c93c9 --- /dev/null +++ b/scripts/monitoring-helm-postrender.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python3 +"""Keep chart service identities while moving their backends to Debian.""" +import ipaddress +import sys +import yaml + + +def render(documents, host): + ipaddress.IPv4Address(host) + ports = {'prometheus-stack-grafana': 13000, + 'prometheus-stack-kube-prom-prometheus': 19090, + 'prometheus-stack-kube-prom-alertmanager': 19093} + output = [] + for item in documents: + if not item: + continue + name = item.get('metadata', {}).get('name') + if item.get('kind') == 'Service' and name in ports: + item['spec'].pop('selector', None) + web = next(p for p in item['spec']['ports'] if p['name'] in ('http-web', 'http-web-svc')) + web['targetPort'] = ports[name] + item['spec']['ports'] = [web] + output.append({'apiVersion': 'v1', 'kind': 'Endpoints', + 'metadata': {'name': name, 'namespace': item['metadata']['namespace']}, + 'subsets': [{'addresses': [{'ip': host}], + 'ports': [{'name': web['name'], 'port': ports[name], 'protocol': 'TCP'}]}]}) + output.append(item) + return output + + +if __name__ == '__main__': + raw = sys.stdin.read() + if len(sys.argv) < 2 or not sys.argv[1]: + sys.stdout.write(raw) + else: + yaml.safe_dump_all(render(yaml.safe_load_all(raw), sys.argv[1]), sys.stdout, sort_keys=False) diff --git a/scripts/monitoring-readiness.py b/scripts/monitoring-readiness.py index a537665..4cd6137 100644 --- a/scripts/monitoring-readiness.py +++ b/scripts/monitoring-readiness.py @@ -17,7 +17,7 @@ def owned(name, release): ) -def readiness_errors(items, release): +def readiness_errors(items, release, external=False): """Check desired controller state, including Operator-created StatefulSets.""" errors = [] roles = set() @@ -52,9 +52,9 @@ def readiness_errors(items, release): complete = complete and status.get("currentRevision") == status.get("updateRevision") if kind == "DaemonSet" and not desired: complete = False - if name == release + "-grafana" and not desired: + if name == release + "-grafana" and not desired and not external: complete = False - if name.startswith("prometheus-" + release + "-") and not desired: + if name.startswith("prometheus-" + release + "-") and not desired and not external: complete = False if not complete: errors.append(f"{kind}/{name}: ready={ready}/{desired} updated={updated} observed={observed}") @@ -230,6 +230,7 @@ def main(): parser.add_argument("--namespace", default="monitoring") parser.add_argument("--release", default="prometheus-stack") parser.add_argument("--timeout", type=int, default=300) + parser.add_argument("--external", action="store_true", help="Backends intentionally run on Debian; check cluster collectors") parser.add_argument("--recover-stale-pending", action="store_true", help="Replace only a stale, unscheduled Grafana pod blocked on an old priority revision") args = parser.parse_args() @@ -240,7 +241,7 @@ def main(): while True: try: items = kubectl(args, "-n", args.namespace, "get", "deployment,statefulset,daemonset", "-o", "json")["items"] - errors = readiness_errors(items, args.release) + errors = readiness_errors(items, args.release, args.external) if errors and args.recover_stale_pending: recover_stale_grafana(args, items) except (RuntimeError, subprocess.TimeoutExpired, ValueError, KeyError) as exc: diff --git a/scripts/validate-homelab b/scripts/validate-homelab index 3799f3c..77a4315 100755 --- a/scripts/validate-homelab +++ b/scripts/validate-homelab @@ -128,6 +128,8 @@ validate_unit_tests() { python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_go_launchers.py' python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_doctor_focus.py' python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_stale_pod_candidate.py' + python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_monitoring_debian.py' + python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_monitoring_readiness.py' python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_doctor_k3s_storage.py' python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_holmes_evidence.py' if [[ -x "${LAB_HOLMES_ADAPTER_PYTHON:-/home/jv/.local/share/pipx/venvs/holmesgpt/bin/python}" ]]; then diff --git a/tests/jeannie/test_monitoring_debian.py b/tests/jeannie/test_monitoring_debian.py new file mode 100644 index 0000000..d54e04f --- /dev/null +++ b/tests/jeannie/test_monitoring_debian.py @@ -0,0 +1,107 @@ +import copy +import tempfile +import importlib.util +from pathlib import Path +import unittest +from unittest.mock import patch + +ROOT = Path(__file__).resolve().parents[2] + + +def module(name): + spec = importlib.util.spec_from_file_location(name, ROOT / 'scripts' / (name + '.py')) + value = importlib.util.module_from_spec(spec) + spec.loader.exec_module(value) + return value + + +MANAGER = module('monitoring-debian') +RENDER = module('monitoring-helm-postrender') + + +class MonitoringMigrationTests(unittest.TestCase): + def test_failed_export_restores_last_valid_rules_and_configuration(self): + with tempfile.TemporaryDirectory() as directory: + manager = MANAGER.Monitoring.__new__(MANAGER.Monitoring) + manager.root = Path(directory) + original = manager.root / 'config/prometheus/prometheus.yaml' + original.parent.mkdir(parents=True) + original.write_text('last valid configuration') + new_rule = original.parent / 'invalid-rule.yaml' + def invalid_export(_reload): + original.write_text('invalid replacement') + new_rule.write_text('invalid rule') + raise RuntimeError('promtool rejected configuration') + with patch.object(manager, '_refresh', side_effect=invalid_export), self.assertRaises(RuntimeError): + manager.refresh() + self.assertEqual(original.read_text(), 'last valid configuration') + self.assertFalse(new_rule.exists()) + + def test_routes_cannot_override_lan_or_default_connectivity(self): + manager = MANAGER.Monitoring.__new__(MANAGER.Monitoring) + manager.settings = {'networks': ['192.168.100.0/24'], 'debian_ip': '192.168.100.73', 'node_ip': '192.168.100.80'} + with patch.object(MANAGER, 'run') as execute, self.assertRaises(RuntimeError): + manager.routes() + execute.assert_not_called() + def test_service_resolution_reads_all_namespaces(self): + manager = MANAGER.Monitoring.__new__(MANAGER.Monitoring) + manager.k = ['kubectl'] + with patch.object(MANAGER, 'run', return_value=b'{"items":[]}') as query: + manager.get('services', namespace='*') + self.assertIn('-A', query.call_args.args[0]) + self.assertLess(query.call_args.args[0].index('get'), query.call_args.args[0].index('-A')) + def test_operator_discovery_rules_and_labels_are_preserved(self): + source = {'rule_files': ['/rules/a.yaml'], 'global': {'external_labels': {'cluster_uid': 'pinned'}}, + 'scrape_configs': [{'job_name': 'serviceMonitor/lab', + 'kubernetes_sd_configs': [{'role': 'endpoints', 'namespaces': {'names': ['lab']}}], + 'relabel_configs': [{'action': 'keep', 'regex': 'my-service'}]}]} + original = copy.deepcopy(source) + result = MANAGER.external_config(source, 'https://192.168.100.80:6443') + self.assertEqual(result['rule_files'], source['rule_files']) + self.assertEqual(result['global'], source['global']) + self.assertEqual(result['scrape_configs'][0]['relabel_configs'], source['scrape_configs'][0]['relabel_configs']) + sd = result['scrape_configs'][0]['kubernetes_sd_configs'][0] + self.assertEqual(sd['api_server'], 'https://192.168.100.80:6443') + self.assertIn('credentials_file', sd['authorization']) + self.assertEqual(source, original) + + def test_services_keep_identity_and_redirect_to_debian(self): + svc = {'apiVersion': 'v1', 'kind': 'Service', + 'metadata': {'name': MANAGER.GRAFANA, 'namespace': 'monitoring', 'labels': {'existing': 'label'}}, + 'spec': {'selector': {'old': 'pod'}, 'ports': [{'name': 'http-web', 'port': 80, 'targetPort': 'grafana'}]}} + output = RENDER.render([svc], '192.168.100.73') + self.assertEqual(output[0]['kind'], 'Endpoints') + self.assertEqual(output[0]['subsets'][0]['addresses'], [{'ip': '192.168.100.73'}]) + self.assertNotIn('selector', output[1]['spec']) + self.assertEqual(output[1]['metadata']['labels'], {'existing': 'label'}) + self.assertEqual(output[1]['spec']['ports'][0]['port'], 80) + self.assertEqual(output[1]['spec']['ports'][0]['targetPort'], 13000) + + def test_datasource_urls_preserve_uids_and_external_oidc(self): + services = {(MANAGER.PROM, 'monitoring'): '10.43.1.2', ('otel-lab-tempo', 'monitoring'): '10.43.1.3'} + self.assertEqual(MANAGER.service_url('http://' + MANAGER.PROM + '.monitoring.svc:9090', services), 'http://127.0.0.1:19090') + self.assertEqual(MANAGER.service_url('http://otel-lab-tempo.monitoring.svc:3200', services), 'http://10.43.1.3:3200') + self.assertEqual(MANAGER.service_url('https://auth.example.org/token', services), 'https://auth.example.org/token') + + def test_invalid_endpoint_address_fails_closed(self): + with self.assertRaises(ValueError): + RENDER.render([], '127.0.0.1;invalid') + + def test_dex_validation_rejects_secret_or_callback_drift(self): + config = {'staticClients': [{'id': 'grafana', 'secret': 'test-value', 'redirectURIs': ['https://grafana.test/login/generic_oauth']}]} + MANAGER.validate_dex_client(config, 'test-value', 'https://grafana.test/login/generic_oauth') + for secret, callback in (('different', 'https://grafana.test/login/generic_oauth'), ('test-value', 'https://wrong.test')): + with self.assertRaises(RuntimeError): + MANAGER.validate_dex_client(config, secret, callback) + + def test_operator_shard_placeholders_are_expanded_before_relabeling(self): + result = MANAGER.external_config({'global': {'external_labels': {'prometheus_replica': '$(POD_NAME)'}}, + 'scrape_configs': [{'relabel_configs': [{'action': 'keep', 'regex': '$(SHARD);|.+;.+'}]}]}, 'https://api') + self.assertEqual(result['scrape_configs'][0]['relabel_configs'][0]['regex'], '0;|.+;.+') + self.assertEqual(result['global']['external_labels']['prometheus_replica'], 'debian-prometheus') + with self.assertRaises(RuntimeError): + MANAGER.external_config({'global': {'unknown': '$(UNKNOWN_VALUE)'}}, 'https://api') + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/jeannie/test_monitoring_readiness.py b/tests/jeannie/test_monitoring_readiness.py index 808ec36..7471c38 100644 --- a/tests/jeannie/test_monitoring_readiness.py +++ b/tests/jeannie/test_monitoring_readiness.py @@ -64,6 +64,14 @@ class MonitoringReadinessTests(unittest.TestCase): self.items[-1]["status"].update(replicas=0, readyReplicas=0, updatedReplicas=0) self.assertTrue(MODULE.readiness_errors(self.items, "prometheus-stack")) + def test_external_mode_accepts_intentionally_zero_backend_replicas(self): + for item in self.items: + if item['kind'] == 'StatefulSet': + item['spec']['replicas'] = 0 + item['status']['readyReplicas'] = 0 + item['status']['updatedReplicas'] = 0 + self.assertEqual(MODULE.readiness_errors(self.items, 'prometheus-stack', external=True), []) + class StaleGrafanaRecoveryTests(unittest.TestCase): def setUp(self):