An open-source, faster Devin alternative
TypeScript
reap orphaned Azure disks + stray qemu processes
Brian Reardon98045b083b89
diff --git a/cmd/worker/main.go b/cmd/worker/main.goindex dc4880c3..5838a0cf 100644--- a/cmd/worker/main.go+++ b/cmd/worker/main.go@@ -657,6 +657,16 @@ func main() {}worker.StartResourceMetricsTick(ctx, allocator, sbCounter, cfg.Region, cfg.WorkerID, cfg.DataDir, 30*time.Second)+ // Reap stray qemu processes for sandboxes the control plane no longer places+ // here (abandoned live-migration targets). Worker-side + cell-PG-aware so it+ // kills only leftovers, without emitting a lifecycle event for a box that+ // lives (hibernated) on another worker.+ if qemuMgr != nil && store != nil {+ observability.Go("foreign-vm-reaper", func() {+ worker.StartForeignVMReaper(ctx, qemuMgr, store, cfg.WorkerID, 5*time.Minute)+ })+ }+// 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).diff --git a/internal/compute/azure.go b/internal/compute/azure.goindex d63b9390..4bbe7fa4 100644--- a/internal/compute/azure.go+++ b/internal/compute/azure.go@@ -308,31 +308,40 @@ func (p *AzurePool) DestroyMachine(ctx context.Context, machineID string) error}}- // Delete VM+ // Delete VM. A poll timeout here is common for large VMs — the async delete+ // usually still completes ("natural expiry") — so do NOT return early on it:+ // fall through to best-effort NIC + disk cleanup. Returning early was the+ // primary source of orphaned OS disks (a timed-out VM delete stranded its+ // disk forever, since the disk-cleanup loop below was never reached). The+ // standalone orphan-disk reaper in CleanupOrphanedResources is the backstop+ // for a disk still attached (detaching) when this runs.+ var vmDelErr errorvmPoller, err := p.vmClient.BeginDelete(ctx, p.cfg.ResourceGroup, machineID, nil)if err != nil {- return fmt.Errorf("azure: delete VM %s failed: %w", machineID, err)- }- if _, err := vmPoller.PollUntilDone(ctx, nil); err != nil {- return fmt.Errorf("azure: delete VM %s poll failed: %w", machineID, err)+ vmDelErr = fmt.Errorf("azure: delete VM %s failed: %w", machineID, err)+ } else if _, err := vmPoller.PollUntilDone(ctx, nil); err != nil {+ vmDelErr = fmt.Errorf("azure: delete VM %s poll failed: %w", machineID, err)+ log.Printf("%v — proceeding with best-effort NIC/disk cleanup", vmDelErr)}- // Clean up NIC+ // Clean up NIC (best-effort)nicName := machineID + "-nic"- nicPoller, err := p.nicClient.BeginDelete(ctx, p.cfg.ResourceGroup, nicName, nil)- if err == nil {+ if nicPoller, nerr := p.nicClient.BeginDelete(ctx, p.cfg.ResourceGroup, nicName, nil); nerr == nil {nicPoller.PollUntilDone(ctx, nil)}- // Clean up disks+ // Clean up disks (best-effort). If the VM delete only timed out and the disk+ // is still detaching, this fails and the disk-orphan reaper collects it later.for _, diskName := range diskNames {- diskPoller, err := p.diskClient.BeginDelete(ctx, p.cfg.ResourceGroup, diskName, nil)- if err == nil {+ if diskPoller, derr := p.diskClient.BeginDelete(ctx, p.cfg.ResourceGroup, diskName, nil); derr == nil {diskPoller.PollUntilDone(ctx, nil)log.Printf("azure: deleted disk %s", diskName)}}+ if vmDelErr != nil {+ return vmDelErr+ }log.Printf("azure: VM %s destroyed (+ %d disks + NIC)", machineID, len(diskNames))return nil}@@ -436,10 +445,11 @@ func (p *AzurePool) CleanupOrphanedResources(_ context.Context) (int, error) {ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)defer cancel()- var orphaned []string- pager := p.nicClient.NewListPager(p.cfg.ResourceGroup, nil)- for pager.More() {- page, err := pager.NextPage(ctx)+ // Orphaned NICs: osb-worker-* NICs with no VM attached.+ var orphanedNICs []string+ nicPager := p.nicClient.NewListPager(p.cfg.ResourceGroup, nil)+ for nicPager.More() {+ page, err := nicPager.NextPage(ctx)if err != nil {return 0, fmt.Errorf("azure: list NICs: %w", err)}@@ -454,22 +464,52 @@ func (p *AzurePool) CleanupOrphanedResources(_ context.Context) (int, error) {if !strings.HasPrefix(name, "osb-worker-") {continue}- orphaned = append(orphaned, name)+ orphanedNICs = append(orphanedNICs, name)}}- if len(orphaned) == 0 {- return 0, nil+ // Orphaned OS disks: Unattached osb-worker-* managed disks. A worker VM's OS+ // disk is left behind whenever DestroyMachine's disk cleanup is skipped (VM-+ // delete poll timeout) and nothing else reaps it, so these accumulate+ // unbounded (observed: ~200 disks / ~6 TB / ~$1k/mo). This is the backstop.+ var orphanedDisks []string+ diskPager := p.diskClient.NewListByResourceGroupPager(p.cfg.ResourceGroup, nil)+ for diskPager.More() {+ page, err := diskPager.NextPage(ctx)+ if err != nil {+ return 0, fmt.Errorf("azure: list disks: %w", err)+ }+ for _, d := range page.Value {+ name := ""+ if d.Name != nil {+ name = *d.Name+ }+ if !strings.HasPrefix(name, "osb-worker-") {+ continue+ }+ // ManagedBy set → still attached to a VM. Skip.+ if d.ManagedBy != nil && *d.ManagedBy != "" {+ continue+ }+ // Belt-and-suspenders: only reap disks Azure reports as Unattached.+ if d.Properties != nil && d.Properties.DiskState != nil && *d.Properties.DiskState != armcompute.DiskStateUnattached {+ continue+ }+ orphanedDisks = append(orphanedDisks, name)+ }}- log.Printf("azure: found %d orphaned NICs, cleaning up in parallel", len(orphaned))+ if len(orphanedNICs) == 0 && len(orphanedDisks) == 0 {+ return 0, nil+ }+ log.Printf("azure: orphan cleanup: %d NICs, %d disks — deleting in parallel", len(orphanedNICs), len(orphanedDisks))var (cleaned int64wg sync.WaitGroupsem = make(chan struct{}, 10))- for _, name := range orphaned {+ for _, name := range orphanedNICs {wg.Add(1)sem <- struct{}{}go func(nicName string) {@@ -487,6 +527,24 @@ func (p *AzurePool) CleanupOrphanedResources(_ context.Context) (int, error) {atomic.AddInt64(&cleaned, 1)}(name)}+ for _, name := range orphanedDisks {+ wg.Add(1)+ sem <- struct{}{}+ go func(diskName string) {+ defer wg.Done()+ defer func() { <-sem }()+ poller, err := p.diskClient.BeginDelete(ctx, p.cfg.ResourceGroup, diskName, nil)+ if err != nil {+ log.Printf("azure: failed to delete orphaned disk %s: %v", diskName, err)+ return+ }+ if _, err := poller.PollUntilDone(ctx, nil); err != nil {+ log.Printf("azure: orphaned disk %s delete poll failed: %v", diskName, err)+ return+ }+ atomic.AddInt64(&cleaned, 1)+ }(name)+ }wg.Wait()return int(cleaned), nildiff --git a/internal/worker/foreign_vm_reaper.go b/internal/worker/foreign_vm_reaper.gonew file mode 100644index 00000000..9ebf0c1e--- /dev/null+++ b/internal/worker/foreign_vm_reaper.go@@ -0,0 +1,123 @@+package worker++import (+ "context"+ "log"+ "time"++ "github.com/opensandbox/opensandbox/internal/db"+ "github.com/opensandbox/opensandbox/pkg/types"+)++// vmReaper is the subset of the qemu manager the foreign-VM reaper needs.+// Kill removes the VM from the manager's map and tears down the qemu process+// WITHOUT emitting the global "stopped" lifecycle event that the gRPC+// DestroySandbox handler fires — critical here, because a stray VM's canonical+// session is owned by another worker (or is deep-hibernated in blob) and must+// not be flipped to stopped in the edge index.+type vmReaper interface {+ List(ctx context.Context) ([]types.Sandbox, error)+ Kill(ctx context.Context, id string) error+}++// foreignReapCap bounds how many VMs one pass may reap. A correct fleet reaps 0;+// a handful is normal churn. A sudden large number means something is wrong+// (PG blip returning bad rows, a mass mis-label) — refuse to act and log, rather+// than nuke the worker's VMs on bad data.+const foreignReapCap = 20++// StartForeignVMReaper periodically destroys qemu processes this worker is still+// running for sandboxes the control plane no longer places here. These leak from+// failed/abandoned live migrations: a target prepares (or completes) an incoming+// VM, the migration is then aborted or the box is re-homed / deep-hibernated+// elsewhere, and the target's qemu is left running. The ghost reaper misses it+// (the process is alive and no longer flagged -incoming), so it lingers ~58MB ++// a slot until the worker restarts. Blocks until ctx is cancelled; run in a+// goroutine. No-op if store is nil.+func StartForeignVMReaper(ctx context.Context, mgr vmReaper, store *db.Store, workerID string, interval time.Duration) {+ if store == nil || mgr == nil || workerID == "" {+ return+ }+ log.Printf("foreign-vm-reaper: started (worker=%s interval=%s)", workerID, interval)+ t := time.NewTicker(interval)+ defer t.Stop()+ for {+ select {+ case <-ctx.Done():+ return+ case <-t.C:+ reapForeignVMsOnce(ctx, mgr, store, workerID)+ }+ }+}++// isStrayVM reports whether a live VM on workerID, whose cell session is+// `session`, is a stray leftover that is safe to reap. Safe cases:+//+// (A) the box's canonical home is a DIFFERENT worker and it is not running or+// migrating — an abandoned migration leftover. status=running is excluded+// so an in-flight incoming migration (worker_id still points at the source)+// is never killed.+// (B) the box is terminal (stopped/error) yet its qemu is still alive on its+// OWNING worker — a local teardown that leaked the process.+//+// Everything else — owned-here-and-live, pooled, paused, deep-hibernated-here,+// or mid-migration — returns false and is left alone.+func isStrayVM(session *db.SandboxSession, workerID string) bool {+ if session == nil || session.MigratingToWorker != "" {+ return false+ }+ foreignHome := session.WorkerID != "" && session.WorkerID != workerID+ terminalHere := session.WorkerID == workerID &&+ (session.Status == "stopped" || session.Status == "error")+ return (foreignHome && session.Status != "running") || terminalHere+}++// reapForeignVMsOnce runs a single reap pass, killing every VM isStrayVM flags.+func reapForeignVMsOnce(ctx context.Context, mgr vmReaper, store *db.Store, workerID string) {+ vms, err := mgr.List(ctx)+ if err != nil {+ log.Printf("foreign-vm-reaper: list failed: %v", err)+ return+ }++ type strayVM struct {+ id string+ home string+ status string+ }+ var strays []strayVM+ for _, vm := range vms {+ session, err := store.GetSandboxSession(ctx, vm.ID)+ if err != nil || session == nil {+ // Lookup error or no row: leave it. Absent-row VMs are handled+ // conservatively (a create race can briefly have a VM before its row+ // is visible); the ghost/stale-incoming reapers cover the rest.+ continue+ }+ if isStrayVM(session, workerID) {+ strays = append(strays, strayVM{vm.ID, session.WorkerID, session.Status})+ }+ }++ if len(strays) == 0 {+ return+ }+ if len(strays) > foreignReapCap {+ log.Printf("foreign-vm-reaper: %d candidate strays exceeds cap %d — refusing to act (suspect bad PG state)", len(strays), foreignReapCap)+ return+ }++ reaped := 0+ for _, s := range strays {+ if err := mgr.Kill(ctx, s.id); err != nil {+ log.Printf("foreign-vm-reaper: kill stray %s (home=%s status=%s) failed: %v", s.id, s.home, s.status, err)+ continue+ }+ log.Printf("foreign-vm-reaper: killed stray VM %s (home=%s status=%s)", s.id, s.home, s.status)+ reaped+++ }+ if reaped > 0 {+ log.Printf("foreign-vm-reaper: reaped %d stray VM(s) on %s", reaped, workerID)+ }+}diff --git a/internal/worker/foreign_vm_reaper_test.go b/internal/worker/foreign_vm_reaper_test.gonew file mode 100644index 00000000..6dbc2dbe--- /dev/null+++ b/internal/worker/foreign_vm_reaper_test.go@@ -0,0 +1,45 @@+package worker++import (+ "testing"++ "github.com/opensandbox/opensandbox/internal/db"+)++func TestIsStrayVM(t *testing.T) {+ const self = "w-azure-osb-worker-self"+ const other = "w-azure-osb-worker-other"++ cases := []struct {+ name string+ session *db.SandboxSession+ want bool+ }{+ // --- legit: never reap ---+ {"running here", &db.SandboxSession{WorkerID: self, Status: "running"}, false},+ {"pooled here", &db.SandboxSession{WorkerID: self, Status: "pooled"}, false},+ {"hibernated (paused) here", &db.SandboxSession{WorkerID: self, Status: "hibernated"}, false},+ {"deep-hibernated here", &db.SandboxSession{WorkerID: self, Status: "hibernated"}, false},+ {"nil session", nil, false},+ {"empty home", &db.SandboxSession{WorkerID: "", Status: "hibernated"}, false},+ // in-flight incoming migration: home still points at source, box running.+ {"incoming migration (foreign home, running)", &db.SandboxSession{WorkerID: other, Status: "running"}, false},+ // mid-migration flag set: never touch, even if it looks foreign.+ {"migrating flag set", &db.SandboxSession{WorkerID: other, Status: "hibernated", MigratingToWorker: self}, false},+ {"migrating flag set, running here", &db.SandboxSession{WorkerID: self, Status: "running", MigratingToWorker: other}, false},++ // --- stray: reap ---+ {"deep-hibernated elsewhere (the observed leak)", &db.SandboxSession{WorkerID: other, Status: "hibernated"}, true},+ {"stopped elsewhere", &db.SandboxSession{WorkerID: other, Status: "stopped"}, true},+ {"pooled but owned elsewhere", &db.SandboxSession{WorkerID: other, Status: "pooled"}, true},+ {"terminal (stopped) here, qemu leaked", &db.SandboxSession{WorkerID: self, Status: "stopped"}, true},+ {"terminal (error) here, qemu leaked", &db.SandboxSession{WorkerID: self, Status: "error"}, true},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ if got := isStrayVM(tc.session, self); got != tc.want {+ t.Errorf("isStrayVM(%+v) = %v, want %v", tc.session, got, tc.want)+ }+ })+ }+}