An open-source, faster Devin alternative
TypeScript
metrics: ship platform metrics to Axiom via Vector (#244)
Mohamed Habib70898bc0ab66
diff --git a/cmd/server/main.go b/cmd/server/main.goindex 60885d67..b9ef3150 100644--- a/cmd/server/main.go+++ b/cmd/server/main.go@@ -23,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/metrics""github.com/opensandbox/opensandbox/internal/obslog""github.com/opensandbox/opensandbox/internal/observability""github.com/opensandbox/opensandbox/internal/proxy"@@ -556,6 +557,13 @@ func main() {addr := fmt.Sprintf(":%d", cfg.Port)log.Printf("opensandbox: starting server on %s (mode=%s)", addr, cfg.Mode)+ // Prometheus /metrics endpoint on a separate port. Different from the+ // worker's :9091 so a dev-host (worker+server on one VM) doesn't collide.+ // Vector scrapes this and ships to Axiom alongside platform logs.+ metricsSrv := metrics.StartMetricsServer(":9092")+ defer metricsSrv.Close()+ log.Println("opensandbox: metrics server started on :9092")+go func() {if err := server.Start(addr); err != nil {log.Printf("server error: %v", err)diff --git a/cmd/worker/main.go b/cmd/worker/main.goindex f1f552cf..2cb350b1 100644--- a/cmd/worker/main.go+++ b/cmd/worker/main.go@@ -166,6 +166,7 @@ func main() {QEMUBin: cfg.QEMUBin,AgentBinaryPath: "/usr/local/bin/osb-agent",AgentVersion: AgentVersion,+ Region: cfg.Region,DefaultMemoryMB: cfg.DefaultSandboxMemoryMB,DefaultCPUs: cfg.DefaultSandboxCPUs,DefaultDiskMB: cfg.DefaultSandboxDiskMB,@@ -413,10 +414,22 @@ func main() {defer metricsSrv.Close()log.Println("opensandbox-worker: metrics server started on :9091")+ // Periodic resource-stats sampler: disk bytes (used/avail/total on the+ // data mount), memory bytes (total/avail from /proc/meminfo), allocated+ // memory (sum of MemoryMB across running VMs), CPU pressure (PSI 'some'+ // avg10/avg60/avg300, or loadavg/nproc fallback).+ var allocator worker.MemoryAllocator+ if qemuMgr != nil {+ allocator = qemuMgr+ }+ worker.StartResourceMetricsTick(ctx, allocator, cfg.Region, cfg.WorkerID, cfg.DataDir, 30*time.Second)+// gRPC server (nil builder — template building via podman not needed for QEMU)grpcServer := worker.NewGRPCServer(mgr, ptyMgr, execMgr, sandboxDBMgr, checkpointStore, sbRouter, nil, store)// Wire up Axiom log-shipping. Empty token disables shipping (kill-switch).grpcServer.SetAxiomConfig(cfg.AxiomIngestToken, cfg.AxiomDataset)+ // Tag wake-source metrics with the worker's region.+ grpcServer.SetRegion(cfg.Region)if cfg.AxiomIngestToken != "" {log.Printf("opensandbox-worker: sandbox session log shipping enabled (dataset=%s)", cfg.AxiomDataset)}diff --git a/deploy/vector/control-plane.yaml b/deploy/vector/control-plane.yamlindex 896d4f91..69dfca28 100644--- a/deploy/vector/control-plane.yaml+++ b/deploy/vector/control-plane.yaml@@ -1,7 +1,7 @@# 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.+# not Docker). Reads opensandbox-server.service from journald, scrapes the+# control plane's Prometheus /metrics on :9092, enriches both streams with+# the host envelope, and ships to oc-platform-logs.## Install path: /etc/vector/vector.yaml# Env file: /etc/opensandbox/vector.env (populated by@@ -17,6 +17,16 @@ sources:# Default current_boot_only=true is fine — Vector tracks its own cursor# in data_dir, so restarts resume cleanly without replaying the journal.+ # Scrape the control plane's own /metrics on :9092. Different port from the+ # worker's :9091 so a dev host running both binaries doesn't collide. The+ # control-plane binary serves Prometheus via metrics.StartMetricsServer+ # (cmd/server/main.go).+ control_plane_metrics:+ type: prometheus_scrape+ endpoints:+ - http://127.0.0.1:9092/metrics+ scrape_interval_secs: 30+transforms:control_plane_parse:type: remap@@ -37,7 +47,36 @@ transforms:if !exists(.host_ip) { .host_ip = "${OPENCOMPUTER_HOST_IP:-unknown}" }if !exists(.hostname) { .hostname, _ = get_hostname() }+ # Convert metric events to log shape (metric_to_log is a transform type;+ # VRL has no `to_log` function in Vector 0.55+).+ control_plane_metrics_to_log:+ type: metric_to_log+ inputs:+ - control_plane_metrics++ # Envelope: same fields as logs so cross-event-type joins work in Axiom+ # (event_type="metric" filter, then group by region/cell_id/...).+ # metric_name carries the Prom name; namespaced to dodge a clash with any+ # log payload that happens to contain a literal `name` field.+ control_plane_metrics_envelope:+ type: remap+ inputs:+ - control_plane_metrics_to_log+ source: |+ .event_type = "metric"+ if exists(.name) {+ .metric_name = .name+ del(.name)+ }+ .service = "control-plane"+ .service_id, _ = get_hostname()+ .cell_id = "${OPENCOMPUTER_CELL_ID:-unknown}"+ .region = "${OPENSANDBOX_REGION:-unknown}"+ .host_ip = "${OPENCOMPUTER_HOST_IP:-unknown}"+ .hostname, _ = get_hostname()+sinks:+ # Logs sink: ships journald (parsed + enveloped) to the platform-logs dataset.axiom_platform:type: axiominputs:@@ -50,3 +89,20 @@ sinks:when_full: drop_newesthealthcheck:enabled: true++ # Metrics sink: separate dataset + token. See worker.yaml for the rationale+ # (histogram-bucket volume, independent retention/budget, independent+ # rollout). Soft-fails on missing creds — buffers to disk and doesn't take+ # the logs sink down.+ axiom_metrics:+ type: axiom+ inputs:+ - control_plane_metrics_envelope+ dataset: "${AXIOM_PLATFORM_METRICS_DATASET}"+ token: "${AXIOM_PLATFORM_METRICS_TOKEN}"+ buffer:+ type: disk+ max_size: 268435488+ when_full: drop_newest+ healthcheck:+ enabled: truediff --git a/deploy/vector/dev-host.yaml b/deploy/vector/dev-host.yamlindex 38d2081a..8965dd26 100644--- a/deploy/vector/dev-host.yaml+++ b/deploy/vector/dev-host.yaml@@ -7,7 +7,9 @@# 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.+# tags `service` based on which unit emitted each line. Two Prometheus+# scrape sources (9091=worker, 9092=control-plane) feed metric events through+# the same envelope path.## Install path: /etc/vector/vector.yaml# Env file: /etc/opensandbox/vector.env (provides AXIOM_PLATFORM_TOKEN)@@ -24,6 +26,21 @@ sources:# limitation). Default (true) is fine — Vector tracks its own cursor in# data_dir, so restarts pick up where they left off rather than replaying.+ # Two scrape sources so each emitted metric event can carry the correct+ # service label (worker vs control-plane). Vector doesn't expose the scrape+ # endpoint as a field, so we split sources and tag in the transforms.+ dev_worker_metrics:+ type: prometheus_scrape+ endpoints:+ - http://127.0.0.1:9091/metrics+ scrape_interval_secs: 30++ dev_control_plane_metrics:+ type: prometheus_scrape+ endpoints:+ - http://127.0.0.1:9092/metrics+ scrape_interval_secs: 30+transforms:dev_parse:type: remap@@ -72,7 +89,60 @@ transforms:# don't claim the dev tag..environment = "dev"+ # Convert each scrape source to log shape (metric_to_log is a transform+ # type; VRL has no `to_log` function in Vector 0.55+). Two parallel+ # converters so we can stamp the right service label downstream without+ # re-parsing the scrape endpoint URL.+ dev_worker_metrics_to_log:+ type: metric_to_log+ inputs:+ - dev_worker_metrics++ dev_control_plane_metrics_to_log:+ type: metric_to_log+ inputs:+ - dev_control_plane_metrics++ # Envelopes: same shape as dev_parse for join-friendly events. event_type="metric"+ # is the cross-type discriminator.+ dev_worker_metrics_envelope:+ type: remap+ inputs:+ - dev_worker_metrics_to_log+ source: |+ .event_type = "metric"+ if exists(.name) {+ .metric_name = .name+ del(.name)+ }+ .service = "worker"+ .service_id = "${OPENSANDBOX_WORKER_ID:-unknown}"+ .cell_id = "${OPENCOMPUTER_CELL_ID:-unknown}"+ .region = "${OPENSANDBOX_REGION:-unknown}"+ .host_ip = "${OPENCOMPUTER_HOST_IP:-unknown}"+ .hostname, _ = get_hostname()+ .environment = "dev"++ dev_control_plane_metrics_envelope:+ type: remap+ inputs:+ - dev_control_plane_metrics_to_log+ source: |+ .event_type = "metric"+ if exists(.name) {+ .metric_name = .name+ del(.name)+ }+ .service = "control-plane"+ .service_id, _ = get_hostname()+ .cell_id = "${OPENCOMPUTER_CELL_ID:-unknown}"+ .region = "${OPENSANDBOX_REGION:-unknown}"+ .host_ip = "${OPENCOMPUTER_HOST_IP:-unknown}"+ .hostname, _ = get_hostname()+ .environment = "dev"+sinks:+ # Logs sink: ships journald (parsed + enveloped) to the platform-logs dataset.axiom_platform:type: axiominputs:@@ -85,3 +155,20 @@ sinks:when_full: drop_newesthealthcheck:enabled: true++ # Metrics sink: separate dataset + token. Both scrape sources funnel through+ # here. See worker.yaml for the rationale (histogram-bucket volume,+ # independent retention/budget, independent rollout).+ axiom_metrics:+ type: axiom+ inputs:+ - dev_worker_metrics_envelope+ - dev_control_plane_metrics_envelope+ dataset: "${AXIOM_PLATFORM_METRICS_DATASET}"+ token: "${AXIOM_PLATFORM_METRICS_TOKEN}"+ buffer:+ type: disk+ max_size: 268435488+ when_full: drop_newest+ healthcheck:+ enabled: truediff --git a/deploy/vector/populate-vector-env.sh b/deploy/vector/populate-vector-env.shindex 19282a83..577d5010 100755--- a/deploy/vector/populate-vector-env.sh+++ b/deploy/vector/populate-vector-env.sh@@ -1,5 +1,5 @@#!/bin/bash-# populate-vector-env.sh — Fetch the Axiom platform-logs ingest credentials+# populate-vector-env.sh — Fetch the Axiom platform 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.#@@ -17,19 +17,27 @@# 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)+# shared-axiom-platform-ingest-token → AXIOM_PLATFORM_TOKEN (required — logs)+# shared-axiom-platform-dataset → AXIOM_PLATFORM_DATASET (required — logs)+# shared-axiom-platform-metrics-ingest-token → AXIOM_PLATFORM_METRICS_TOKEN (optional — metrics)+# shared-axiom-platform-metrics-dataset → AXIOM_PLATFORM_METRICS_DATASET (optional — metrics)#-# 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).+# Logs secrets are hard-required: missing → exit 0 without writing env file,+# Vector fails healthcheck and buffers to disk until the secret appears+# (don't break the worker boot path over a logging credential).+#+# Metrics secrets are soft-optional: missing → env file still gets written+# with logs creds set, metrics ones empty. The metrics sink fails healthcheck+# and buffers to disk independently. Lets operators roll out the metrics+# dataset asynchronously without coordinating with the worker fleet.set -euo pipefailVAULT_NAME="${OPENSANDBOX_AZURE_KEY_VAULT_NAME:-}"ENV_FILE=/etc/opensandbox/vector.envTOKEN_SECRET=shared-axiom-platform-ingest-tokenDATASET_SECRET=shared-axiom-platform-dataset+METRICS_TOKEN_SECRET=shared-axiom-platform-metrics-ingest-token+METRICS_DATASET_SECRET=shared-axiom-platform-metrics-datasetlog() { logger -t populate-vector-env "$*"; echo "$*"; }@@ -70,6 +78,16 @@ if [ -z "$DATASET_VALUE" ]; thenexit 0fi+# Metrics creds are soft-optional. Empty values land in the env file and the+# axiom_metrics sink in Vector fails its healthcheck; the logs sink keeps+# working. Lets operators provision the metrics dataset on their own schedule+# without coordinating with worker boots.+METRICS_TOKEN_VALUE=$(kv_get "$METRICS_TOKEN_SECRET")+METRICS_DATASET_VALUE=$(kv_get "$METRICS_DATASET_SECRET")+if [ -z "$METRICS_TOKEN_VALUE" ] || [ -z "$METRICS_DATASET_VALUE" ]; then+ log "metrics secrets ($METRICS_TOKEN_SECRET / $METRICS_DATASET_SECRET) missing — metrics sink will buffer to disk until configured"+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)@@ -78,6 +96,8 @@ umask 077cat > "${ENV_FILE}.tmp" <<EOFAXIOM_PLATFORM_TOKEN=${TOKEN_VALUE}AXIOM_PLATFORM_DATASET=${DATASET_VALUE}+AXIOM_PLATFORM_METRICS_TOKEN=${METRICS_TOKEN_VALUE}+AXIOM_PLATFORM_METRICS_DATASET=${METRICS_DATASET_VALUE}OPENCOMPUTER_CELL_ID=${OPENCOMPUTER_CELL_ID:-unknown}OPENSANDBOX_REGION=${OPENSANDBOX_REGION:-unknown}OPENCOMPUTER_HOST_IP=${HOST_IP:-unknown}@@ -86,4 +106,8 @@ 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})"+metrics_status="absent"+if [ -n "$METRICS_TOKEN_VALUE" ] && [ -n "$METRICS_DATASET_VALUE" ]; then+ metrics_status="present"+fi+log "populated $ENV_FILE (logs token+dataset from $VAULT_NAME, metrics=$metrics_status, host_ip=${HOST_IP:-unknown})"diff --git a/deploy/vector/worker.yaml b/deploy/vector/worker.yamlindex a066d242..143fa2ae 100644--- a/deploy/vector/worker.yaml+++ b/deploy/vector/worker.yaml@@ -1,12 +1,16 @@# 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.+# Two pipelines, two Axiom datasets:+# • logs: journald → parse → axiom_platform sink → AXIOM_PLATFORM_DATASET+# • metrics: /metrics scrape → envelope → axiom_metrics sink → AXIOM_PLATFORM_METRICS_DATASET+#+# Separate datasets because histogram-bucket volume dwarfs log volume at scale+# and the two streams want different retention/cost policies.## Install path: /etc/vector/vector.yaml-# Env file: /etc/opensandbox/vector.env (provides AXIOM_PLATFORM_TOKEN)+# Env file: /etc/opensandbox/vector.env (provides AXIOM_PLATFORM_TOKEN ++# AXIOM_PLATFORM_METRICS_TOKEN, populated by+# populate-vector-env.service from Key Vault at boot)## Field shape after this pipeline:# service "worker"@@ -15,6 +19,9 @@# region e.g. eastus2# hostname VM hostname# host_ip primary IPv4+# event_type "metric" for scraped Prom samples, absent on logs+# metric_name Prom metric name when event_type=="metric"+# tags Prom label map when event_type=="metric"# 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@@ -30,6 +37,16 @@ sources:# systemd 250-257 — Vector limitation.) Vector tracks its own cursor in# data_dir, so restarts pick up where they left off rather than replaying.+ # Scrape the worker's own /metrics on :9091. The worker binary serves+ # Prometheus via metrics.StartMetricsServer (cmd/worker/main.go). 30s+ # matches the worker's internal resource-stats tick so we don't capture+ # interpolated transient values.+ worker_metrics:+ type: prometheus_scrape+ endpoints:+ - http://127.0.0.1:9091/metrics+ scrape_interval_secs: 30+transforms:worker_parse:type: remap@@ -53,7 +70,43 @@ transforms:if !exists(.host_ip) { .host_ip = "${OPENCOMPUTER_HOST_IP:-unknown}" }if !exists(.hostname) { .hostname, _ = get_hostname() }+ # Convert Prom metric events to log-shaped events so the Axiom sink can+ # ingest them. metric_to_log is a dedicated transform type — VRL has no+ # `to_log` function (Vector 0.55+).+ worker_metrics_to_log:+ type: metric_to_log+ inputs:+ - worker_metrics++ # Envelope: same fields as logs (service/service_id/cell_id/region/host_ip/+ # hostname) so dashboards can join across event_type and cross-filter by+ # infra dimension. event_type="metric" is the discriminator vs logs — we+ # deliberately don't reuse `kind`, which metric_to_log writes as+ # "incremental"/"absolute".+ #+ # metric_name carries the Prom name (namespaced to dodge clashes with log+ # payloads that might contain a literal `name` field). Label values stay+ # under `.tags` (region, worker_id, template, status, ...).+ worker_metrics_envelope:+ type: remap+ inputs:+ - worker_metrics_to_log+ source: |+ .event_type = "metric"+ if exists(.name) {+ .metric_name = .name+ del(.name)+ }+ .service = "worker"+ .service_id = "${OPENSANDBOX_WORKER_ID:-unknown}"+ .cell_id = "${OPENCOMPUTER_CELL_ID:-unknown}"+ .region = "${OPENSANDBOX_REGION:-unknown}"+ .host_ip = "${OPENCOMPUTER_HOST_IP:-unknown}"+ .hostname, _ = get_hostname()+sinks:+ # Logs sink: ships journald (parsed + enveloped) to the platform-logs dataset.+ # Unchanged from pre-metrics behavior.axiom_platform:type: axiominputs:@@ -69,3 +122,21 @@ sinks:when_full: drop_newesthealthcheck:enabled: true++ # Metrics sink: separate Axiom dataset (typically `oc-platform-metrics`)+ # with its own ingest token. Volume is histogram-bucket-multiplied and+ # belongs on a different retention/budget than logs. If the secrets aren't+ # provisioned yet the populator writes empty values; this sink fails its+ # healthcheck and buffers to disk independently — the logs sink keeps working.+ axiom_metrics:+ type: axiom+ inputs:+ - worker_metrics_envelope+ dataset: "${AXIOM_PLATFORM_METRICS_DATASET}"+ token: "${AXIOM_PLATFORM_METRICS_TOKEN}"+ buffer:+ type: disk+ max_size: 268435488+ when_full: drop_newest+ healthcheck:+ enabled: truediff --git a/internal/api/router.go b/internal/api/router.goindex fcc2b6b7..793eea09 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -21,6 +21,7 @@ import ("github.com/opensandbox/opensandbox/internal/cloudflare""github.com/opensandbox/opensandbox/internal/controlplane""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"@@ -161,6 +162,10 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, oe.Use(middleware.Recover())e.Use(middleware.RequestID())e.Use(obslog.EchoMiddleware())+ // Prometheus instrumentation: counts requests by status, observes handler+ // latency, tracks in-flight. Uses c.Path() (route template) for the path+ // label so high-cardinality IDs don't blow up the metric.+ e.Use(metrics.EchoMiddleware())e.Use(middleware.CORS())// Subdomain proxy middleware (before auth — subdomain traffic is public)diff --git a/internal/metrics/metrics.go b/internal/metrics/metrics.goindex 4f714058..54a78aea 100644--- a/internal/metrics/metrics.go+++ b/internal/metrics/metrics.go@@ -10,6 +10,9 @@ import ("github.com/prometheus/client_golang/prometheus/promhttp")+// lifecycleBuckets covers from sub-second warm forks to slow checkpoint uploads.+var lifecycleBuckets = []float64{0.1, 0.25, 0.5, 1.0, 2.0, 5.0, 10.0, 30.0, 60.0}+// Worker metricsvar (SandboxesActive = prometheus.NewGaugeVec(@@ -24,9 +27,47 @@ var (prometheus.HistogramOpts{Name: "opensandbox_sandbox_create_duration_seconds",Help: "Time to create a sandbox",- Buckets: []float64{0.1, 0.25, 0.5, 1.0, 2.0, 5.0, 10.0},+ Buckets: lifecycleBuckets,+ },+ []string{"region", "template", "status"},+ )++ CheckpointDuration = prometheus.NewHistogramVec(+ prometheus.HistogramOpts{+ Name: "opensandbox_checkpoint_duration_seconds",+ Help: "Time to create a sandbox checkpoint (savevm + archive + upload)",+ Buckets: lifecycleBuckets,+ },+ []string{"region", "template", "status"},+ )++ // Exists alongside CheckpointDuration{status="failure"} so failures can be+ // attributed by *cause* without log parsing.+ CheckpointFailuresTotal = prometheus.NewCounterVec(+ prometheus.CounterOpts{+ Name: "opensandbox_checkpoint_failures_total",+ Help: "Checkpoint failures by classified reason",},- []string{"region", "template"},+ []string{"region", "template", "reason"},+ )++ HibernateDuration = prometheus.NewHistogramVec(+ prometheus.HistogramOpts{+ Name: "opensandbox_hibernate_duration_seconds",+ Help: "Time to hibernate a sandbox (quiesce + savevm + upload)",+ Buckets: lifecycleBuckets,+ },+ []string{"region", "template", "status"},+ )++ // source=warm_cache: local snapshot reused. source=s3: downloaded archive.+ WakeDuration = prometheus.NewHistogramVec(+ prometheus.HistogramOpts{+ Name: "opensandbox_wake_duration_seconds",+ Help: "Time to create a sandbox from a checkpoint",+ Buckets: lifecycleBuckets,+ },+ []string{"region", "template", "source", "status"},)ExecDuration = prometheus.NewHistogramVec(@@ -54,6 +95,44 @@ var ([]string{"region", "worker_id"},)+ // Worker resource gauges. Populated by a periodic tick in cmd/worker/main.go.+ WorkerDiskUsedBytes = prometheus.NewGaugeVec(+ prometheus.GaugeOpts{Name: "opensandbox_worker_disk_used_bytes", Help: "Disk bytes used on the worker's data mount"},+ []string{"region", "worker_id", "mount"},+ )+ WorkerDiskAvailableBytes = prometheus.NewGaugeVec(+ prometheus.GaugeOpts{Name: "opensandbox_worker_disk_available_bytes", Help: "Disk bytes available on the worker's data mount"},+ []string{"region", "worker_id", "mount"},+ )+ WorkerDiskTotalBytes = prometheus.NewGaugeVec(+ prometheus.GaugeOpts{Name: "opensandbox_worker_disk_total_bytes", Help: "Total disk bytes on the worker's data mount"},+ []string{"region", "worker_id", "mount"},+ )++ WorkerMemoryTotalBytes = prometheus.NewGaugeVec(+ prometheus.GaugeOpts{Name: "opensandbox_worker_memory_total_bytes", Help: "Total physical memory (MemTotal)"},+ []string{"region", "worker_id"},+ )+ WorkerMemoryAvailableBytes = prometheus.NewGaugeVec(+ prometheus.GaugeOpts{Name: "opensandbox_worker_memory_available_bytes", Help: "Memory available to userspace (MemAvailable)"},+ []string{"region", "worker_id"},+ )+ // Sum of MemoryMB committed to running sandboxes. Measures oversubscription+ // independent of actual guest workload.+ WorkerMemoryAllocatedBytes = prometheus.NewGaugeVec(+ prometheus.GaugeOpts{Name: "opensandbox_worker_memory_allocated_bytes", Help: "Sum of memory allocated to running sandboxes"},+ []string{"region", "worker_id"},+ )++ // CPU pressure percent. window: avg10/avg60/avg300.+ // source=psi: PSI "some" stall pct from /proc/pressure/cpu (preferred).+ // source=loadavg: loadavg/nproc*100 fallback (older kernels / macOS dev hosts);+ // different semantics — interpret with care.+ WorkerCPUPressure = prometheus.NewGaugeVec(+ prometheus.GaugeOpts{Name: "opensandbox_worker_cpu_pressure", Help: "CPU pressure percent (PSI 'some' or loadavg/nproc*100 fallback)"},+ []string{"region", "worker_id", "window", "source"},+ )+DirectConnectionsActive = prometheus.NewGaugeVec(prometheus.GaugeOpts{Name: "opensandbox_direct_connections_active",@@ -81,6 +160,23 @@ var ([]string{"method", "path", "status"},)+ HTTPRequestDuration = prometheus.NewHistogramVec(+ prometheus.HistogramOpts{+ Name: "opensandbox_http_request_duration_seconds",+ Help: "HTTP request handler latency",+ Buckets: []float64{0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30},+ },+ []string{"method", "path", "status"},+ )++ HTTPRequestsInFlight = prometheus.NewGaugeVec(+ prometheus.GaugeOpts{+ Name: "opensandbox_http_requests_in_flight",+ Help: "Currently in-flight HTTP requests",+ },+ []string{"method"},+ )+SandboxCreatesTotal = prometheus.NewCounterVec(prometheus.CounterOpts{Name: "opensandbox_sandbox_creates_total",@@ -115,16 +211,28 @@ var ()func init() {- // Register all metricsprometheus.MustRegister(SandboxesActive,SandboxCreateDuration,+ CheckpointDuration,+ CheckpointFailuresTotal,+ HibernateDuration,+ WakeDuration,ExecDuration,PTYSessionsActive,WorkerUtilization,+ WorkerDiskUsedBytes,+ WorkerDiskAvailableBytes,+ WorkerDiskTotalBytes,+ WorkerMemoryTotalBytes,+ WorkerMemoryAvailableBytes,+ WorkerMemoryAllocatedBytes,+ WorkerCPUPressure,DirectConnectionsActive,SQLiteSyncLag,HTTPRequestsTotal,+ HTTPRequestDuration,+ HTTPRequestsInFlight,SandboxCreatesTotal,AuthAttemptsTotal,WorkersTotal,@@ -138,9 +246,16 @@ func Handler() http.Handler {}// EchoMiddleware returns Echo middleware that instruments HTTP requests.+//+// path label uses c.Path() (the route template, e.g. /api/sandboxes/:id) rather+// than c.Request().URL.Path so high-cardinality IDs don't explode the metric.func EchoMiddleware() echo.MiddlewareFunc {return func(next echo.HandlerFunc) echo.HandlerFunc {return func(c echo.Context) error {+ method := c.Request().Method+ HTTPRequestsInFlight.WithLabelValues(method).Inc()+ defer HTTPRequestsInFlight.WithLabelValues(method).Dec()+start := time.Now()err := next(c)duration := time.Since(start)@@ -152,13 +267,11 @@ func EchoMiddleware() echo.MiddlewareFunc {}}- HTTPRequestsTotal.WithLabelValues(- c.Request().Method,- c.Path(),- strconv.Itoa(status),- ).Inc()+ statusStr := strconv.Itoa(status)+ path := c.Path()+ HTTPRequestsTotal.WithLabelValues(method, path, statusStr).Inc()+ HTTPRequestDuration.WithLabelValues(method, path, statusStr).Observe(duration.Seconds())- _ = duration // Could add request duration histogram herereturn err}}diff --git a/internal/qemu/manager.go b/internal/qemu/manager.goindex 4e5293a4..cd57bd46 100644--- a/internal/qemu/manager.go+++ b/internal/qemu/manager.go@@ -20,6 +20,7 @@ import ("time""github.com/google/uuid"+ "github.com/opensandbox/opensandbox/internal/metrics""github.com/opensandbox/opensandbox/internal/sandbox""github.com/opensandbox/opensandbox/internal/storage""github.com/opensandbox/opensandbox/pkg/types"@@ -264,6 +265,7 @@ type Config struct {QEMUBin string // path to qemu-system-x86_64 binaryAgentBinaryPath string // path to osb-agent binary on host (for hot-upgrade)AgentVersion string // expected agent version (for hot-upgrade check)+ Region string // worker region (e.g. eastus2); used as a metric labelDefaultMemoryMB intDefaultCPUs intDefaultDiskMB int@@ -405,6 +407,22 @@ func (m *Manager) GoldenVersion() string {return m.goldenVersion}+// MemoryAllocatedBytes returns the sum of memory committed to currently-running+// sandboxes, in bytes. Used by the worker's resource-stats tick to report+// oversubscription independent of actual guest workload.+func (m *Manager) MemoryAllocatedBytes() uint64 {+ m.mu.RLock()+ defer m.mu.RUnlock()+ var total uint64+ for _, vm := range m.vms {+ if vm == nil {+ continue+ }+ total += uint64(vm.MemoryMB) * 1024 * 1024+ }+ return total+}+// sealSandboxEnvs runs cfg.Envs through the secrets proxy to swap real values// for sealed tokens, registers a proxy session for the guest IP, and writes the// proxy CA cert into the guest trust store. Returns the env map that should be@@ -1387,7 +1405,20 @@ func (m *Manager) buildQEMUArgs(cpus, memMB int, rootfsPath, workspacePath, tapN}// Create launches a new QEMU VM.-func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (*types.Sandbox, error) {+func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (sb *types.Sandbox, retErr error) {+ t0 := time.Now()+ template := cfg.Template+ if template == "" || template == "base" {+ template = "default"+ }+ defer func() {+ status := "success"+ if retErr != nil {+ status = "failure"+ }+ metrics.SandboxCreateDuration.WithLabelValues(m.cfg.Region, template, status).Observe(time.Since(t0).Seconds())+ }()+// Check disk space before creating — refuse if >95% to prevent ENOSPC corruptionif usage, err := diskUsagePercent(m.cfg.DataDir); err == nil && usage > 95 {return nil, fmt.Errorf("disk usage at %d%%, refusing new sandbox (threshold: 95%%)", usage)@@ -1399,10 +1430,6 @@ func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (*types.S}// Fast path: restore from golden snapshot if available and using default template- template := cfg.Template- if template == "" || template == "base" {- template = "default"- }if m.goldenDir != "" && template == "default" && cfg.TemplateRootfsKey == "" {sb, err := m.createFromGolden(ctx, cfg, id)if err != nil {@@ -2445,12 +2472,25 @@ func (m *Manager) ContainerName(id string) string {}// Hibernate snapshots a VM and uploads to S3.-func (m *Manager) Hibernate(ctx context.Context, sandboxID string, checkpointStore *storage.CheckpointStore) (*sandbox.HibernateResult, error) {+func (m *Manager) Hibernate(ctx context.Context, sandboxID string, checkpointStore *storage.CheckpointStore) (res *sandbox.HibernateResult, retErr error) {vm, err := m.getVM(sandboxID)if err != nil {+ // Pre-lookup failure — observe with an "unknown" template label so the+ // histogram still records the failure surface without inventing a+ // template we didn't find.+ metrics.HibernateDuration.WithLabelValues(m.cfg.Region, "unknown", "failure").Observe(0)return nil, err}+ t0 := time.Now()+ defer func() {+ status := "success"+ if retErr != nil {+ status = "failure"+ }+ metrics.HibernateDuration.WithLabelValues(m.cfg.Region, vm.Template, status).Observe(time.Since(t0).Seconds())+ }()+// Refuse hibernate if rootfs is critically full. dpkg/apt mid-rename + an// unsynced page cache + a savevm produces qcow2 EXT4 metadata corruption// that won't cold-mount on the next wake. Cheap pre-flight check; the@@ -2478,7 +2518,7 @@ func (m *Manager) Hibernate(ctx context.Context, sandboxID string, checkpointSto// Wake restores a VM from a snapshot.// Guards against double-wake: if the sandbox is already running, returns it.-func (m *Manager) Wake(ctx context.Context, sandboxID string, checkpointKey string, checkpointStore *storage.CheckpointStore, timeout int) (*types.Sandbox, error) {+func (m *Manager) Wake(ctx context.Context, sandboxID string, checkpointKey string, checkpointStore *storage.CheckpointStore, timeout int) (sb *types.Sandbox, retErr error) {// Prevent double wake — if sandbox is already running, return itm.mu.RLock()if existing, ok := m.vms[sandboxID]; ok {@@ -2487,6 +2527,23 @@ func (m *Manager) Wake(ctx context.Context, sandboxID string, checkpointKey strireturn vmToSandbox(existing), nil}m.mu.RUnlock()++ // Wake = resume hibernated sandbox from S3 — by definition the checkpoint+ // archive lives in object storage. ForkFromCheckpoint in grpc_server.go+ // observes the warm_cache path separately.+ t0 := time.Now()+ defer func() {+ status := "success"+ template := "unknown"+ if sb != nil {+ template = sb.Template+ }+ if retErr != nil {+ status = "failure"+ }+ metrics.WakeDuration.WithLabelValues(m.cfg.Region, template, "s3", status).Observe(time.Since(t0).Seconds())+ }()+return m.doWake(ctx, sandboxID, checkpointKey, checkpointStore, timeout)}@@ -2535,14 +2592,32 @@ func (m *Manager) CheckpointCachePath(checkpointID, filename string) string {// than being silently logged — the control plane gets the reason and// persists it via SetCheckpointFailed (migration 039 added error_msg).func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID string, checkpointStore *storage.CheckpointStore, onReady func()) (rootfsKey, workspaceKey string, sizeBytes int64, err error) {+ tStart := time.Now()+ // failureReason is updated at each error site below so the defer can attribute+ // failures by cause. Stays "other" for any unclassified path (which is a+ // signal to add an explicit classification when seen).+ failureReason := "other"+ template := "unknown"+ defer func() {+ status := "success"+ if err != nil {+ status = "failure"+ metrics.CheckpointFailuresTotal.WithLabelValues(m.cfg.Region, template, failureReason).Inc()+ }+ metrics.CheckpointDuration.WithLabelValues(m.cfg.Region, template, status).Observe(time.Since(tStart).Seconds())+ }()+vm, err := m.getVM(sandboxID)if err != nil {+ failureReason = "vm_not_found"return "", "", 0, err}+ template = vm.Template// Refuse if rootfs is critically full — same corruption risk as hibernate// (dpkg/apt mid-rename + savevm = qcow2 EXT4 metadata broken on next mount).if err := m.checkRootfsPressure(ctx, vm); err != nil {+ failureReason = "disk_pressure"return "", "", 0, err}@@ -2550,6 +2625,7 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID// Without this, rapid-fire checkpoints queue up and the agent gets into a bad state// from overlapping SIGUSR1/reconnect cycles.if !vm.opMu.TryLock() {+ failureReason = "op_in_progress"return "", "", 0, fmt.Errorf("another operation is in progress on sandbox %s — try again shortly", sandboxID)}defer vm.opMu.Unlock()@@ -2557,6 +2633,7 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointIDt0 := time.Now()if vm.qmp == nil {+ failureReason = "qmp_unavailable"return "", "", 0, fmt.Errorf("QMP connection not available for %s", sandboxID)}@@ -2568,9 +2645,10 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID// against an un-synced guest captures inconsistent qcow2 metadata that// becomes unbootable on next cold-mount. See ErrAgentUnresponsive.if vm.agent != nil {- if err := quiesceAndCloseAgent(ctx, vm.agent); err != nil {- log.Printf("qemu: CreateCheckpoint %s/%s: refusing savevm — %v", sandboxID, checkpointID, err)- return "", "", 0, fmt.Errorf("checkpoint %s: %w", sandboxID, err)+ if qErr := quiesceAndCloseAgent(ctx, vm.agent); qErr != nil {+ log.Printf("qemu: CreateCheckpoint %s/%s: refusing savevm — %v", sandboxID, checkpointID, qErr)+ failureReason = "agent_unresponsive"+ return "", "", 0, fmt.Errorf("checkpoint %s: %w", sandboxID, qErr)}vm.agent = nil}@@ -2590,12 +2668,14 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID// (close agent + let SIGUSR1 reset the virtio-serial listener before// savevm) is preserved above.if vm.qmp == nil {+ failureReason = "qmp_unavailable"return "", "", 0, fmt.Errorf("QMP connection not available for %s", sandboxID)}cacheDir := m.checkpointCacheDir(checkpointID)stagingDir := cacheDir + ".staging"if mkErr := os.MkdirAll(filepath.Join(stagingDir, "snapshot"), 0755); mkErr != nil {+ failureReason = "staging_setup"return "", "", 0, fmt.Errorf("mkdir staging: %w", mkErr)}@@ -2611,6 +2691,7 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointIDsnapshotName := "cp-" + checkpointIDif stopErr := vm.qmp.Stop(); stopErr != nil {os.RemoveAll(stagingDir)+ failureReason = "qmp_stop"return "", "", 0, fmt.Errorf("qmp stop before savevm: %w", stopErr)}saveErr := vm.qmp.SaveVM(snapshotName)@@ -2619,6 +2700,7 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID}if saveErr != nil {os.RemoveAll(stagingDir)+ failureReason = "qmp_savevm"return "", "", 0, fmt.Errorf("savevm: %w", saveErr)}log.Printf("qemu: CreateCheckpoint %s/%s: savevm complete (%dms)", sandboxID, checkpointID, time.Since(t0).Milliseconds())@@ -2631,10 +2713,12 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointIDsrcWorkspace := filepath.Join(vm.sandboxDir, "workspace.qcow2")if err := copyFileReflink(srcRootfs, filepath.Join(stagingDir, "rootfs.qcow2")); err != nil {os.RemoveAll(stagingDir)+ failureReason = "qcow2_copy"return "", "", 0, fmt.Errorf("copy rootfs: %w", err)}if err := copyFileReflink(srcWorkspace, filepath.Join(stagingDir, "workspace.qcow2")); err != nil {os.RemoveAll(stagingDir)+ failureReason = "qcow2_copy"return "", "", 0, fmt.Errorf("copy workspace: %w", err)}// Record the savevm snapshot name so ForkFromCheckpoint / RestoreFromCheckpoint@@ -2744,6 +2828,7 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointIDlog.Printf("qemu: checkpoint %s: archive failed: %v", checkpointID, archErr)// Surface as the function's error so the API can persist it via// SetCheckpointFailed instead of silently logging.+ failureReason = "archive"return rootfsKey, workspaceKey, 0, fmt.Errorf("create checkpoint archive: %w", archErr)}// 15-min upload budget. Pre-fix this was 5 min, which combined with@@ -2766,6 +2851,7 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointIDos.Remove(archivePath)if uerr != nil {log.Printf("qemu: checkpoint %s: S3 upload failed: %v", checkpointID, uerr)+ failureReason = "s3_upload"return rootfsKey, workspaceKey, sizeBytes, fmt.Errorf("upload checkpoint to S3: %w", uerr)}log.Printf("qemu: checkpoint %s: S3 upload complete (%dms, %.1f MB, files=%v)",diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.goindex 2cf8ea4f..84d01314 100644--- a/internal/worker/grpc_server.go+++ b/internal/worker/grpc_server.go@@ -21,6 +21,7 @@ import ("github.com/opensandbox/opensandbox/internal/db""github.com/opensandbox/opensandbox/internal/grpctls"+ "github.com/opensandbox/opensandbox/internal/metrics""github.com/opensandbox/opensandbox/internal/observability""github.com/opensandbox/opensandbox/internal/sandbox""github.com/opensandbox/opensandbox/internal/sparse"@@ -83,8 +84,16 @@ type GRPCServer struct {// (kill-switch). Set via SetAxiomConfig at startup.axiomIngestToken stringaxiomDataset string++ // region is the worker's region label, used to tag operation metrics.+ // Set via SetRegion at startup. Empty = "unknown".+ region string}+// SetRegion stamps the worker's region onto operation metrics emitted from+// this gRPC server (e.g. WakeDuration for warm-fork vs s3 paths).+func (s *GRPCServer) SetRegion(region string) { s.region = region }+// SetAxiomConfig wires Axiom log-shipping credentials. The worker// passes them down to each sandbox's agent on create via the// LogshipConfigurator interface (implemented by the QEMU manager).@@ -215,8 +224,17 @@ func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxReq// Warm fork: if checkpoint_id is set, fork from the local checkpoint cache.// ForkFromCheckpoint uses the local cache directly — no S3 needed.if req.CheckpointId != "" {+ // WakeDuration covers "create from checkpoint" end-to-end. source label+ // distinguishes a local-cache hit (fast, ~hundreds of ms) from a path+ // that had to pull the archive from S3 (slow, seconds to minutes).+ tWake := time.Now()+ observeWake := func(source, status string) {+ metrics.WakeDuration.WithLabelValues(s.region, cfg.Template, source, status).Observe(time.Since(tWake).Seconds())+ }+sb, err := s.manager.ForkFromCheckpoint(ctx, req.CheckpointId, cfg)if err == nil {+ observeWake("warm_cache", "success")if s.router != nil {// timeout == 0 means "persistent" (no auto-hibernate).timeout := cfg.Timeout@@ -239,7 +257,9 @@ func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxReqnotInCache := strings.Contains(err.Error(), "not found in cache")if !notInCache {// Some other error (rebase failure, agent reconnect, etc.).- // Don't try to mask it — return the real reason.+ // Don't try to mask it — return the real reason. Attribute as+ // warm_cache failure since we never got to the S3 path.+ observeWake("warm_cache", "failure")return nil, fmt.Errorf("fork from checkpoint %s: %w", req.CheckpointId, err)}if req.TemplateRootfsKey == "" || s.checkpointStore == nil {@@ -251,16 +271,20 @@ func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxReq// symptom Oliviero hit on a checkpoint whose DB row had// empty rootfs_s3_key. Fail loud instead so the customer (and// us) sees an actionable error rather than a corrupt sandbox.+ observeWake("s3", "failure")return nil, fmt.Errorf("fork from checkpoint %s: not in local cache and no S3 key to recover from (DB row may be missing rootfs_s3_key)", req.CheckpointId)}log.Printf("grpc: warm fork %s: not in local cache, downloading from S3", req.CheckpointId)if dlErr := s.downloadFullCheckpoint(ctx, req.CheckpointId, req.TemplateRootfsKey); dlErr != nil {+ observeWake("s3", "failure")return nil, fmt.Errorf("fork from checkpoint %s: cache miss + S3 download failed: %w", req.CheckpointId, dlErr)}sb, retryErr := s.manager.ForkFromCheckpoint(ctx, req.CheckpointId, cfg)if retryErr != nil {+ observeWake("s3", "failure")return nil, fmt.Errorf("fork from checkpoint %s: retry after S3 download failed: %w", req.CheckpointId, retryErr)}+ observeWake("s3", "success")if s.router != nil {timeout := cfg.Timeoutif timeout < 0 {diff --git a/internal/worker/resource_metrics.go b/internal/worker/resource_metrics.gonew file mode 100644index 00000000..891e5e5e--- /dev/null+++ b/internal/worker/resource_metrics.go@@ -0,0 +1,72 @@+package worker++import (+ "context"+ "log"+ "path/filepath"+ "time"++ "github.com/opensandbox/opensandbox/internal/metrics"+)++// MemoryAllocator is the slice of the QEMU manager interface needed to report+// per-worker memory allocation. Duck-typed so this package doesn't depend on+// internal/qemu directly.+type MemoryAllocator interface {+ MemoryAllocatedBytes() uint64+}++// StartResourceMetricsTick runs a goroutine that samples disk, memory, allocated+// memory, and CPU pressure every interval and writes them to the worker-side+// Prometheus gauges. Cancel via the provided context.+//+// dataDir is the worker data directory (e.g. /data/sandboxes) — its mountpoint+// is what the disk gauges report on. mount is just the label value, defaulted+// to filepath.Clean(dataDir).+//+// allocator may be nil (e.g. on a non-QEMU backend); allocated-memory gauge is+// then left unwritten.+func StartResourceMetricsTick(ctx context.Context, allocator MemoryAllocator, region, workerID, dataDir string, interval time.Duration) {+ if interval <= 0 {+ interval = 30 * time.Second+ }+ mount := filepath.Clean(dataDir)+ go func() {+ // Emit one sample immediately so the gauges aren't reported empty for+ // the first interval after worker boot.+ collectAndPublish(allocator, region, workerID, dataDir, mount)+ t := time.NewTicker(interval)+ defer t.Stop()+ for {+ select {+ case <-ctx.Done():+ return+ case <-t.C:+ collectAndPublish(allocator, region, workerID, dataDir, mount)+ }+ }+ }()+ log.Printf("opensandbox-worker: resource-stats tick started (interval=%s, mount=%s)", interval, mount)+}++func collectAndPublish(allocator MemoryAllocator, region, workerID, dataDir, mount string) {+ if total, used, avail, err := DiskBytes(dataDir); err == nil {+ metrics.WorkerDiskTotalBytes.WithLabelValues(region, workerID, mount).Set(float64(total))+ metrics.WorkerDiskUsedBytes.WithLabelValues(region, workerID, mount).Set(float64(used))+ metrics.WorkerDiskAvailableBytes.WithLabelValues(region, workerID, mount).Set(float64(avail))+ }++ if total, avail, err := MemoryBytes(); err == nil && total > 0 {+ metrics.WorkerMemoryTotalBytes.WithLabelValues(region, workerID).Set(float64(total))+ metrics.WorkerMemoryAvailableBytes.WithLabelValues(region, workerID).Set(float64(avail))+ }++ if allocator != nil {+ metrics.WorkerMemoryAllocatedBytes.WithLabelValues(region, workerID).Set(float64(allocator.MemoryAllocatedBytes()))+ }++ psi := ReadCPUPressure()+ metrics.WorkerCPUPressure.WithLabelValues(region, workerID, "avg10", psi.Source).Set(psi.Avg10)+ metrics.WorkerCPUPressure.WithLabelValues(region, workerID, "avg60", psi.Source).Set(psi.Avg60)+ metrics.WorkerCPUPressure.WithLabelValues(region, workerID, "avg300", psi.Source).Set(psi.Avg300)+}diff --git a/internal/worker/stats.go b/internal/worker/stats.goindex 4131c72c..473ae7a1 100644--- a/internal/worker/stats.go+++ b/internal/worker/stats.go@@ -147,3 +147,154 @@ func diskPercent() float64 {}return float64(total-free) / float64(total) * 100.0}++// DiskBytes returns total / used / available bytes for the filesystem+// containing path. Used for the per-worker disk metrics.+// Available uses Bavail (free to non-privileged users) rather than Bfree —+// matches what `df` reports and is the number that actually constrains us.+func DiskBytes(path string) (total, used, available uint64, err error) {+ var stat syscall.Statfs_t+ if err = syscall.Statfs(path, &stat); err != nil {+ return 0, 0, 0, err+ }+ total = stat.Blocks * uint64(stat.Bsize)+ available = stat.Bavail * uint64(stat.Bsize)+ if free := stat.Bfree * uint64(stat.Bsize); total >= free {+ used = total - free+ }+ return total, used, available, nil+}++// MemoryBytes returns total and available bytes on Linux from /proc/meminfo.+// Returns (0, 0, nil) on non-Linux platforms so callers can skip the metric+// without treating it as an error.+func MemoryBytes() (total, available uint64, err error) {+ if runtime.GOOS != "linux" {+ return 0, 0, nil+ }+ f, err := os.Open("/proc/meminfo")+ if err != nil {+ return 0, 0, err+ }+ defer f.Close()+ scanner := bufio.NewScanner(f)+ for scanner.Scan() {+ line := scanner.Text()+ switch {+ case strings.HasPrefix(line, "MemTotal:"):+ total = parseMeminfoKB(line) * 1024+ case strings.HasPrefix(line, "MemAvailable:"):+ available = parseMeminfoKB(line) * 1024+ }+ if total > 0 && available > 0 {+ break+ }+ }+ return total, available, nil+}++// CPUPressure reports stall percentages for the host CPU across three+// rolling windows (avg10, avg60, avg300).+//+// On modern Linux kernels (4.20+) with CONFIG_PSI enabled, source="psi" and+// values come from /proc/pressure/cpu's "some" line — percent of wall time+// during which at least one task was stalled on CPU. This is the right CPU+// pressure signal: it captures CPU saturation independent of utilization+// (a worker at 95% CPU with 0% PSI is fine; one at 60% with rising PSI is+// already in trouble).+//+// On older kernels or non-Linux dev hosts the fallback is source="loadavg":+// /proc/loadavg's 1/5/15-minute values divided by nproc and scaled to a+// percent. Different semantics — loadavg measures runqueue depth, not stall+// time — but it's the same 0..100+ scale and dashboards can flag the source+// label to interpret accordingly.+type CPUPressure struct {+ Avg10, Avg60, Avg300 float64+ Source string // "psi" or "loadavg"+}++func ReadCPUPressure() CPUPressure {+ if runtime.GOOS == "linux" {+ if p, ok := readPSI("/proc/pressure/cpu"); ok {+ p.Source = "psi"+ return p+ }+ }+ return readLoadavgFallback()+}++// readPSI parses /proc/pressure/cpu format:+//+// some avg10=0.00 avg60=0.00 avg300=0.00 total=...+// full avg10=...+//+// We use the "some" line — "full" doesn't apply to CPU pressure anyway+// (it's always 0 for CPU, only meaningful for memory/io).+func readPSI(path string) (CPUPressure, bool) {+ f, err := os.Open(path)+ if err != nil {+ return CPUPressure{}, false+ }+ defer f.Close()+ scanner := bufio.NewScanner(f)+ for scanner.Scan() {+ line := scanner.Text()+ if !strings.HasPrefix(line, "some ") {+ continue+ }+ var p CPUPressure+ for _, field := range strings.Fields(line)[1:] {+ kv := strings.SplitN(field, "=", 2)+ if len(kv) != 2 {+ continue+ }+ v, err := strconv.ParseFloat(kv[1], 64)+ if err != nil {+ continue+ }+ switch kv[0] {+ case "avg10":+ p.Avg10 = v+ case "avg60":+ p.Avg60 = v+ case "avg300":+ p.Avg300 = v+ }+ }+ return p, true+ }+ return CPUPressure{}, false+}++// readLoadavgFallback reads /proc/loadavg (Linux) or returns zero on macOS.+// Scales by 100/nproc so values are roughly comparable to PSI percent+// (loadavg == nproc → ~100%).+func readLoadavgFallback() CPUPressure {+ p := CPUPressure{Source: "loadavg"}+ if runtime.GOOS != "linux" {+ return p+ }+ data, err := os.ReadFile("/proc/loadavg")+ if err != nil {+ return p+ }+ fields := strings.Fields(string(data))+ if len(fields) < 3 {+ return p+ }+ nproc := float64(runtime.NumCPU())+ if nproc < 1 {+ nproc = 1+ }+ parse := func(s string) float64 {+ v, _ := strconv.ParseFloat(s, 64)+ return v / nproc * 100.0+ }+ // /proc/loadavg windows: 1min, 5min, 15min. Map onto avg10/avg60/avg300+ // purely so the same label set works — the windows aren't equivalent but+ // the source="loadavg" label tells dashboards not to mix them with PSI.+ p.Avg10 = parse(fields[0])+ p.Avg60 = parse(fields[1])+ p.Avg300 = parse(fields[2])+ return p+}