#!/usr/bin/env bash # name: metrics-agent # summary: Ship this machine's host and container metrics to the estate's Prometheus # # Run as root on a VM (proxmox-vm's first-boot snippet does this): # curl -fsSL https://install.xaritomi.xyz/metrics-agent | sudo bash # HOST_ENV=prod ... to stamp env=prod (default: dev) # # Two modes, both from gitlab.com/xaritomi/observability and copied below: # - Docker present (or METRICS_DOCKER=install, which proxmox-vm sets for new # VMs): the generic Alloy + cadvisor containers (agents/generic), with # container metrics. # - No Docker: Alloy as a system service from Grafana's apt repo, host # metrics only (agents/host). Proxmox nodes, k8s nodes and plain VMs get # this; Docker is never installed on them (it would clash with k8s's own # container runtime). # METRICS ONLY: # logs need per-app labels first. The push credential is never embedded (this # site is public). It is read, in order, from: # 1. 1Password, if /etc/op-service-account.env and op are present (midgard VMs) # 2. /etc/metrics-push.env (PUSH_USER=, PUSH_PASSWORD=), injected per VM by # proxmox-vm --metrics-push on nodes without a vault credential (zerene) # With neither, it says so and exits 0: the VM is fine, just unmonitored. # Idempotent: re-running rewrites the files and restarts the agent. set -euo pipefail DIR=/opt/observability-agent log() { printf '[metrics-agent] %s\n' "$*"; } creds() { PUSH_USER=""; PUSH_PASSWORD="" if [ -r /etc/op-service-account.env ] && command -v op >/dev/null 2>&1; then set -a; . /etc/op-service-account.env; set +a PUSH_USER=$(op read "op://mimir/observability-push-basicauth/username" /dev/null || true) PUSH_PASSWORD=$(op read "op://mimir/observability-push-basicauth/password" /dev/null || true) fi if { [ -z "$PUSH_USER" ] || [ -z "$PUSH_PASSWORD" ]; } && [ -r /etc/metrics-push.env ]; then PUSH_USER=$(sed -n 's/^PUSH_USER=//p' /etc/metrics-push.env | head -1) PUSH_PASSWORD=$(sed -n 's/^PUSH_PASSWORD=//p' /etc/metrics-push.env | head -1) fi } docker_up() { if ! command -v docker >/dev/null 2>&1; then log "installing docker" DEBIAN_FRONTEND=noninteractive apt-get update -qq DEBIAN_FRONTEND=noninteractive apt-get install -y -qq docker.io docker-compose-v2 >/dev/null mkdir -p /etc/docker [ -e /etc/docker/daemon.json ] || echo '{"log-driver":"json-file","log-opts":{"max-size":"10m","max-file":"3"}}' > /etc/docker/daemon.json systemctl enable --now docker fi # Docker from some installs has no compose plugin (seen on wings-dev). if ! docker compose version >/dev/null 2>&1; then log "installing the docker compose plugin" DEBIAN_FRONTEND=noninteractive apt-get install -y -qq docker-compose-v2 >/dev/null 2>&1 \ || DEBIAN_FRONTEND=noninteractive apt-get install -y -qq docker-compose-plugin >/dev/null fi } host_only() { log "no docker: installing alloy as a system service (host metrics only)" export DEBIAN_FRONTEND=noninteractive apt-get install -y -qq gpg curl ca-certificates >/dev/null mkdir -p /etc/apt/keyrings [ -s /etc/apt/keyrings/grafana.gpg ] || curl -fsSL https://apt.grafana.com/gpg.key | gpg --dearmor -o /etc/apt/keyrings/grafana.gpg echo "deb [signed-by=/etc/apt/keyrings/grafana.gpg] https://apt.grafana.com stable main" > /etc/apt/sources.list.d/grafana.list apt-get update -qq # Pinned to the version the Docker agent runs; --allow-downgrades so a re-run can bring a host back to it. apt-get install -y -qq --allow-downgrades "alloy=${ALLOY_VERSION:-1.20.1}-1" >/dev/null mkdir -p /etc/alloy cat > /etc/alloy/config.alloy <<'HOST_CONFIG_END' // The host-only agent: this machine's own metrics (unix exporter) and the // agent's health, for a host without Docker (Proxmox nodes, k8s nodes, plain // VMs). Runs as the alloy system service from Grafana's apt repo, so the // exporter reads the real /proc and /sys directly. Identity comes from // /etc/default/alloy: // HOST_LABEL the machine's hostname, stamped as host= on every series // HOST_ENV prod or dev, stamped as env= // PUSH_USER / PUSH_PASSWORD op://mimir/observability-push-basicauth logging { level = "info" format = "logfmt" } prometheus.exporter.unix "host" { filesystem { mount_points_exclude = "^/(sys|proc|dev|run|var/lib/(docker|containerd|kubelet))($|/)" fs_types_exclude = "^(autofs|binfmt_misc|bpf|cgroup2?|configfs|debugfs|devpts|devtmpfs|fusectl|hugetlbfs|iso9660|mqueue|nsfs|overlay|proc|procfs|pstore|rpc_pipefs|securityfs|selinuxfs|squashfs|sysfs|tmpfs|tracefs)$" } } prometheus.scrape "host_exporters" { targets = prometheus.exporter.unix.host.targets forward_to = [prometheus.relabel.add_identity.receiver] scrape_interval = "15s" } prometheus.exporter.self "agent" { } prometheus.scrape "agent" { targets = prometheus.exporter.self.agent.targets forward_to = [prometheus.relabel.add_identity.receiver] scrape_interval = "30s" } prometheus.relabel "add_identity" { forward_to = [prometheus.remote_write.central.receiver] rule { target_label = "host" replacement = sys.env("HOST_LABEL") } rule { target_label = "app" replacement = "host" } rule { target_label = "env" replacement = sys.env("HOST_ENV") } rule { target_label = "instance" replacement = sys.env("HOST_LABEL") } } prometheus.remote_write "central" { endpoint { url = "https://push.xaritomi.xyz/api/v1/write" basic_auth { username = sys.env("PUSH_USER") password = sys.env("PUSH_PASSWORD") } queue_config { capacity = 2500 max_shards = 5 max_samples_per_send = 500 } } } HOST_CONFIG_END ( umask 077 printf 'CONFIG_FILE="/etc/alloy/config.alloy"\nCUSTOM_ARGS="--server.http.listen-addr=127.0.0.1:12345"\nRESTART_ON_UPGRADE=true\nHOST_LABEL=%s\nHOST_ENV=%s\nPUSH_USER=%s\nPUSH_PASSWORD=%s\n' \ "$(hostname)" "${HOST_ENV:-dev}" "$PUSH_USER" "$PUSH_PASSWORD" > /etc/default/alloy ) # The package ships this file 0644, and overwriting keeps the mode: it holds the push password. chmod 600 /etc/default/alloy; chown root:root /etc/default/alloy systemctl enable alloy >/dev/null 2>&1 # Alloy reads its config only at start (observability/agents/README.md). systemctl restart alloy } write_files() { mkdir -p "$DIR/config" cat > "$DIR/docker-compose.yml" <<'EOF' # The generic agent: host and container METRICS only, for any VM with Docker. # Logs are not shipped from here: each app needs its own app/env labels first # (see ../README.md, "To onboard a host"). The hetzner-prod agent is the # full-featured one; this is the same building blocks minus the app parts. name: observability-agent services: alloy: image: grafana/alloy:v1.20.1 container_name: alloy restart: unless-stopped env_file: .env command: - run - --server.http.listen-addr=0.0.0.0:12345 - --storage.path=/var/lib/alloy/data - /etc/alloy/config.alloy volumes: # Directory mount, not a single file: a replaced file's inode leaves the # container serving stale config with no warning. - ./config:/etc/alloy:ro - /proc:/host/proc:ro - /sys:/host/sys:ro - /:/host/root:ro,rslave - /run/udev:/run/udev:ro - alloy_data:/var/lib/alloy/data ports: - '127.0.0.1:12345:12345' mem_limit: 256m # As on hetzner-prod: privileged and credential-free; only Alloy scrapes it. # No --docker_only (on Docker 29 it strips the name label); nameless series # are dropped in the agent's relabel instead. cadvisor: image: gcr.io/cadvisor/cadvisor:v0.49.1 container_name: cadvisor restart: unless-stopped privileged: true # Docker 29 with the containerd image store (driver-type # io.containerd.snapshotter.v1) hides containers from cadvisor's docker # factory: even v0.52.1 finds none. Its containerd factory, pointed at # Docker's own "moby" namespace, sees them, named by container ID rather # than by name. install.sh sets CADVISOR_CONTAINERD_NS=moby on those hosts; # elsewhere the default (k8s.io) leaves the docker factory in charge. command: - --housekeeping_interval=15s - --containerd-namespace=${CADVISOR_CONTAINERD_NS:-moby} devices: - /dev/kmsg volumes: - /:/rootfs:ro - /var/run:/var/run:ro - /sys:/sys:ro - /var/lib/docker/:/var/lib/docker:ro - /dev/disk/:/dev/disk:ro mem_limit: 256m volumes: alloy_data: EOF cat > "$DIR/config/config.alloy" <<'EOF' // The generic agent: host metrics (unix exporter), container metrics (cadvisor) // and the agent's own health, for any VM with Docker. Metrics only; see // ../docker-compose.yml. Identity comes from the host's .env: // HOST_LABEL the machine's hostname, stamped as host= on every series // HOST_ENV prod or dev, stamped as env= // PUSH_USER / PUSH_PASSWORD op://mimir/observability-push-basicauth logging { level = "info" format = "logfmt" } // Host paths, not the container's: otherwise the exporter reports the // container's own filesystem, memory and disks. prometheus.exporter.unix "host" { procfs_path = "/host/proc" sysfs_path = "/host/sys" rootfs_path = "/host/root" filesystem { mount_points_exclude = "^/(sys|proc|dev|host|etc|run/credentials)($|/)" } } prometheus.scrape "host_exporters" { targets = prometheus.exporter.unix.host.targets forward_to = [prometheus.relabel.add_identity.receiver] scrape_interval = "15s" } prometheus.scrape "cadvisor" { targets = [{ __address__ = "cadvisor:8080", instance = sys.env("HOST_LABEL"), }] forward_to = [prometheus.relabel.cadvisor_identity.receiver] scrape_interval = "15s" } prometheus.relabel "cadvisor_identity" { forward_to = [prometheus.remote_write.central.receiver] rule { target_label = "host" replacement = sys.env("HOST_LABEL") } rule { target_label = "env" replacement = sys.env("HOST_ENV") } // A container's app is its compose project; anything else is the host. rule { source_labels = ["container_label_com_docker_compose_project"] target_label = "app" } rule { source_labels = ["app"] regex = "" replacement = "host" target_label = "app" } // Nameless pseudo-containers (the host's own cgroups), but keep cadvisor's // own `up` series, which has no name label either. rule { source_labels = ["__name__", "name"] separator = ";" regex = "container_.*;" action = "drop" } rule { regex = "container_label_com_docker_compose_(config_hash|container_number|depends_on|image|oneoff|project_config_files|project_working_dir|version)" action = "labeldrop" } } prometheus.relabel "add_identity" { forward_to = [prometheus.remote_write.central.receiver] rule { target_label = "host" replacement = sys.env("HOST_LABEL") } rule { target_label = "app" replacement = "host" } rule { target_label = "env" replacement = sys.env("HOST_ENV") } // Pinned to the host, not the agent container's id, so recreating the // agent doesn't start a new series set. rule { target_label = "instance" replacement = sys.env("HOST_LABEL") } } prometheus.remote_write "central" { endpoint { url = "https://push.xaritomi.xyz/api/v1/write" basic_auth { username = sys.env("PUSH_USER") password = sys.env("PUSH_PASSWORD") } queue_config { capacity = 2500 max_shards = 5 max_samples_per_send = 500 } } } prometheus.exporter.self "agent" { } prometheus.scrape "agent" { targets = prometheus.exporter.self.agent.targets forward_to = [prometheus.relabel.add_identity.receiver] scrape_interval = "30s" } EOF } main() { [ "$(id -u)" -eq 0 ] || { log "must run as root"; exit 1; } creds if [ -z "$PUSH_USER" ] || [ -z "$PUSH_PASSWORD" ]; then log "no push credential (no vault access and no /etc/metrics-push.env); skipping" exit 0 fi if ! command -v docker >/dev/null 2>&1 && [ "${METRICS_DOCKER:-}" != install ]; then host_only [ -e /etc/metrics-push.env ] && shred -u /etc/metrics-push.env 2>/dev/null || true log "running as host=$(hostname) env=${HOST_ENV:-dev} (host metrics only)" return 0 fi docker_up write_files # Docker 29's API is too new for cadvisor 0.49's docker client, on either image # store, so containers are read through containerd, in Docker's namespace. local ns=moby ( umask 077 printf 'HOST_LABEL=%s\nHOST_ENV=%s\nCADVISOR_CONTAINERD_NS=%s\nPUSH_USER=%s\nPUSH_PASSWORD=%s\n' \ "$(hostname)" "${HOST_ENV:-dev}" "$ns" "$PUSH_USER" "$PUSH_PASSWORD" > "$DIR/.env" ) ( cd "$DIR" && docker compose up -d --quiet-pull ) [ -e /etc/metrics-push.env ] && shred -u /etc/metrics-push.env 2>/dev/null || true log "running as host=$(hostname) env=${HOST_ENV:-dev}" } main "$@"