Skip to content

An open-source, faster Devin alternative

TypeScript

Ship platform logs to Axiom via Vector (#240)

Mohamed Habib737d527f1055
diff --git a/.github/workflows/build-worker-ami.yml b/.github/workflows/build-worker-ami.yml
index 53a3920e..1719509e 100644
--- a/.github/workflows/build-worker-ami.yml
+++ b/.github/workflows/build-worker-ami.yml
@@ -94,6 +94,14 @@ jobs:
deploy/ec2/build-rootfs-docker.sh \
scripts/claude-agent-wrapper/
+ - name: Package Vector configs
+ # Bundled separately so Packer's file provisioner has a known
+ # tarball path (it can't reliably upload an arbitrary directory).
+ # install.sh on the builder extracts and installs Vector + the
+ # KV-token populator into the AMI.
+ run: |
+ tar czf /tmp/packer-vector-ctx.tar.gz -C deploy vector
+
- name: Azure Login
uses: azure/login@v2
with:
diff --git a/.github/workflows/deploy-server.yml b/.github/workflows/deploy-server.yml
index 800c31f0..15c1c909 100644
--- a/.github/workflows/deploy-server.yml
+++ b/.github/workflows/deploy-server.yml
@@ -50,6 +50,13 @@ jobs:
- name: Package web assets
run: tar czf bin/web-dist.tar.gz -C web dist
+ - name: Package Vector configs
+ # Bundle deploy/vector/ for distribution to control-plane hosts.
+ # install.sh is idempotent: skips Vector install if already present,
+ # always refreshes config + restarts. Workers get the same files via
+ # the Packer image bake (build-worker-ami.yml).
+ run: tar czf bin/vector-deploy.tar.gz -C deploy vector
+
- name: Azure Login
uses: azure/login@v2
with:
@@ -75,6 +82,14 @@ jobs:
--file bin/web-dist.tar.gz \
--overwrite true -o none
+ az storage blob upload \
+ --account-name ${{ secrets.AZURE_STORAGE_ACCOUNT }} \
+ --account-key "${{ secrets.AZURE_STORAGE_KEY }}" \
+ --container-name checkpoints \
+ --name deploy/vector-deploy.tar.gz \
+ --file bin/vector-deploy.tar.gz \
+ --overwrite true -o none
+
echo "Artifacts uploaded to blob storage"
- name: Discover control planes
@@ -120,6 +135,12 @@ jobs:
--container-name checkpoints --name deploy/web-dist.tar.gz \
--file /tmp/web-dist.tar.gz --overwrite true -o none
+ az storage blob download \
+ --account-name ${{ secrets.AZURE_STORAGE_ACCOUNT }} \
+ --account-key '${{ secrets.AZURE_STORAGE_KEY }}' \
+ --container-name checkpoints --name deploy/vector-deploy.tar.gz \
+ --file /tmp/vector-deploy.tar.gz --overwrite true -o none
+
# Stop, replace binary, extract frontend
systemctl stop opensandbox-server
sleep 1
@@ -136,6 +157,17 @@ jobs:
fi
systemctl start opensandbox-server
+
+ # Install/refresh Vector + the KV token populator. install.sh
+ # is idempotent (skips Vector install if already present,
+ # always refreshes config + reloads). populate-vector-env
+ # fetches AXIOM_PLATFORM_TOKEN from KV via the VM's managed
+ # identity at every boot (and on this restart).
+ mkdir -p /tmp/vector-deploy
+ tar xzf /tmp/vector-deploy.tar.gz -C /tmp/vector-deploy
+ bash /tmp/vector-deploy/vector/install.sh control-plane
+ rm -rf /tmp/vector-deploy /tmp/vector-deploy.tar.gz
+
echo 'Deploy complete'
" -o none
diff --git a/.gitignore b/.gitignore
index 032cf9b9..0d870b97 100644
--- a/.gitignore
+++ b/.gitignore
@@ -65,4 +65,5 @@ delme
deploy/azure/.dev-env-state-*
deploy/azure/.dev-env-secrets*
!deploy/azure/.dev-env-secrets.example
+deploy/azure/.dev-vector-token-*
/server
diff --git a/cmd/server/main.go b/cmd/server/main.go
index 8eea8537..60885d67 100644
--- a/cmd/server/main.go
+++ b/cmd/server/main.go
@@ -5,6 +5,7 @@ import (
"encoding/base64"
"fmt"
"log"
+ "log/slog"
"os"
"strconv"
"strings"
@@ -22,6 +23,7 @@ import (
"github.com/opensandbox/opensandbox/internal/controlplane"
"github.com/opensandbox/opensandbox/internal/crypto"
"github.com/opensandbox/opensandbox/internal/db"
+ "github.com/opensandbox/opensandbox/internal/obslog"
"github.com/opensandbox/opensandbox/internal/observability"
"github.com/opensandbox/opensandbox/internal/proxy"
"github.com/opensandbox/opensandbox/internal/sandbox"
@@ -42,6 +44,21 @@ func main() {
log.Fatalf("failed to load config: %v", err)
}
+ // Structured logging (JSON to stdout, host envelope baked in). Installs
+ // itself as slog.Default AND redirects stdlib log.Printf through slog so
+ // existing log call sites emit JSON automatically. Vector reads stdout
+ // from the Docker logging driver and ships to Axiom.
+ cpHostname, _ := os.Hostname()
+ obslog.Init(obslog.HostFields{
+ Service: obslog.ServiceControlPlane,
+ ServiceID: cpHostname, // hostname distinguishes HA replicas
+ CellID: cfg.CellID,
+ Region: cfg.Region,
+ Hostname: cpHostname,
+ HostIP: cfg.HostIP,
+ Version: ServerVersion,
+ }, slog.LevelInfo)
+
// Sentry error reporting — no-op if OPENSANDBOX_SENTRY_DSN is unset.
flushSentry := observability.Init(cfg, "control-plane", ServerVersion)
defer flushSentry()
diff --git a/cmd/worker/main.go b/cmd/worker/main.go
index f0c06969..f1f552cf 100644
--- a/cmd/worker/main.go
+++ b/cmd/worker/main.go
@@ -5,6 +5,7 @@ import (
"fmt"
"io"
"log"
+ "log/slog"
"os"
"os/signal"
"path/filepath"
@@ -19,6 +20,7 @@ import (
"github.com/opensandbox/opensandbox/internal/db"
"github.com/opensandbox/opensandbox/internal/metrics"
"github.com/opensandbox/opensandbox/internal/observability"
+ "github.com/opensandbox/opensandbox/internal/obslog"
"github.com/opensandbox/opensandbox/internal/proxy"
qm "github.com/opensandbox/opensandbox/internal/qemu"
"github.com/opensandbox/opensandbox/internal/sandbox"
@@ -66,6 +68,21 @@ func main() {
log.Fatalf("failed to load config: %v", err)
}
+ // Structured logging (JSON to stdout/journald, host envelope baked in).
+ // Installs itself as slog.Default AND redirects stdlib log.Printf through
+ // slog so existing log call sites emit JSON automatically. Vector on the
+ // host reads journald and ships to Axiom.
+ workerHostname, _ := os.Hostname()
+ obslog.Init(obslog.HostFields{
+ Service: obslog.ServiceWorker,
+ ServiceID: cfg.WorkerID,
+ CellID: cfg.CellID,
+ Region: cfg.Region,
+ Hostname: workerHostname,
+ HostIP: cfg.HostIP,
+ Version: WorkerVersion,
+ }, slog.LevelInfo)
+
// Sentry error reporting — no-op if OPENSANDBOX_SENTRY_DSN is unset.
flushSentry := observability.Init(cfg, "worker", WorkerVersion)
defer flushSentry()
diff --git a/deploy/azure/deploy-azure-dev.sh b/deploy/azure/deploy-azure-dev.sh
index 9989369d..3931dceb 100755
--- a/deploy/azure/deploy-azure-dev.sh
+++ b/deploy/azure/deploy-azure-dev.sh
@@ -125,7 +125,9 @@ SETUP_DISK
log "Syncing codebase..."
rsync -az --progress \
--exclude '.git' --exclude 'bin/' --exclude 'node_modules/' \
- --exclude '.dev-env-state*' --exclude '*.ext4' --exclude 'vendor/' \
+ --exclude '.dev-env-state*' --exclude '.dev-env-secrets*' \
+ --exclude '.dev-vector-token-*' \
+ --exclude '*.ext4' --exclude 'vendor/' \
"$REPO_ROOT/" "${AZURE_ADMIN_USER}@${VM_PUBLIC_IP}:~/opensandbox/"
log "Running host setup..."
@@ -190,7 +192,9 @@ cmd_deploy() {
log "Syncing code..."
rsync -az --progress \
--exclude '.git' --exclude 'bin/' --exclude 'node_modules/' \
- --exclude '.dev-env-state*' --exclude '*.ext4' --exclude 'vendor/' \
+ --exclude '.dev-env-state*' --exclude '.dev-env-secrets*' \
+ --exclude '.dev-vector-token-*' \
+ --exclude '*.ext4' --exclude 'vendor/' \
"$REPO_ROOT/" "${AZURE_ADMIN_USER}@${VM_PUBLIC_IP}:~/opensandbox/"
# Build binaries on instance
diff --git a/deploy/packer/worker-ami.pkr.hcl b/deploy/packer/worker-ami.pkr.hcl
index 52126a4e..b1782404 100644
--- a/deploy/packer/worker-ami.pkr.hcl
+++ b/deploy/packer/worker-ami.pkr.hcl
@@ -320,6 +320,36 @@ build {
]
}
+ # 4.5. Install Vector + the KV-token-populator for platform-logs shipping.
+ #
+ # Vector is enabled but NOT started (Packer captures the image before
+ # systemd has run). At first boot:
+ # 1. cloud-init writes /etc/opensandbox/worker.env
+ # 2. populate-vector-env.service fires (Before=vector.service), reads
+ # SECRETS_VAULT_NAME from worker.env, fetches AXIOM_PLATFORM_TOKEN
+ # from KV via the VM's managed identity, writes /etc/opensandbox/vector.env
+ # 3. vector.service starts, reads both env files, ships to oc-platform-logs
+ #
+ # PACKER_BUILD=1 tells install.sh to skip `systemctl start` — systemd in a
+ # baking image is offline.
+ #
+ # CI is expected to pre-tar deploy/vector/ at /tmp/packer-vector-ctx.tar.gz
+ # (see .github/workflows/build-worker-ami.yml).
+ provisioner "file" {
+ source = "/tmp/packer-vector-ctx.tar.gz"
+ destination = "/tmp/vector-ctx.tar.gz"
+ }
+ provisioner "shell" {
+ execute_command = "chmod +x {{ .Path }}; {{ .Vars }} sudo -E bash '{{ .Path }}'"
+ environment_vars = ["PACKER_BUILD=1"]
+ inline = [
+ "mkdir -p /tmp/vector-ctx",
+ "tar xzf /tmp/vector-ctx.tar.gz -C /tmp/vector-ctx",
+ "cd /tmp/vector-ctx/vector && PACKER_BUILD=1 bash install.sh worker",
+ "rm -rf /tmp/vector-ctx /tmp/vector-ctx.tar.gz",
+ ]
+ }
+
# 4b. Archive base image to blob storage keyed by goldenVersion so that old
# checkpoints referencing this base can be rebased even after workers roll.
provisioner "shell" {
diff --git a/deploy/vector/control-plane.yaml b/deploy/vector/control-plane.yaml
new file mode 100644
index 00000000..896d4f91
--- /dev/null
+++ b/deploy/vector/control-plane.yaml
@@ -0,0 +1,52 @@
+# Vector config for the control-plane host (Azure prod: systemd binary,
+# not Docker). Reads opensandbox-server.service from journald, parses JSON
+# log lines (emitted by internal/obslog), enriches non-JSON lines with the
+# host envelope from env, and ships to oc-platform-logs.
+#
+# Install path: /etc/vector/vector.yaml
+# Env file: /etc/opensandbox/vector.env (populated by
+# populate-vector-env.service from Key Vault at boot)
+
+data_dir: /var/lib/vector
+
+sources:
+ control_plane_journald:
+ type: journald
+ include_units:
+ - opensandbox-server.service
+ # Default current_boot_only=true is fine — Vector tracks its own cursor
+ # in data_dir, so restarts resume cleanly without replaying the journal.
+
+transforms:
+ control_plane_parse:
+ type: remap
+ inputs:
+ - control_plane_journald
+ source: |
+ parsed, err = parse_json(.message)
+ if err == null && is_object(parsed) {
+ . = merge(., object!(parsed))
+ # Drop stringified duplicate; non-JSON lines (panics, systemd boot)
+ # keep .message as the readable content.
+ del(.message)
+ }
+ if !exists(.service) { .service = "control-plane" }
+ if !exists(.service_id) { .service_id, _ = get_hostname() }
+ if !exists(.cell_id) { .cell_id = "${OPENCOMPUTER_CELL_ID:-unknown}" }
+ if !exists(.region) { .region = "${OPENSANDBOX_REGION:-unknown}" }
+ if !exists(.host_ip) { .host_ip = "${OPENCOMPUTER_HOST_IP:-unknown}" }
+ if !exists(.hostname) { .hostname, _ = get_hostname() }
+
+sinks:
+ axiom_platform:
+ type: axiom
+ inputs:
+ - control_plane_parse
+ dataset: "${AXIOM_PLATFORM_DATASET}"
+ token: "${AXIOM_PLATFORM_TOKEN}"
+ buffer:
+ type: disk
+ max_size: 268435488
+ when_full: drop_newest
+ healthcheck:
+ enabled: true
diff --git a/deploy/vector/dev-host.yaml b/deploy/vector/dev-host.yaml
new file mode 100644
index 00000000..38d2081a
--- /dev/null
+++ b/deploy/vector/dev-host.yaml
@@ -0,0 +1,87 @@
+# Vector config for a dev host that runs BOTH opensandbox-server AND
+# opensandbox-worker as systemd services on the same VM (the layout produced
+# by deploy/azure/deploy-azure-dev.sh).
+#
+# Production hosts use worker.yaml or control-plane.yaml — one role per host.
+# This config exists so the request-id join can be validated end-to-end on a
+# single dev VM before standing up a multi-VM dev cluster.
+#
+# The journald source captures both units in one stream; the parse transform
+# tags `service` based on which unit emitted each line.
+#
+# Install path: /etc/vector/vector.yaml
+# Env file: /etc/opensandbox/vector.env (provides AXIOM_PLATFORM_TOKEN)
+
+data_dir: /var/lib/vector
+
+sources:
+ dev_journald:
+ type: journald
+ include_units:
+ - opensandbox-server.service
+ - opensandbox-worker.service
+ # `current_boot_only: false` is rejected on systemd 250-257 (Vector
+ # limitation). Default (true) is fine — Vector tracks its own cursor in
+ # data_dir, so restarts pick up where they left off rather than replaying.
+
+transforms:
+ dev_parse:
+ type: remap
+ inputs:
+ - dev_journald
+ source: |
+ parsed, err = parse_json(.message)
+ if err == null && is_object(parsed) {
+ . = merge(., object!(parsed))
+ # The structured fields (msg, level, request_id, ...) are now at
+ # root. Drop the stringified copy so events don't duplicate the
+ # payload in Axiom. Non-JSON lines (panics, kernel) fall through
+ # this branch and keep .message as the readable content.
+ del(.message)
+ }
+ # Tag service based on the systemd unit. obslog.Init already sets
+ # `service` inside JSON log lines, so this only fires for non-JSON
+ # output (panics, plain stderr, systemd boot messages).
+ if !exists(.service) {
+ unit = string(.SYSTEMD_UNIT) ?? ""
+ if unit == "opensandbox-server.service" {
+ .service = "control-plane"
+ } else if unit == "opensandbox-worker.service" {
+ .service = "worker"
+ } else {
+ .service = "unknown"
+ }
+ }
+ if !exists(.service_id) {
+ # Worker exports OPENSANDBOX_WORKER_ID; control plane has no
+ # equivalent on a binary-deployed dev host — fall back to hostname.
+ unit = string(.SYSTEMD_UNIT) ?? ""
+ if unit == "opensandbox-worker.service" {
+ .service_id = "${OPENSANDBOX_WORKER_ID:-unknown}"
+ } else {
+ .service_id, _ = get_hostname()
+ }
+ }
+ if !exists(.cell_id) { .cell_id = "${OPENCOMPUTER_CELL_ID:-unknown}" }
+ if !exists(.region) { .region = "${OPENSANDBOX_REGION:-unknown}" }
+ if !exists(.host_ip) { .host_ip = "${OPENCOMPUTER_HOST_IP:-unknown}" }
+ if !exists(.hostname) { .hostname, _ = get_hostname() }
+ # Stamp every event with environment so dev traffic is filterable inside
+ # a shared dataset. Only the dev-host config sets this — production
+ # worker.yaml / control-plane.yaml deliberately omit it so prod events
+ # don't claim the dev tag.
+ .environment = "dev"
+
+sinks:
+ axiom_platform:
+ type: axiom
+ inputs:
+ - dev_parse
+ dataset: "${AXIOM_PLATFORM_DATASET}"
+ token: "${AXIOM_PLATFORM_TOKEN}"
+ buffer:
+ type: disk
+ max_size: 268435488
+ when_full: drop_newest
+ healthcheck:
+ enabled: true
diff --git a/deploy/vector/install.sh b/deploy/vector/install.sh
new file mode 100755
index 00000000..d290eb19
--- /dev/null
+++ b/deploy/vector/install.sh
@@ -0,0 +1,118 @@
+#!/usr/bin/env bash
+# install.sh — Install Vector on a host and wire it to a role-specific config.
+#
+# Usage (run as root on the target host):
+# ./install.sh worker # for prod worker VMs (reads journald)
+# ./install.sh control-plane # for prod control plane VM (reads journald)
+# ./install.sh dev-host # single VM running both server + worker as systemd
+#
+# Two ways the env file (with the Axiom token) reaches the host:
+#
+# 1. Production (Azure VMs with managed identity to KV): populate-vector-env.service
+# is installed alongside vector.service. At each boot it fetches the
+# `shared-axiom-platform-ingest-token` secret from $SECRETS_VAULT_NAME and
+# writes /etc/opensandbox/vector.env. Vector starts after. No human in the
+# loop, no static token on disk.
+#
+# 2. Operator-managed (dev hosts, ad-hoc): the operator writes
+# /etc/opensandbox/vector.env manually before running this script (or any
+# other way). The KV oneshot finds no SECRETS_VAULT_NAME and exits clean,
+# and Vector reads whatever the operator put there.
+set -euo pipefail
+
+ROLE="${1:-}"
+case "$ROLE" in
+ worker|control-plane|dev-host) ;;
+ *)
+ echo "usage: $0 worker|control-plane|dev-host" >&2
+ exit 2
+ ;;
+esac
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+CONFIG_SRC="$SCRIPT_DIR/${ROLE}.yaml"
+if [ ! -f "$CONFIG_SRC" ]; then
+ echo "config not found: $CONFIG_SRC" >&2
+ exit 1
+fi
+
+echo "=== Installing Vector (role: $ROLE) ==="
+
+# --- Install Vector via official setup script ---
+# setup.vector.dev configures the right apt repo + key for the host's distro.
+# (Vector moved off repositories.timber.io after the Datadog acquisition; the
+# old URL no longer resolves.)
+if ! command -v vector &>/dev/null; then
+ echo "Installing Vector..."
+ bash -c "$(curl -fsSL https://setup.vector.dev)"
+ apt-get install -y -qq vector
+fi
+vector --version
+
+# --- Drop the role config ---
+mkdir -p /etc/vector /var/lib/vector
+install -m 0644 "$CONFIG_SRC" /etc/vector/vector.yaml
+chown -R vector:vector /var/lib/vector
+
+# --- Install the KV → env-file populator (oneshot, runs Before=vector.service) ---
+# Both the script and the unit file are tracked in this dir so they roll
+# atomically with config changes.
+install -m 0755 "$SCRIPT_DIR/populate-vector-env.sh" /usr/local/bin/populate-vector-env.sh
+install -m 0644 "$SCRIPT_DIR/populate-vector-env.service" \
+ /etc/systemd/system/populate-vector-env.service
+
+# --- Wire env file + KV oneshot into the vector.service unit ---
+# Use a drop-in instead of editing the package file so a Vector upgrade
+# doesn't clobber our changes.
+mkdir -p /etc/systemd/system/vector.service.d
+cat > /etc/systemd/system/vector.service.d/override.conf <<'EOF'
+[Unit]
+# Soft dependency: if the KV fetch fails, vector still starts so we
+# preserve whatever state was on disk from a previous boot.
+Wants=populate-vector-env.service
+After=populate-vector-env.service
+
+[Service]
+EnvironmentFile=-/etc/opensandbox/worker.env
+EnvironmentFile=-/etc/opensandbox/server.env
+EnvironmentFile=-/etc/opensandbox/vector.env
+# Vector needs to read journald — add the user to the right group.
+SupplementaryGroups=systemd-journal
+EOF
+
+# --- Auto-detect HOST_IP if not provisioned ---
+# Vector enriches log lines with OPENCOMPUTER_HOST_IP from the env file. If the
+# operator didn't set it (and the KV oneshot hasn't run yet), fill it in from
+# the primary interface so the field isn't "unknown" in Axiom.
+if [ -f /etc/opensandbox/vector.env ] && \
+ ! grep -q '^OPENCOMPUTER_HOST_IP=' /etc/opensandbox/vector.env 2>/dev/null; then
+ # `ip route get` returns the kernel's chosen source IP for outbound — bypasses
+ # Azure's 169.254.169.253 IMDS address which is also scope=global on lo.
+ HOST_IP=$(ip route get 8.8.8.8 2>/dev/null | \
+ awk '/src/ {for(i=1;i<NF;i++) if($i=="src") print $(i+1); exit}')
+ if [ -n "$HOST_IP" ]; then
+ echo "OPENCOMPUTER_HOST_IP=$HOST_IP" >> /etc/opensandbox/vector.env
+ echo "Detected HOST_IP=$HOST_IP"
+ fi
+fi
+
+# --- Start ---
+systemctl daemon-reload
+systemctl enable populate-vector-env.service vector.service
+
+# In a Packer image bake, systemd may not actually run units (the image is
+# captured before reboot). Skip the start in that case so packer's
+# deprovision step doesn't trip over a started service. PACKER_BUILD is set
+# by the Packer provisioner.
+if [ -z "${PACKER_BUILD:-}" ]; then
+ systemctl restart populate-vector-env.service 2>&1 || true
+ systemctl restart vector
+ sleep 2
+ systemctl status vector --no-pager -l | head -15
+fi
+
+echo
+echo "=== Done ==="
+echo "Check vector status: systemctl status vector"
+echo "Tail vector logs: journalctl -u vector -f"
+echo "Confirm Axiom ingest: look for events in dataset \${AXIOM_PLATFORM_DATASET}"
diff --git a/deploy/vector/populate-vector-env.service b/deploy/vector/populate-vector-env.service
new file mode 100644
index 00000000..b897f55d
--- /dev/null
+++ b/deploy/vector/populate-vector-env.service
@@ -0,0 +1,31 @@
+# Pulls AXIOM_PLATFORM_TOKEN from Key Vault via the VM's managed identity
+# and writes /etc/opensandbox/vector.env before vector.service starts.
+#
+# Reads SECRETS_VAULT_NAME (and OPENCOMPUTER_CELL_ID/REGION for tagging)
+# from whichever role-env file exists — worker.env on workers, server.env
+# on the control plane. EnvironmentFile lines with a leading `-` are
+# silently skipped if the file is absent, so this unit works on both roles.
+
+[Unit]
+Description=Populate /etc/opensandbox/vector.env from Key Vault
+After=network-online.target
+Wants=network-online.target
+Before=vector.service
+DefaultDependencies=no
+
+[Service]
+Type=oneshot
+EnvironmentFile=-/etc/opensandbox/worker.env
+EnvironmentFile=-/etc/opensandbox/server.env
+ExecStart=/usr/local/bin/populate-vector-env.sh
+RemainAfterExit=yes
+# Retry a few times if KV is briefly unreachable at boot.
+Restart=on-failure
+RestartSec=10s
+# Cap retries — after this the unit fails; vector still starts (Wants=
+# from vector's drop-in, not Requires=).
+StartLimitBurst=5
+StartLimitIntervalSec=120
+
+[Install]
+WantedBy=multi-user.target
diff --git a/deploy/vector/populate-vector-env.sh b/deploy/vector/populate-vector-env.sh
new file mode 100755
index 00000000..dc033338
--- /dev/null
+++ b/deploy/vector/populate-vector-env.sh
@@ -0,0 +1,87 @@
+#!/bin/bash
+# populate-vector-env.sh — Fetch the Axiom platform-logs ingest credentials
+# (token + dataset name) from Azure Key Vault via the VM's managed identity,
+# write them to /etc/opensandbox/vector.env so Vector picks them up at start.
+#
+# Runs as a one-shot systemd unit (populate-vector-env.service) before
+# vector.service. Idempotent on every boot.
+#
+# Required env (sourced from /etc/opensandbox/worker.env or server.env by
+# the systemd unit's EnvironmentFile=):
+# SECRETS_VAULT_NAME Key Vault name (e.g. opencomputer-prod-kv)
+#
+# Optional env (used to enrich Vector's host envelope for non-JSON lines):
+# OPENCOMPUTER_CELL_ID e.g. eastus2-default
+# OPENSANDBOX_REGION e.g. eastus2
+#
+# KV secrets fetched:
+# shared-axiom-platform-ingest-token → AXIOM_PLATFORM_TOKEN (required)
+# shared-axiom-platform-dataset → AXIOM_PLATFORM_DATASET (required)
+#
+# Both stored under `shared-` so the same secret can be read by both
+# worker and server hosts. If either is absent, the script exits 0 — Vector
+# fails its healthcheck and events buffer to disk until the secret appears
+# (don't break the worker boot path over a missing logging credential).
+set -euo pipefail
+
+VAULT_NAME="${SECRETS_VAULT_NAME:-}"
+ENV_FILE=/etc/opensandbox/vector.env
+TOKEN_SECRET=shared-axiom-platform-ingest-token
+DATASET_SECRET=shared-axiom-platform-dataset
+
+log() { logger -t populate-vector-env "$*"; echo "$*"; }
+
+if [ -z "$VAULT_NAME" ]; then
+ log "SECRETS_VAULT_NAME not set — skipping (Vector will start without a token)"
+ exit 0
+fi
+
+# IMDS → AAD token for Key Vault
+IMDS_RESP=$(curl -sf -H 'Metadata: true' \
+ "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fvault.azure.net" \
+ || true)
+AAD_TOKEN=$(echo "$IMDS_RESP" | python3 -c 'import sys,json; print(json.load(sys.stdin).get("access_token",""))' 2>/dev/null)
+if [ -z "$AAD_TOKEN" ]; then
+ log "failed to acquire IMDS token (managed identity not attached?); skipping"
+ exit 0
+fi
+
+# Helper: fetch one secret value or empty string.
+kv_get() {
+ local name=$1
+ local resp
+ resp=$(curl -sf -H "Authorization: Bearer $AAD_TOKEN" \
+ "https://${VAULT_NAME}.vault.azure.net/secrets/${name}?api-version=7.4" \
+ || true)
+ echo "$resp" | python3 -c 'import sys,json; print(json.load(sys.stdin).get("value",""))' 2>/dev/null
+}
+
+TOKEN_VALUE=$(kv_get "$TOKEN_SECRET")
+if [ -z "$TOKEN_VALUE" ]; then
+ log "secret $TOKEN_SECRET not found in $VAULT_NAME (or no access); skipping"
+ exit 0
+fi
+
+DATASET_VALUE=$(kv_get "$DATASET_SECRET")
+if [ -z "$DATASET_VALUE" ]; then
+ log "secret $DATASET_SECRET not found in $VAULT_NAME (or no access); skipping — Vector won't have a dataset to ship to"
+ exit 0
+fi
+
+# Auto-detect HOST_IP via the kernel's source-address selection (skips link-local).
+HOST_IP=$(ip route get 8.8.8.8 2>/dev/null | awk '/src/ {for(i=1;i<NF;i++) if($i=="src") print $(i+1); exit}' || true)
+
+install -d -m 0755 /etc/opensandbox
+umask 077
+cat > "${ENV_FILE}.tmp" <<EOF
+AXIOM_PLATFORM_TOKEN=${TOKEN_VALUE}
+AXIOM_PLATFORM_DATASET=${DATASET_VALUE}
+OPENCOMPUTER_CELL_ID=${OPENCOMPUTER_CELL_ID:-unknown}
+OPENSANDBOX_REGION=${OPENSANDBOX_REGION:-unknown}
+OPENCOMPUTER_HOST_IP=${HOST_IP:-unknown}
+EOF
+chown root:root "${ENV_FILE}.tmp"
+chmod 0600 "${ENV_FILE}.tmp"
+mv -f "${ENV_FILE}.tmp" "$ENV_FILE"
+
+log "populated $ENV_FILE (token+dataset from $VAULT_NAME, host_ip=${HOST_IP:-unknown})"
diff --git a/deploy/vector/vector.env.example b/deploy/vector/vector.env.example
new file mode 100644
index 00000000..f035c8d5
--- /dev/null
+++ b/deploy/vector/vector.env.example
@@ -0,0 +1,31 @@
+# /etc/opensandbox/vector.env
+#
+# Vector reads this at startup (via systemd EnvironmentFile= drop-in). Only
+# these variables are needed — everything else is in worker.env / set on the
+# host by cloud-init.
+#
+# Production hosts: this file is written by populate-vector-env.service at
+# every boot, fetching `shared-axiom-platform-ingest-token` and
+# `shared-axiom-platform-dataset` from Azure Key Vault via the VM's managed
+# identity. Operators do not need to maintain this file manually.
+#
+# Dev/operator-managed hosts: write this file by hand before running
+# install.sh (populate-vector-env will exit 0 if SECRETS_VAULT_NAME isn't
+# set, leaving the operator's file in place).
+
+# Axiom platform-logs ingest token. Create in Axiom: Settings → API tokens,
+# capability Ingest only, scoped to your platform dataset only. Do not reuse
+# the customer-sandbox-logs token — different blast radius.
+AXIOM_PLATFORM_TOKEN=xaat-...
+
+# Axiom dataset name. Required, no default — explicit per environment so a
+# misconfigured prod host doesn't silently ship into the wrong stream.
+AXIOM_PLATFORM_DATASET=oc-platform-logs
+
+# Optional: cell ID for the host envelope. Set to "<region>-<pool>" (e.g.
+# eastus2-default). The control plane / worker daemons get this from their
+# own worker.env / server.env; this is only needed if you have non-slog log
+# lines (kernel, systemd, panic stack traces) and want them tagged with cell.
+# OPENCOMPUTER_CELL_ID=eastus2-default
+
+# OPENCOMPUTER_HOST_IP is auto-detected by install.sh if absent.
diff --git a/deploy/vector/worker.yaml b/deploy/vector/worker.yaml
new file mode 100644
index 00000000..a066d242
--- /dev/null
+++ b/deploy/vector/worker.yaml
@@ -0,0 +1,71 @@
+# Vector config for worker hosts (Azure VMs and EC2).
+#
+# Reads journald entries from the opensandbox-worker systemd unit, parses JSON
+# log lines (emitted by internal/obslog), enriches with host envelope fields
+# from /etc/opensandbox/worker.env, and ships to the oc-platform-logs Axiom
+# dataset.
+#
+# Install path: /etc/vector/vector.yaml
+# Env file: /etc/opensandbox/vector.env (provides AXIOM_PLATFORM_TOKEN)
+#
+# Field shape after this pipeline:
+# service "worker"
+# service_id worker_id (e.g. w-oc-eastus2-1)
+# cell_id <region>-<pool>
+# region e.g. eastus2
+# hostname VM hostname
+# host_ip primary IPv4
+# request_id set per request by control plane, forwarded to worker
+# sandbox_id set per request when in scope
+# msg, level, ts present from slog
+
+data_dir: /var/lib/vector
+
+sources:
+ worker_journald:
+ type: journald
+ include_units:
+ - opensandbox-worker.service
+ # Default current_boot_only=true. (Explicit `false` is rejected on
+ # systemd 250-257 — Vector limitation.) Vector tracks its own cursor in
+ # data_dir, so restarts pick up where they left off rather than replaying.
+
+transforms:
+ worker_parse:
+ type: remap
+ inputs:
+ - worker_journald
+ # VRL: parse_json fails for non-JSON lines (e.g. systemd boot messages,
+ # panic stack traces from Go's runtime). For those we keep the original
+ # message and just stamp the host envelope so they're still queryable.
+ source: |
+ parsed, err = parse_json(.message)
+ if err == null && is_object(parsed) {
+ . = merge(., object!(parsed))
+ # See dev-host.yaml — drop stringified duplicate; non-JSON lines
+ # keep .message as the readable content.
+ del(.message)
+ }
+ if !exists(.service) { .service = "worker" }
+ if !exists(.service_id) { .service_id = "${OPENSANDBOX_WORKER_ID:-unknown}" }
+ if !exists(.cell_id) { .cell_id = "${OPENCOMPUTER_CELL_ID:-unknown}" }
+ if !exists(.region) { .region = "${OPENSANDBOX_REGION:-unknown}" }
+ if !exists(.host_ip) { .host_ip = "${OPENCOMPUTER_HOST_IP:-unknown}" }
+ if !exists(.hostname) { .hostname, _ = get_hostname() }
+
+sinks:
+ axiom_platform:
+ type: axiom
+ inputs:
+ - worker_parse
+ dataset: "${AXIOM_PLATFORM_DATASET}"
+ token: "${AXIOM_PLATFORM_TOKEN}"
+ # Disk buffer so a network blip or Axiom outage doesn't lose worker logs.
+ # 256 MiB is enough for a few hours at typical worker rates; drop_newest
+ # keeps the most-recent context if the buffer fills (better than blocking).
+ buffer:
+ type: disk
+ max_size: 268435488
+ when_full: drop_newest
+ healthcheck:
+ enabled: true
diff --git a/internal/api/router.go b/internal/api/router.go
index 78fb59bd..fcc2b6b7 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -22,6 +22,7 @@ import (
"github.com/opensandbox/opensandbox/internal/controlplane"
"github.com/opensandbox/opensandbox/internal/db"
"github.com/opensandbox/opensandbox/internal/observability"
+ "github.com/opensandbox/opensandbox/internal/obslog"
"github.com/opensandbox/opensandbox/internal/proxy"
"github.com/opensandbox/opensandbox/internal/sandbox"
"github.com/opensandbox/opensandbox/internal/storage"
@@ -152,11 +153,15 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
// Global middleware. Sentry goes first so it can attach request context and
// observe panics before echo's Recover middleware converts them to 500s.
+ // RequestID() runs before obslog.EchoMiddleware so the X-Request-Id header
+ // is on the response by the time obslog reads it. obslog replaces Echo's
+ // built-in Logger() — same access log line, but JSON with the host
+ // envelope and request_id/sandbox_id pulled from context.
e.Use(observability.EchoMiddleware())
e.Use(middleware.Recover())
- e.Use(middleware.Logger())
- e.Use(middleware.CORS())
e.Use(middleware.RequestID())
+ e.Use(obslog.EchoMiddleware())
+ e.Use(middleware.CORS())
// Subdomain proxy middleware (before auth — subdomain traffic is public)
if opts != nil && opts.SandboxProxy != nil {
diff --git a/internal/config/config.go b/internal/config/config.go
index 9b691401..0487f790 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -37,6 +37,18 @@ type Config struct {
WorkerID string // Unique worker ID (e.g., "w-iad-1")
HTTPAddr string // Public HTTP address for direct SDK access
+ // Platform observability identity (used by internal/obslog for log
+ // envelope so all logs in Axiom can be sliced by cell, host, and service
+ // ID). CellID is "<region>-<pool>"; default to "<region>-default" when
+ // unset. HostIP is auto-detected from the first non-loopback IPv4 at
+ // startup if OPENCOMPUTER_HOST_IP is not provisioned via cloud-init.
+ //
+ // These use the OPENCOMPUTER_* prefix (vs the rest of the file's
+ // OPENSANDBOX_*) intentionally — they're new fields scoped to the
+ // product-named observability envelope.
+ CellID string
+ HostIP string
+
// WorkOS
WorkOSAPIKey string
WorkOSClientID string
@@ -177,6 +189,9 @@ func Load() (*Config, error) {
WorkerID: envOrDefault("OPENSANDBOX_WORKER_ID", "w-local-1"),
HTTPAddr: envOrDefault("OPENSANDBOX_HTTP_ADDR", "http://localhost:8080"),
+ CellID: os.Getenv("OPENCOMPUTER_CELL_ID"),
+ HostIP: os.Getenv("OPENCOMPUTER_HOST_IP"),
+
WorkOSAPIKey: os.Getenv("WORKOS_API_KEY"),
WorkOSClientID: os.Getenv("WORKOS_CLIENT_ID"),
WorkOSRedirectURI: envOrDefault("WORKOS_REDIRECT_URI", "http://localhost:8080/auth/callback"),
@@ -263,6 +278,13 @@ func Load() (*Config, error) {
cfg.S3Region = cfg.Region
}
+ // Default cell ID to "<region>-default" so logs always have a cell tag.
+ // Fleet can split a region into multiple cells later by setting the env
+ // var explicitly at provisioning time.
+ if cfg.CellID == "" {
+ cfg.CellID = cfg.Region + "-default"
+ }
+
if portStr := os.Getenv("OPENSANDBOX_PORT"); portStr != "" {
port, err := strconv.Atoi(portStr)
if err != nil {
diff --git a/internal/config/keyvault.go b/internal/config/keyvault.go
index 9438f050..b0ede32b 100644
--- a/internal/config/keyvault.go
+++ b/internal/config/keyvault.go
@@ -73,6 +73,18 @@ var secretMapping = map[string]string{
"shared-axiom-ingest-token": "AXIOM_INGEST_TOKEN",
"shared-axiom-query-token": "AXIOM_QUERY_TOKEN",
"shared-axiom-dataset": "AXIOM_DATASET",
+ // Platform-logs (this PR): Vector reads these from
+ // /etc/opensandbox/vector.env, populated by populate-vector-env.service
+ // via its own IMDS+KV REST call (not by this Go-side loader, because
+ // Vector starts as its own systemd unit before the Go binary). The
+ // entries here exist for two reasons:
+ // 1. Discoverability — secretMapping is the single source of truth
+ // for "what shared-* secrets does this deployment need in KV".
+ // 2. Side-effect: the Go binary ALSO loads them into its own env at
+ // startup; future Go code that wants to surface platform-stream
+ // config (e.g. an admin endpoint) gets them for free.
+ "shared-axiom-platform-ingest-token": "AXIOM_PLATFORM_TOKEN",
+ "shared-axiom-platform-dataset": "AXIOM_PLATFORM_DATASET",
}
// LoadSecretsFromKeyVault fetches secrets from Azure Key Vault and sets them
diff --git a/internal/controlplane/server.go b/internal/controlplane/server.go
index 5147dce4..a9743601 100644
--- a/internal/controlplane/server.go
+++ b/internal/controlplane/server.go
@@ -16,6 +16,7 @@ import (
"github.com/opensandbox/opensandbox/internal/auth"
"github.com/opensandbox/opensandbox/internal/db"
"github.com/opensandbox/opensandbox/internal/grpctls"
+ "github.com/opensandbox/opensandbox/internal/obslog"
pb "github.com/opensandbox/opensandbox/proto/worker"
)
@@ -40,11 +41,13 @@ func NewServer(store *db.Store, jwtIssuer *auth.JWTIssuer, registry *WorkerRegis
registry: registry,
}
- // Global middleware
+ // Global middleware. RequestID() comes first so the X-Request-Id header
+ // is present when obslog.EchoMiddleware tags the request context — that
+ // way every log line emitted inside the handler carries the same id.
e.Use(middleware.Recover())
- e.Use(middleware.Logger())
- e.Use(middleware.CORS())
e.Use(middleware.RequestID())
+ e.Use(obslog.EchoMiddleware())
+ e.Use(middleware.CORS())
// Health check
e.GET("/health", func(c echo.Context) error {
diff --git a/internal/obslog/echo.go b/internal/obslog/echo.go
new file mode 100644
index 00000000..df53c36e
--- /dev/null
+++ b/internal/obslog/echo.go
@@ -0,0 +1,78 @@
+package obslog
+
+import (
+ "log/slog"
+ "time"
+
+ "github.com/labstack/echo/v4"
+)
+
+// EchoMiddleware stashes the X-Request-Id header and the :id URL param
+// (sandbox_id) into the request context so downstream handler logs are
+// automatically tagged. On request completion it emits a single structured
+// access-log line.
+//
+// Place this AFTER middleware.RequestID() — that middleware generates the
+// X-Request-Id if absent. Replaces middleware.Logger().
+func EchoMiddleware() echo.MiddlewareFunc {
+ return func(next echo.HandlerFunc) echo.HandlerFunc {
+ return func(c echo.Context) error {
+ start := time.Now()
+ req := c.Request()
+
+ // middleware.RequestID() (which runs before us) sets the id on
+ // the RESPONSE header — that's the authoritative location whether
+ // the id was forwarded inbound or generated here. Falling back to
+ // the request header is defensive: a future caller might want
+ // only the request header set.
+ rid := c.Response().Header().Get(echo.HeaderXRequestID)
+ if rid == "" {
+ rid = req.Header.Get(echo.HeaderXRequestID)
+ }
+ rf := RequestFields{
+ RequestID: rid,
+ SandboxID: c.Param("id"),
+ }
+ ctx := WithRequest(req.Context(), rf)
+ c.SetRequest(req.WithContext(ctx))
+
+ err := next(c)
+
+ res := c.Response()
+ attrs := []any{
+ slog.String("event", "http_request"),
+ slog.String("method", req.Method),
+ slog.String("path", c.Path()),
+ slog.String("uri", req.RequestURI),
+ slog.Int("status", res.Status),
+ slog.Int64("duration_ms", time.Since(start).Milliseconds()),
+ slog.String("remote_ip", c.RealIP()),
+ slog.Int64("bytes_in", req.ContentLength),
+ slog.Int64("bytes_out", res.Size),
+ }
+ if err != nil {
+ attrs = append(attrs, slog.String("err", err.Error()))
+ }
+
+ level := slog.LevelInfo
+ switch {
+ case res.Status >= 500:
+ level = slog.LevelError
+ case res.Status >= 400:
+ level = slog.LevelWarn
+ }
+ slog.LogAttrs(ctx, level, "http_request", toSlogAttrs(attrs)...)
+ return err
+ }
+ }
+}
+
+func toSlogAttrs(in []any) []slog.Attr {
+ out := make([]slog.Attr, 0, len(in))
+ for _, a := range in {
+ if attr, ok := a.(slog.Attr); ok {
+ out = append(out, attr)
+ }
+ }
+ return out
+}
diff --git a/internal/obslog/echo_test.go b/internal/obslog/echo_test.go
new file mode 100644
index 00000000..e408043b
--- /dev/null
+++ b/internal/obslog/echo_test.go
@@ -0,0 +1,134 @@
+package obslog
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/labstack/echo/v4"
+ "github.com/labstack/echo/v4/middleware"
+)
+
+// TestEchoMiddlewareForwardsRequestIDIntoHandlerContext exercises the real
+// middleware chain a server uses: middleware.RequestID generates the header
+// (or reuses an inbound one), obslog.EchoMiddleware pulls it into context,
+// and a handler emits a log line via slog.InfoContext that carries the same
+// id. This is the contract that makes the cross-service join in Axiom work.
+func TestEchoMiddlewareForwardsRequestIDIntoHandlerContext(t *testing.T) {
+ var buf bytes.Buffer
+ // Capture slog output to buf. slog.Default is process-wide so other tests
+ // running in parallel would see this; run sequentially.
+ prevDefault := slog.Default()
+ t.Cleanup(func() { slog.SetDefault(prevDefault) })
+
+ handler := &ctxHandler{
+ inner: slog.NewJSONHandler(&buf, &slog.HandlerOptions{Level: slog.LevelDebug}),
+ }
+ slog.SetDefault(slog.New(handler))
+
+ e := echo.New()
+ e.Use(middleware.RequestID())
+ e.Use(EchoMiddleware())
+ e.GET("/sandboxes/:id/files", func(c echo.Context) error {
+ slog.InfoContext(c.Request().Context(), "handler_invoked")
+ return c.String(http.StatusOK, "ok")
+ })
+
+ req := httptest.NewRequest(http.MethodGet, "/sandboxes/sb-test-1/files", nil)
+ req.Header.Set(echo.HeaderXRequestID, "req-from-control-plane")
+ rec := httptest.NewRecorder()
+ e.ServeHTTP(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200", rec.Code)
+ }
+
+ // Parse every JSON line; we expect at least one with msg=handler_invoked
+ // and one with msg=http_request, both carrying the same request_id +
+ // sandbox_id.
+ var handlerLine, accessLine map[string]any
+ for _, line := range strings.Split(strings.TrimSpace(buf.String()), "\n") {
+ var m map[string]any
+ if err := json.Unmarshal([]byte(line), &m); err != nil {
+ t.Fatalf("non-JSON log line: %q (err=%v)", line, err)
+ }
+ switch m["msg"] {
+ case "handler_invoked":
+ handlerLine = m
+ case "http_request":
+ accessLine = m
+ }
+ }
+
+ if handlerLine == nil {
+ t.Fatalf("no handler log line found in:\n%s", buf.String())
+ }
+ if accessLine == nil {
+ t.Fatalf("no http_request access log line found in:\n%s", buf.String())
+ }
+
+ for _, ll := range []map[string]any{handlerLine, accessLine} {
+ if ll["request_id"] != "req-from-control-plane" {
+ t.Errorf("request_id = %v, want req-from-control-plane (msg=%v)", ll["request_id"], ll["msg"])
+ }
+ if ll["sandbox_id"] != "sb-test-1" {
+ t.Errorf("sandbox_id = %v, want sb-test-1 (msg=%v)", ll["sandbox_id"], ll["msg"])
+ }
+ }
+
+ if accessLine["status"] != float64(200) {
+ t.Errorf("access log status = %v, want 200", accessLine["status"])
+ }
+ if accessLine["method"] != "GET" {
+ t.Errorf("access log method = %v, want GET", accessLine["method"])
+ }
+}
+
+// TestEchoMiddlewareGeneratesRequestIDIfMissing verifies that Echo's
+// middleware.RequestID generates an id when no inbound header is present,
+// and that obslog still picks it up. This is the case when a client hits
+// the control plane directly.
+func TestEchoMiddlewareGeneratesRequestIDIfMissing(t *testing.T) {
+ var buf bytes.Buffer
+ prevDefault := slog.Default()
+ t.Cleanup(func() { slog.SetDefault(prevDefault) })
+
+ handler := &ctxHandler{
+ inner: slog.NewJSONHandler(&buf, &slog.HandlerOptions{Level: slog.LevelDebug}),
+ }
+ slog.SetDefault(slog.New(handler))
+
+ e := echo.New()
+ e.Use(middleware.RequestID())
+ e.Use(EchoMiddleware())
+ e.GET("/health", func(c echo.Context) error {
+ return c.String(http.StatusOK, "ok")
+ })
+
+ req := httptest.NewRequest(http.MethodGet, "/health", nil)
+ rec := httptest.NewRecorder()
+ e.ServeHTTP(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200", rec.Code)
+ }
+
+ var got map[string]any
+ if err := json.Unmarshal(bytes.TrimSpace(buf.Bytes()), &got); err != nil {
+ t.Fatalf("unmarshal: %v\n%s", err, buf.String())
+ }
+ rid, _ := got["request_id"].(string)
+ if rid == "" {
+ t.Fatalf("expected generated request_id, got %v", got["request_id"])
+ }
+}
+
+// Compile-time check: ctxHandler implements slog.Handler so it can be passed
+// to slog.New.
+var _ slog.Handler = (*ctxHandler)(nil)
+var _ context.Context = context.Background()
diff --git a/internal/obslog/obslog.go b/internal/obslog/obslog.go
new file mode 100644
index 00000000..a948fd43
--- /dev/null
+++ b/internal/obslog/obslog.go
@@ -0,0 +1,206 @@
+// Package obslog provides structured JSON logging with a stable per-host
+// envelope (service, service_id, cell_id, region, hostname, host_ip, version)
+// shared across the control plane and worker daemon. Per-request fields
+// (request_id, sandbox_id, worker_id) are added via context.
+//
+// All logs are emitted as JSON on stdout/stderr; Vector reads journald/Docker
+// stdout on each host and ships to Axiom. Field names are snake_case and
+// fixed — adding a new well-known field requires a code change here so that
+// the dashboard schema stays stable across services.
+package obslog
+
+import (
+ "context"
+ "log"
+ "log/slog"
+ "net"
+ "os"
+ "strings"
+)
+
+// Service identifiers used in the `service` field. Keep this list short and
+// stable; adding a value is fine but renaming one breaks dashboards.
+const (
+ ServiceControlPlane = "control-plane"
+ ServiceWorker = "worker"
+ ServiceDB = "db"
+)
+
+// HostFields is the per-process envelope, captured at startup and attached
+// to every log line. Empty values are omitted.
+type HostFields struct {
+ Service string // "control-plane" | "worker" | "db"
+ ServiceID string // worker_id for workers; hostname for control plane
+ CellID string // <region>-<pool>, e.g. "eastus2-default"
+ Region string
+ Hostname string
+ HostIP string
+ Version string
+}
+
+// contextKey is unexported to prevent collisions with other packages.
+type contextKey struct{}
+
+// RequestFields are per-request attributes attached to log lines via context.
+// Empty fields are omitted from output.
+type RequestFields struct {
+ RequestID string // X-Request-Id, propagated across services
+ SandboxID string // when in scope
+ WorkerID string // on control-plane logs, the worker chosen for this request
+}
+
+// Init builds a JSON slog.Logger with HostFields baked in, installs it as the
+// default slog logger, AND redirects the stdlib `log` package through it so
+// existing `log.Printf` call sites are picked up automatically. Returns the
+// logger for explicit use.
+//
+// Call this once from main() before any logging happens.
+func Init(h HostFields, level slog.Level) *slog.Logger {
+ if h.Hostname == "" {
+ h.Hostname, _ = os.Hostname()
+ }
+ if h.HostIP == "" {
+ h.HostIP = detectHostIP()
+ }
+
+ handler := &ctxHandler{
+ inner: slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
+ Level: level,
+ }),
+ }
+
+ attrs := []slog.Attr{}
+ if h.Service != "" {
+ attrs = append(attrs, slog.String("service", h.Service))
+ }
+ if h.ServiceID != "" {
+ attrs = append(attrs, slog.String("service_id", h.ServiceID))
+ }
+ if h.CellID != "" {
+ attrs = append(attrs, slog.String("cell_id", h.CellID))
+ }
+ if h.Region != "" {
+ attrs = append(attrs, slog.String("region", h.Region))
+ }
+ if h.Hostname != "" {
+ attrs = append(attrs, slog.String("hostname", h.Hostname))
+ }
+ if h.HostIP != "" {
+ attrs = append(attrs, slog.String("host_ip", h.HostIP))
+ }
+ if h.Version != "" {
+ attrs = append(attrs, slog.String("version", h.Version))
+ }
+
+ logger := slog.New(handler.WithAttrs(attrs))
+ slog.SetDefault(logger)
+
+ // Redirect stdlib log.Printf / log.Println / log.Fatalf through slog so
+ // existing call sites emit JSON with the host envelope. Stdlib log calls
+ // land at INFO; this loses no semantics because the existing call sites
+ // don't differentiate levels.
+ log.SetFlags(0)
+ log.SetOutput(&slogWriter{logger: logger, level: slog.LevelInfo})
+
+ return logger
+}
+
+// WithRequest returns a new context carrying request fields. Subsequent log
+// lines emitted with this context (via slog.InfoContext etc.) include them.
+func WithRequest(ctx context.Context, f RequestFields) context.Context {
+ if existing, ok := ctx.Value(contextKey{}).(RequestFields); ok {
+ // Merge — non-empty new fields win, but don't clobber an existing
+ // request_id mid-flight.
+ if f.RequestID == "" {
+ f.RequestID = existing.RequestID
+ }
+ if f.SandboxID == "" {
+ f.SandboxID = existing.SandboxID
+ }
+ if f.WorkerID == "" {
+ f.WorkerID = existing.WorkerID
+ }
+ }
+ return context.WithValue(ctx, contextKey{}, f)
+}
+
+// Request returns the RequestFields stored on ctx, or the zero value.
+func Request(ctx context.Context) RequestFields {
+ if ctx == nil {
+ return RequestFields{}
+ }
+ f, _ := ctx.Value(contextKey{}).(RequestFields)
+ return f
+}
+
+// ctxHandler wraps a slog.Handler, injecting per-request fields from ctx into
+// every record. This means call sites don't have to pass attrs manually —
+// `slog.InfoContext(ctx, "msg")` automatically picks up request_id etc.
+type ctxHandler struct {
+ inner slog.Handler
+}
+
+func (h *ctxHandler) Enabled(ctx context.Context, level slog.Level) bool {
+ return h.inner.Enabled(ctx, level)
+}
+
+func (h *ctxHandler) Handle(ctx context.Context, r slog.Record) error {
+ rf := Request(ctx)
+ if rf.RequestID != "" {
+ r.AddAttrs(slog.String("request_id", rf.RequestID))
+ }
+ if rf.SandboxID != "" {
+ r.AddAttrs(slog.String("sandbox_id", rf.SandboxID))
+ }
+ if rf.WorkerID != "" {
+ r.AddAttrs(slog.String("worker_id", rf.WorkerID))
+ }
+ return h.inner.Handle(ctx, r)
+}
+
+func (h *ctxHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
+ return &ctxHandler{inner: h.inner.WithAttrs(attrs)}
+}
+
+func (h *ctxHandler) WithGroup(name string) slog.Handler {
+ return &ctxHandler{inner: h.inner.WithGroup(name)}
+}
+
+// slogWriter adapts an io.Writer call (used by stdlib log.Logger) to a slog
+// call so legacy `log.Printf("...")` lines flow through the JSON pipeline.
+type slogWriter struct {
+ logger *slog.Logger
+ level slog.Level
+}
+
+func (w *slogWriter) Write(p []byte) (int, error) {
+ msg := strings.TrimRight(string(p), "\n")
+ w.logger.Log(context.Background(), w.level, msg)
+ return len(p), nil
+}
+
+// detectHostIP returns the first non-loopback IPv4 address on the host, or ""
+// if none can be discovered. Used as a fallback when OPENSANDBOX_HOST_IP is
+// not provisioned at boot.
+func detectHostIP() string {
+ addrs, err := net.InterfaceAddrs()
+ if err != nil {
+ return ""
+ }
+ for _, a := range addrs {
+ ipnet, ok := a.(*net.IPNet)
+ // Skip loopback (127.x) and link-local (169.254.x). On Azure, the
+ // IMDS metadata interface advertises 169.254.169.253 and shows up
+ // first in InterfaceAddrs() — without this filter, every Azure host
+ // reports the same IP, which collapses per-host filtering in Axiom.
+ if !ok || ipnet.IP.IsLoopback() || ipnet.IP.IsLinkLocalUnicast() {
+ continue
+ }
+ ip4 := ipnet.IP.To4()
+ if ip4 == nil {
+ continue
+ }
+ return ip4.String()
+ }
+ return ""
+}
diff --git a/internal/obslog/obslog_test.go b/internal/obslog/obslog_test.go
new file mode 100644
index 00000000..2531fe6c
--- /dev/null
+++ b/internal/obslog/obslog_test.go
@@ -0,0 +1,125 @@
+package obslog
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "log/slog"
+ "net"
+ "testing"
+)
+
+// newTestLogger builds an isolated logger writing to buf, with the same
+// ctxHandler wrapping the real package uses. Init() can't be used in tests
+// because it mutates process globals.
+func newTestLogger(buf *bytes.Buffer, host HostFields) *slog.Logger {
+ handler := &ctxHandler{
+ inner: slog.NewJSONHandler(buf, &slog.HandlerOptions{Level: slog.LevelDebug}),
+ }
+ attrs := []slog.Attr{
+ slog.String("service", host.Service),
+ slog.String("service_id", host.ServiceID),
+ slog.String("cell_id", host.CellID),
+ }
+ return slog.New(handler.WithAttrs(attrs))
+}
+
+func TestHostEnvelopeAppearsOnEveryLine(t *testing.T) {
+ var buf bytes.Buffer
+ logger := newTestLogger(&buf, HostFields{
+ Service: ServiceControlPlane,
+ ServiceID: "cp-1",
+ CellID: "eastus2-default",
+ })
+ logger.Info("hello")
+
+ var got map[string]any
+ if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
+ t.Fatalf("unmarshal: %v\n%s", err, buf.String())
+ }
+ if got["service"] != "control-plane" {
+ t.Errorf("service = %v, want control-plane", got["service"])
+ }
+ if got["service_id"] != "cp-1" {
+ t.Errorf("service_id = %v, want cp-1", got["service_id"])
+ }
+ if got["cell_id"] != "eastus2-default" {
+ t.Errorf("cell_id = %v, want eastus2-default", got["cell_id"])
+ }
+ if got["msg"] != "hello" {
+ t.Errorf("msg = %v, want hello", got["msg"])
+ }
+}
+
+func TestRequestFieldsFromContext(t *testing.T) {
+ var buf bytes.Buffer
+ logger := newTestLogger(&buf, HostFields{Service: ServiceWorker})
+
+ ctx := WithRequest(context.Background(), RequestFields{
+ RequestID: "req-abc",
+ SandboxID: "sb-xyz",
+ })
+ logger.InfoContext(ctx, "handling")
+
+ var got map[string]any
+ if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
+ t.Fatalf("unmarshal: %v\n%s", err, buf.String())
+ }
+ if got["request_id"] != "req-abc" {
+ t.Errorf("request_id = %v, want req-abc", got["request_id"])
+ }
+ if got["sandbox_id"] != "sb-xyz" {
+ t.Errorf("sandbox_id = %v, want sb-xyz", got["sandbox_id"])
+ }
+}
+
+func TestRequestFieldsMergeWithoutClobbering(t *testing.T) {
+ ctx := WithRequest(context.Background(), RequestFields{RequestID: "req-1"})
+ ctx = WithRequest(ctx, RequestFields{SandboxID: "sb-1"})
+
+ got := Request(ctx)
+ if got.RequestID != "req-1" {
+ t.Errorf("RequestID = %q, want req-1 (must survive second WithRequest)", got.RequestID)
+ }
+ if got.SandboxID != "sb-1" {
+ t.Errorf("SandboxID = %q, want sb-1", got.SandboxID)
+ }
+}
+
+func TestDetectHostIPSkipsLinkLocal(t *testing.T) {
+ // We can't easily inject fake interfaces, but we can assert the returned
+ // IP — if any — is not in the link-local or loopback ranges. On a host
+ // with at least one normal interface this guards against the Azure IMDS
+ // regression where 169.254.169.253 was being reported.
+ ip := detectHostIP()
+ if ip == "" {
+ t.Skip("no non-loopback interface available in test environment")
+ }
+ parsed := net.ParseIP(ip)
+ if parsed == nil {
+ t.Fatalf("detectHostIP returned %q which is not a valid IP", ip)
+ }
+ if parsed.IsLoopback() {
+ t.Errorf("detectHostIP returned loopback %q", ip)
+ }
+ if parsed.IsLinkLocalUnicast() {
+ t.Errorf("detectHostIP returned link-local %q", ip)
+ }
+}
+
+func TestRequestFieldsOmittedWhenAbsent(t *testing.T) {
+ var buf bytes.Buffer
+ logger := newTestLogger(&buf, HostFields{Service: ServiceWorker})
+ logger.Info("no request context")
+
+ var got map[string]any
+ if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
+ t.Fatalf("unmarshal: %v", err)
+ }
+ if _, exists := got["request_id"]; exists {
+ t.Errorf("request_id should be absent when not set, got %v", got["request_id"])
+ }
+ if _, exists := got["sandbox_id"]; exists {
+ t.Errorf("sandbox_id should be absent when not set, got %v", got["sandbox_id"])
+ }
+}
diff --git a/internal/proxy/sandbox_api_proxy.go b/internal/proxy/sandbox_api_proxy.go
index 611d70f9..05b53cca 100644
--- a/internal/proxy/sandbox_api_proxy.go
+++ b/internal/proxy/sandbox_api_proxy.go
@@ -266,6 +266,13 @@ func (p *SandboxAPIProxy) doHTTP(c echo.Context, sandboxID, workerURL, token str
r.URL.RawQuery = c.Request().URL.RawQuery
r.Host = target.Host
+ // Forward X-Request-Id so worker log lines share the same id as the
+ // control plane log line for this request. Echo's middleware.RequestID
+ // on the worker side reuses the inbound header if present.
+ if rid := c.Request().Header.Get(echo.HeaderXRequestID); rid != "" {
+ r.Header.Set(echo.HeaderXRequestID, rid)
+ }
+
// Set sandbox JWT auth for the worker
if token != "" {
r.Header.Set("Authorization", "Bearer "+token)
diff --git a/internal/worker/http_server.go b/internal/worker/http_server.go
index 58e13bbc..14eae37f 100644
--- a/internal/worker/http_server.go
+++ b/internal/worker/http_server.go
@@ -7,6 +7,7 @@ import (
"github.com/labstack/echo/v4/middleware"
"github.com/opensandbox/opensandbox/internal/auth"
"github.com/opensandbox/opensandbox/internal/observability"
+ "github.com/opensandbox/opensandbox/internal/obslog"
"github.com/opensandbox/opensandbox/internal/proxy"
"github.com/opensandbox/opensandbox/internal/sandbox"
)
@@ -43,11 +44,15 @@ func NewHTTPServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, execMgr *san
// Global middleware. Sentry goes first so it can observe panics and
// attach request context before echo's Recover middleware handles them.
+ // RequestID() before obslog so the request_id is on the context when
+ // our middleware tags it — and the control plane forwards X-Request-Id
+ // from its proxy, which Echo's RequestID() reuses instead of generating
+ // a new id, so the same id appears on both control plane and worker logs.
e.Use(observability.EchoMiddleware())
e.Use(middleware.Recover())
- e.Use(middleware.Logger())
- e.Use(middleware.CORS())
e.Use(middleware.RequestID())
+ e.Use(obslog.EchoMiddleware())
+ e.Use(middleware.CORS())
// Subdomain proxy middleware (before auth — subdomain traffic is public)
if sbProxy != nil {