An open-source, faster Devin alternative
TypeScript
telemetry: fix cloud-init race + wire 3 unset dashboard gauges (#249)
Mohamed Habibad95b448a8b3
diff --git a/cmd/worker/main.go b/cmd/worker/main.goindex b41b6715..bf0747c5 100644--- a/cmd/worker/main.go+++ b/cmd/worker/main.go@@ -504,10 +504,12 @@ func main() {// memory (sum of MemoryMB across running VMs), CPU pressure (PSI 'some'// avg10/avg60/avg300, or loadavg/nproc fallback).var allocator worker.MemoryAllocator+ var sbCounter worker.SandboxCounterif qemuMgr != nil {allocator = qemuMgr+ sbCounter = qemuMgr}- worker.StartResourceMetricsTick(ctx, allocator, cfg.Region, cfg.WorkerID, cfg.DataDir, 30*time.Second)+ worker.StartResourceMetricsTick(ctx, allocator, sbCounter, 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)diff --git a/deploy/vector/populate-vector-env.service b/deploy/vector/populate-vector-env.serviceindex 56a3b6ff..6cab5bf3 100644--- a/deploy/vector/populate-vector-env.service+++ b/deploy/vector/populate-vector-env.service@@ -7,11 +7,20 @@# 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.+#+# Ordering note: on Azure workers, cloud-init's final stage writes+# /etc/opensandbox/worker.env from a base64 payload baked by the control+# plane (internal/compute/azure.go). Without `After=cloud-final.service`+# the populator races cloud-init, reads an empty environ, exits 0 on+# the "OPENSANDBOX_AZURE_KEY_VAULT_NAME not set" branch, and never+# retries (Restart=on-failure doesn't fire on exit 0). Vector then can't+# start because vector.env was never written. Ordering after cloud-final+# guarantees worker.env exists by the time we read it.[Unit]Description=Populate /etc/opensandbox/vector.env from Key Vault-After=network-online.target-Wants=network-online.target+After=network-online.target cloud-final.service+Wants=network-online.target cloud-final.serviceBefore=vector.serviceDefaultDependencies=no# Retry budget for the Restart= below. StartLimit* belongs in [Unit] perdiff --git a/internal/auth/oauth_handlers.go b/internal/auth/oauth_handlers.goindex e906ea2c..19d82668 100644--- a/internal/auth/oauth_handlers.go+++ b/internal/auth/oauth_handlers.go@@ -10,8 +10,17 @@ import ("github.com/google/uuid""github.com/labstack/echo/v4""github.com/workos/workos-go/v4/pkg/usermanagement"++ "github.com/opensandbox/opensandbox/internal/metrics")+// authType label values for opensandbox_auth_attempts_total. The type+// column groups by entry point (WorkOS callback today; add more on demand).+// Result is the binary outcome — success when the session cookie is set,+// failure for any earlier error return. Sub-reasons live in logs, not in+// metric labels, to keep label cardinality bounded.+const authTypeWorkOS = "workos"+// OAuthHandlers provides HTTP handlers for WorkOS OAuth flow.type OAuthHandlers struct {workos *WorkOSMiddleware@@ -64,6 +73,7 @@ func (h *OAuthHandlers) HandleCallback(c echo.Context) error {state := c.QueryParam("state")if code == "" {+ metrics.AuthAttemptsTotal.WithLabelValues(authTypeWorkOS, "failure").Inc()return c.JSON(http.StatusBadRequest, map[string]string{"error": "missing authorization code",})@@ -75,6 +85,7 @@ func (h *OAuthHandlers) HandleCallback(c echo.Context) error {if err == nil {// Cookie exists — verify it matches (normal login flow)if stateCookie.Value != state {+ metrics.AuthAttemptsTotal.WithLabelValues(authTypeWorkOS, "failure").Inc()return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid state parameter",})@@ -98,6 +109,7 @@ func (h *OAuthHandlers) HandleCallback(c echo.Context) error {Code: code,})if err != nil {+ metrics.AuthAttemptsTotal.WithLabelValues(authTypeWorkOS, "failure").Inc()log.Printf("workos: callback authentication failed: %v", err)return c.JSON(http.StatusUnauthorized, map[string]string{"error": "authentication failed",@@ -118,6 +130,7 @@ func (h *OAuthHandlers) HandleCallback(c echo.Context) error {orgName := authResult.User.EmaillocalUser, err := h.workos.ProvisionOrgAndUser(ctx, authResult.User.Email, name, orgName, authResult.User.ID, authResult.OrganizationID)if err != nil {+ metrics.AuthAttemptsTotal.WithLabelValues(authTypeWorkOS, "failure").Inc()log.Printf("workos: provisioning failed: %v", err)return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to provision user",@@ -142,6 +155,8 @@ func (h *OAuthHandlers) HandleCallback(c echo.Context) error {SameSite: http.SameSiteLaxMode,})+ metrics.AuthAttemptsTotal.WithLabelValues(authTypeWorkOS, "success").Inc()+// Redirect to dashboard after loginreturn c.Redirect(http.StatusFound, "/")}diff --git a/internal/controlplane/redis_registry.go b/internal/controlplane/redis_registry.goindex 35b1eda3..c028bc74 100644--- a/internal/controlplane/redis_registry.go+++ b/internal/controlplane/redis_registry.go@@ -14,6 +14,7 @@ import ("google.golang.org/grpc/keepalive""github.com/opensandbox/opensandbox/internal/grpctls"+ "github.com/opensandbox/opensandbox/internal/metrics"pb "github.com/opensandbox/opensandbox/proto/worker")@@ -271,6 +272,24 @@ func (r *RedisWorkerRegistry) reconcileAndPrune() {}}}++ // Publish the opensandbox_workers_total gauge, keyed by (region, status).+ // Reset first so a region that drained to zero stops reporting its last+ // non-zero value forever; only the (region, status) combos still observed+ // in r.workers will emit a time series on this tick.+ metrics.WorkersTotal.Reset()+ type key struct{ region, status string }+ counts := make(map[key]int)+ for _, w := range r.workers {+ status := "active"+ if w.Draining {+ status = "draining"+ }+ counts[key{w.Region, status}]+++ }+ for k, n := range counts {+ metrics.WorkersTotal.WithLabelValues(k.region, k.status).Set(float64(n))+ }}// handleHeartbeat updates the in-memory worker map and dials gRPC if this is a new worker.diff --git a/internal/qemu/manager.go b/internal/qemu/manager.goindex 877c93d8..45e1f564 100644--- a/internal/qemu/manager.go+++ b/internal/qemu/manager.go@@ -435,6 +435,22 @@ func (m *Manager) MemoryAllocatedBytes() uint64 {return total}+// ActiveSandboxesByTemplate returns the count of currently-running sandboxes+// grouped by template. Drives the opensandbox_sandboxes_active gauge from+// the worker's resource-stats tick.+func (m *Manager) ActiveSandboxesByTemplate() map[string]int {+ m.mu.RLock()+ defer m.mu.RUnlock()+ counts := make(map[string]int)+ for _, vm := range m.vms {+ if vm == nil {+ continue+ }+ counts[vm.Template]+++ }+ return counts+}+// 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 bediff --git a/internal/worker/resource_metrics.go b/internal/worker/resource_metrics.goindex 891e5e5e..e1369505 100644--- a/internal/worker/resource_metrics.go+++ b/internal/worker/resource_metrics.go@@ -16,17 +16,24 @@ type MemoryAllocator interface {MemoryAllocatedBytes() uint64}+// SandboxCounter reports the count of currently-active sandboxes grouped by+// template, used to drive the opensandbox_sandboxes_active gauge.+type SandboxCounter interface {+ ActiveSandboxesByTemplate() map[string]int+}+// 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.+// memory, CPU pressure, and active-sandbox count 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+// allocator may be nil (non-QEMU backend); allocated-memory gauge is then left+// unwritten. counter may be nil for the same reason; sandboxes_active gauge is// then left unwritten.-func StartResourceMetricsTick(ctx context.Context, allocator MemoryAllocator, region, workerID, dataDir string, interval time.Duration) {+func StartResourceMetricsTick(ctx context.Context, allocator MemoryAllocator, counter SandboxCounter, region, workerID, dataDir string, interval time.Duration) {if interval <= 0 {interval = 30 * time.Second}@@ -34,7 +41,7 @@ func StartResourceMetricsTick(ctx context.Context, allocator MemoryAllocator, rego 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)+ collectAndPublish(allocator, counter, region, workerID, dataDir, mount)t := time.NewTicker(interval)defer t.Stop()for {@@ -42,14 +49,14 @@ func StartResourceMetricsTick(ctx context.Context, allocator MemoryAllocator, recase <-ctx.Done():returncase <-t.C:- collectAndPublish(allocator, region, workerID, dataDir, mount)+ collectAndPublish(allocator, counter, 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) {+func collectAndPublish(allocator MemoryAllocator, counter SandboxCounter, 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))@@ -69,4 +76,23 @@ func collectAndPublish(allocator MemoryAllocator, region, workerID, dataDir, moumetrics.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)++ if counter != nil {+ // Reset clears stale template label combos (sandbox stopped → its+ // template would otherwise stay at its last value forever). The+ // Reset/re-emit window is sub-microsecond and Vector scrapes on a+ // 15-30s cadence, so the race is negligible.+ metrics.SandboxesActive.Reset()+ counts := counter.ActiveSandboxesByTemplate()+ if len(counts) == 0 {+ // Heartbeat so the dashboard query has at least one row to+ // summarize on (otherwise APL trips on the by-tags.worker_id+ // group-by with "field not found").+ metrics.SandboxesActive.WithLabelValues(region, workerID, "").Set(0)+ } else {+ for tmpl, n := range counts {+ metrics.SandboxesActive.WithLabelValues(region, workerID, tmpl).Set(float64(n))+ }+ }+ }}