Skip to content

An open-source, faster Devin alternative

TypeScript

add disk pressure, add goldensnap versioning system

Brian Reardon95c1121e9279
diff --git a/cmd/worker/main.go b/cmd/worker/main.go
index 7bddb976..9dc14b8c 100644
--- a/cmd/worker/main.go
+++ b/cmd/worker/main.go
@@ -287,6 +287,10 @@ func main() {
grpcServer.SetMigrator(migrator)
log.Println("opensandbox-worker: live migration enabled")
}
+ if rebuilder, ok := mgr.(worker.GoldenRebuilder); ok {
+ grpcServer.SetGoldenRebuilder(rebuilder)
+ log.Println("opensandbox-worker: golden snapshot rebuild enabled")
+ }
grpcAddr := ":9090"
log.Printf("opensandbox-worker: starting gRPC server on %s", grpcAddr)
go func() {
@@ -323,6 +327,9 @@ func main() {
if err != nil {
log.Printf("opensandbox-worker: Redis heartbeat not available: %v", err)
} else {
+ if qemuMgr != nil {
+ hb.SetGoldenVersion(qemuMgr.GoldenVersion())
+ }
if envID := os.Getenv("OPENSANDBOX_MACHINE_ID"); envID != "" {
hb.SetMachineID(envID)
log.Printf("opensandbox-worker: machine ID (env): %s", envID)
@@ -333,10 +340,10 @@ func main() {
hb.SetMachineID(hostname)
log.Printf("opensandbox-worker: machine ID (hostname): %s", hostname)
}
- hb.Start(func() (int, int, float64, float64) {
+ hb.Start(func() (int, int, float64, float64, float64) {
count, _ := mgr.Count(context.Background())
- cpuPct, memPct := worker.SystemStats()
- return cfg.MaxCapacity, count, cpuPct, memPct
+ cpuPct, memPct, diskPct := worker.SystemStats()
+ return cfg.MaxCapacity, count, cpuPct, memPct, diskPct
})
defer hb.Stop()
log.Println("opensandbox-worker: Redis heartbeat started")
@@ -350,10 +357,13 @@ func main() {
log.Printf("opensandbox-worker: NATS not available: %v (continuing without event sync)", err)
} else {
pub.Start()
- pub.StartHeartbeat(func() (int, int, float64, float64) {
+ if qemuMgr != nil {
+ pub.SetGoldenVersion(qemuMgr.GoldenVersion())
+ }
+ pub.StartHeartbeat(func() (int, int, float64, float64, float64) {
count, _ := mgr.Count(context.Background())
- cpuPct, memPct := worker.SystemStats()
- return cfg.MaxCapacity, count, cpuPct, memPct
+ cpuPct, memPct, diskPct := worker.SystemStats()
+ return cfg.MaxCapacity, count, cpuPct, memPct, diskPct
})
defer pub.Stop()
log.Println("opensandbox-worker: NATS event publisher started")
diff --git a/internal/controlplane/redis_registry.go b/internal/controlplane/redis_registry.go
index 1e25fb08..ce821cab 100644
--- a/internal/controlplane/redis_registry.go
+++ b/internal/controlplane/redis_registry.go
@@ -29,6 +29,8 @@ type WorkerEntry struct {
Current int `json:"current"`
CPUPct float64 `json:"cpu_pct"`
MemPct float64 `json:"mem_pct"`
+ DiskPct float64 `json:"disk_pct"`
+ GoldenVersion string `json:"golden_version,omitempty"`
}
// RedisWorkerRegistry maintains an in-memory cache of worker state
@@ -199,6 +201,10 @@ func (r *RedisWorkerRegistry) handleHeartbeat(entry WorkerEntry) {
existing.Capacity = entry.Capacity
existing.CPUPct = entry.CPUPct
existing.MemPct = entry.MemPct
+ existing.DiskPct = entry.DiskPct
+ if entry.GoldenVersion != "" {
+ existing.GoldenVersion = entry.GoldenVersion
+ }
if entry.GRPCAddr != "" {
existing.GRPCAddr = entry.GRPCAddr
}
@@ -293,11 +299,11 @@ func (r *RedisWorkerRegistry) GetLeastLoadedWorker(region string) (*WorkerEntry,
continue
}
// Skip workers under heavy resource pressure
- if w.CPUPct > 90 || w.MemPct > 90 {
+ if w.CPUPct > 90 || w.MemPct > 90 || w.DiskPct > 90 {
continue
}
// Score: remaining capacity weighted by resource headroom
- resourceScore := (100.0 - w.CPUPct) / 100.0 * (100.0 - w.MemPct) / 100.0
+ resourceScore := (100.0 - w.CPUPct) / 100.0 * (100.0 - w.MemPct) / 100.0 * (100.0 - w.DiskPct) / 100.0
score := float64(remaining) * resourceScore
if score > bestScore {
best = w
@@ -312,10 +318,10 @@ func (r *RedisWorkerRegistry) GetLeastLoadedWorker(region string) (*WorkerEntry,
if remaining <= 0 {
continue
}
- if w.CPUPct > 90 || w.MemPct > 90 {
+ if w.CPUPct > 90 || w.MemPct > 90 || w.DiskPct > 90 {
continue
}
- resourceScore := (100.0 - w.CPUPct) / 100.0 * (100.0 - w.MemPct) / 100.0
+ resourceScore := (100.0 - w.CPUPct) / 100.0 * (100.0 - w.MemPct) / 100.0 * (100.0 - w.DiskPct) / 100.0
score := float64(remaining) * resourceScore
if score > bestScore {
best = w
@@ -419,6 +425,8 @@ func (r *RedisWorkerRegistry) GetWorkersByRegion(region string) []*WorkerInfo {
Current: w.Current,
CPUPct: w.CPUPct,
MemPct: w.MemPct,
+ DiskPct: w.DiskPct,
+ GoldenVersion: w.GoldenVersion,
})
}
}
@@ -426,7 +434,7 @@ func (r *RedisWorkerRegistry) GetWorkersByRegion(region string) []*WorkerInfo {
}
// RegionResourcePressure returns the maximum CPU and memory usage across all workers in a region (satisfies ScalerRegistry).
-func (r *RedisWorkerRegistry) RegionResourcePressure(region string) (maxCPU, maxMem float64) {
+func (r *RedisWorkerRegistry) RegionResourcePressure(region string) (maxCPU, maxMem, maxDisk float64) {
workers := r.GetWorkersByRegion(region)
for _, w := range workers {
if w.CPUPct > maxCPU {
@@ -435,8 +443,11 @@ func (r *RedisWorkerRegistry) RegionResourcePressure(region string) (maxCPU, max
if w.MemPct > maxMem {
maxMem = w.MemPct
}
+ if w.DiskPct > maxDisk {
+ maxDisk = w.DiskPct
+ }
}
- return maxCPU, maxMem
+ return maxCPU, maxMem, maxDisk
}
// RegionUtilization returns the average utilization for a region (satisfies ScalerRegistry).
diff --git a/internal/controlplane/scaler.go b/internal/controlplane/scaler.go
index a96f6200..59f62375 100644
--- a/internal/controlplane/scaler.go
+++ b/internal/controlplane/scaler.go
@@ -21,12 +21,14 @@ const (
pendingWorkerTTL = 10 * time.Minute // How long to wait for a launched worker to register
// Resource-based scaling thresholds (applied per-worker, trigger on ANY worker exceeding)
- resourceCPUThreshold = 80.0 // Scale up if any worker CPU > 80%
- resourceMemThreshold = 85.0 // Scale up if any worker memory > 85%
+ resourceCPUThreshold = 80.0 // Scale up if any worker CPU > 80%
+ resourceMemThreshold = 85.0 // Scale up if any worker memory > 85%
+ resourceDiskThreshold = 75.0 // Scale up if any worker disk > 75%
// Evacuation thresholds (per-worker, triggers live migration of sandboxes OFF the hot worker)
- evacuationCPUThreshold = 90.0
- evacuationMemThreshold = 90.0
+ evacuationCPUThreshold = 90.0
+ evacuationMemThreshold = 90.0
+ evacuationDiskThreshold = 80.0
evacuationBatchSize = 3 // sandboxes to migrate per eval cycle per worker
evacuationCooldown = 60 * time.Second // per-worker cooldown between evacuation batches
drainTimeout = 5 * time.Minute // max time to drain a worker before force-destroying
@@ -38,7 +40,7 @@ type ScalerRegistry interface {
Regions() []string
GetWorkersByRegion(region string) []*WorkerInfo
RegionUtilization(region string) float64
- RegionResourcePressure(region string) (maxCPU, maxMem float64)
+ RegionResourcePressure(region string) (maxCPU, maxMem, maxDisk float64)
GetWorkerClient(workerID string) (pb.SandboxWorkerClient, error)
}
@@ -172,7 +174,7 @@ func (s *Scaler) evaluate() {
func (s *Scaler) evaluateRegion(ctx context.Context, region string) {
workers := s.registry.GetWorkersByRegion(region)
utilization := s.registry.RegionUtilization(region)
- maxCPU, maxMem := s.registry.RegionResourcePressure(region)
+ maxCPU, maxMem, maxDisk := s.registry.RegionResourcePressure(region)
// Expire stale pending launches
s.expirePending(region)
@@ -199,6 +201,10 @@ func (s *Scaler) evaluateRegion(ctx context.Context, region string) {
needsScaleUp = true
reason = fmt.Sprintf("memory pressure %.1f%% > %.0f%%", maxMem, resourceMemThreshold)
}
+ if !needsScaleUp && maxDisk > resourceDiskThreshold {
+ needsScaleUp = true
+ reason = fmt.Sprintf("disk pressure %.1f%% > %.0f%%", maxDisk, resourceDiskThreshold)
+ }
// Ensure minimum workers are running (pre-provisioned capacity).
// Ignores cooldowns — if we're below minimum, launch immediately.
@@ -241,8 +247,8 @@ func (s *Scaler) evaluateRegion(ctx context.Context, region string) {
return
}
- log.Printf("scaler: region %s %s, scaling up (cpu=%.1f%% mem=%.1f%% util=%.1f%%)",
- region, reason, maxCPU, maxMem, utilization*100)
+ log.Printf("scaler: region %s %s, scaling up (cpu=%.1f%% mem=%.1f%% disk=%.1f%% util=%.1f%%)",
+ region, reason, maxCPU, maxMem, maxDisk, utilization*100)
s.scaleUp(ctx, region)
} else if utilization < scaleDownThreshold && len(workers) > s.minWorkers {
// Phase 4: Scale down via smart drain (live-migrate sandboxes, then destroy)
@@ -321,7 +327,7 @@ func (s *Scaler) expirePending(region string) {
// evacuateHotWorkers live-migrates sandboxes off workers that exceed critical thresholds.
func (s *Scaler) evacuateHotWorkers(_ context.Context, region string, workers []*WorkerInfo) {
for _, w := range workers {
- if w.CPUPct < evacuationCPUThreshold && w.MemPct < evacuationMemThreshold {
+ if w.CPUPct < evacuationCPUThreshold && w.MemPct < evacuationMemThreshold && w.DiskPct < evacuationDiskThreshold {
continue
}
// Skip if already being drained for scale-down
@@ -336,13 +342,13 @@ func (s *Scaler) evacuateHotWorkers(_ context.Context, region string, workers []
// Find target: least-loaded worker that isn't the hot one and isn't draining
target := s.findMigrationTarget(region, w.ID)
if target == nil {
- log.Printf("scaler: worker %s under pressure (cpu=%.1f%% mem=%.1f%%) but no migration target available",
- w.ID, w.CPUPct, w.MemPct)
+ log.Printf("scaler: worker %s under pressure (cpu=%.1f%% mem=%.1f%% disk=%.1f%%) but no migration target available",
+ w.ID, w.CPUPct, w.MemPct, w.DiskPct)
continue
}
- log.Printf("scaler: worker %s under pressure (cpu=%.1f%% mem=%.1f%%), evacuating up to %d sandboxes to %s",
- w.ID, w.CPUPct, w.MemPct, evacuationBatchSize, target.ID)
+ log.Printf("scaler: worker %s under pressure (cpu=%.1f%% mem=%.1f%% disk=%.1f%%), evacuating up to %d sandboxes to %s",
+ w.ID, w.CPUPct, w.MemPct, w.DiskPct, evacuationBatchSize, target.ID)
s.lastEvacuation[w.ID] = time.Now()
go s.evacuateBatch(w.ID, target.ID, evacuationBatchSize)
@@ -362,10 +368,10 @@ func (s *Scaler) findMigrationTarget(region, excludeWorkerID string) *WorkerInfo
continue
}
remaining := w.Capacity - w.Current
- if remaining <= 0 || w.CPUPct > 85 || w.MemPct > 85 {
+ if remaining <= 0 || w.CPUPct > 85 || w.MemPct > 85 || w.DiskPct > 85 {
continue
}
- resourceScore := (100.0 - w.CPUPct) / 100.0 * (100.0 - w.MemPct) / 100.0
+ resourceScore := (100.0 - w.CPUPct) / 100.0 * (100.0 - w.MemPct) / 100.0 * (100.0 - w.DiskPct) / 100.0
score := float64(remaining) * resourceScore
if score > bestScore {
best = w
@@ -565,6 +571,48 @@ func (s *Scaler) destroyDrainedMachine(machineID string) {
}()
}
+// RebuildGoldenAll triggers a golden snapshot rebuild on all workers.
+// Workers rebuild one at a time to avoid fleet-wide disruption.
+// Returns a map of workerID → new golden version (or error string).
+func (s *Scaler) RebuildGoldenAll(ctx context.Context) map[string]string {
+ results := make(map[string]string)
+ for _, region := range s.registry.Regions() {
+ for _, w := range s.registry.GetWorkersByRegion(region) {
+ client, err := s.registry.GetWorkerClient(w.ID)
+ if err != nil {
+ results[w.ID] = fmt.Sprintf("error: %v", err)
+ continue
+ }
+
+ rebuildCtx, cancel := context.WithTimeout(ctx, 10*time.Minute)
+ resp, err := client.RebuildGoldenSnapshot(rebuildCtx, &pb.RebuildGoldenSnapshotRequest{})
+ cancel()
+
+ if err != nil {
+ results[w.ID] = fmt.Sprintf("error: %v", err)
+ log.Printf("scaler: golden rebuild failed for worker %s: %v", w.ID, err)
+ } else {
+ results[w.ID] = resp.NewVersion
+ log.Printf("scaler: golden rebuild complete for worker %s (%s → %s)",
+ w.ID, resp.OldVersion, resp.NewVersion)
+ }
+ }
+ }
+ return results
+}
+
+// getWorkerInfo returns WorkerInfo for a specific worker by searching all regions.
+func (s *Scaler) getWorkerInfo(workerID string) *WorkerInfo {
+ for _, region := range s.registry.Regions() {
+ for _, w := range s.registry.GetWorkersByRegion(region) {
+ if w.ID == workerID {
+ return w
+ }
+ }
+ }
+ return nil
+}
+
// --- Live Migration Orchestration ---
// liveMigrateSandbox performs a full live migration of a sandbox between workers.
@@ -587,17 +635,31 @@ func (s *Scaler) liveMigrateSandbox(ctx context.Context, sandboxID, sourceWorker
t0 := time.Now()
+ // Determine if source and target share the same golden snapshot version.
+ // Same version → upload thin overlay, target rebases to local base image (fast, small).
+ // Different version → flatten rootfs before upload, target uses it as-is (slow, large).
+ sourceWorker := s.getWorkerInfo(sourceWorkerID)
+ targetWorker := s.getWorkerInfo(targetWorkerID)
+ sameGolden := sourceWorker != nil && targetWorker != nil &&
+ sourceWorker.GoldenVersion != "" && sourceWorker.GoldenVersion == targetWorker.GoldenVersion
+ flatten := !sameGolden
+
// Step 1: Pre-copy drives to S3 (source uploads qcow2s)
preCopyCtx, preCopyCancel := context.WithTimeout(ctx, 3*time.Minute)
defer preCopyCancel()
preCopyResp, err := sourceClient.PreCopyDrives(preCopyCtx, &pb.PreCopyDrivesRequest{
- SandboxId: sandboxID,
+ SandboxId: sandboxID,
+ FlattenRootfs: flatten,
})
if err != nil {
return fmt.Errorf("pre-copy drives: %w", err)
}
- log.Printf("scaler: migrate %s: drives pre-copied to S3 (%dms)", sandboxID, time.Since(t0).Milliseconds())
+ migrationMode := "overlay"
+ if flatten {
+ migrationMode = "flatten"
+ }
+ log.Printf("scaler: migrate %s: drives pre-copied to S3 (%dms, mode=%s)", sandboxID, time.Since(t0).Milliseconds(), migrationMode)
// Step 2: Prepare target (downloads from S3, starts QEMU -incoming)
// Get sandbox config from DB for CPU/memory/port
@@ -638,6 +700,7 @@ func (s *Scaler) liveMigrateSandbox(ctx context.Context, sandboxID, sourceWorker
Template: template,
RootfsS3Key: preCopyResp.RootfsKey,
WorkspaceS3Key: preCopyResp.WorkspaceKey,
+ OverlayMode: sameGolden,
})
if err != nil {
return fmt.Errorf("prepare target: %w", err)
diff --git a/internal/controlplane/worker_registry.go b/internal/controlplane/worker_registry.go
index c07520a2..ab216cfe 100644
--- a/internal/controlplane/worker_registry.go
+++ b/internal/controlplane/worker_registry.go
@@ -22,7 +22,9 @@ type WorkerInfo struct {
Current int `json:"current"`
CPUPct float64 `json:"cpu_pct"`
MemPct float64 `json:"mem_pct"`
- LastSeen time.Time `json:"-"`
+ DiskPct float64 `json:"disk_pct"`
+ GoldenVersion string `json:"golden_version,omitempty"`
+ LastSeen time.Time `json:"-"`
MissedBeats int `json:"-"`
}
@@ -125,11 +127,11 @@ func (r *WorkerRegistry) GetLeastLoadedWorker(region string) *WorkerInfo {
continue
}
// Skip workers under heavy resource pressure
- if w.CPUPct > 90 || w.MemPct > 90 {
+ if w.CPUPct > 90 || w.MemPct > 90 || w.DiskPct > 90 {
continue
}
// Score: remaining capacity weighted by resource headroom
- resourceScore := (100.0 - w.CPUPct) / 100.0 * (100.0 - w.MemPct) / 100.0
+ resourceScore := (100.0 - w.CPUPct) / 100.0 * (100.0 - w.MemPct) / 100.0 * (100.0 - w.DiskPct) / 100.0
score := float64(remaining) * resourceScore
if score > bestScore {
best = w
@@ -178,7 +180,7 @@ func (r *WorkerRegistry) RegionUtilization(region string) float64 {
// RegionResourcePressure returns the maximum CPU and memory usage across all workers in a region.
// Used by the scaler to detect resource pressure even when count-based utilization is low.
-func (r *WorkerRegistry) RegionResourcePressure(region string) (maxCPU, maxMem float64) {
+func (r *WorkerRegistry) RegionResourcePressure(region string) (maxCPU, maxMem, maxDisk float64) {
workers := r.GetWorkersByRegion(region)
for _, w := range workers {
if w.CPUPct > maxCPU {
@@ -187,8 +189,11 @@ func (r *WorkerRegistry) RegionResourcePressure(region string) (maxCPU, maxMem f
if w.MemPct > maxMem {
maxMem = w.MemPct
}
+ if w.DiskPct > maxDisk {
+ maxDisk = w.DiskPct
+ }
}
- return maxCPU, maxMem
+ return maxCPU, maxMem, maxDisk
}
// Regions returns all known regions.
@@ -228,6 +233,10 @@ func (r *WorkerRegistry) handleHeartbeat(msg *nats.Msg) {
existing.Capacity = hb.Capacity
existing.CPUPct = hb.CPUPct
existing.MemPct = hb.MemPct
+ existing.DiskPct = hb.DiskPct
+ if hb.GoldenVersion != "" {
+ existing.GoldenVersion = hb.GoldenVersion
+ }
existing.LastSeen = time.Now()
existing.MissedBeats = 0
if hb.GRPCAddr != "" {
diff --git a/internal/qemu/golden_version.go b/internal/qemu/golden_version.go
new file mode 100644
index 00000000..931dc4b3
--- /dev/null
+++ b/internal/qemu/golden_version.go
@@ -0,0 +1,26 @@
+package qemu
+
+import (
+ "crypto/sha256"
+ "fmt"
+ "io"
+ "os"
+)
+
+// computeGoldenVersion computes a version hash for a golden snapshot by hashing
+// the first 1MB of the base image. Two workers with the same base image will
+// produce the same hash. This is fast (1MB read) and sufficient to detect
+// different base images (kernel, OS, packages).
+func computeGoldenVersion(baseImagePath string) (string, error) {
+ f, err := os.Open(baseImagePath)
+ if err != nil {
+ return "", fmt.Errorf("open base image: %w", err)
+ }
+ defer f.Close()
+
+ h := sha256.New()
+ if _, err := io.CopyN(h, f, 1024*1024); err != nil && err != io.EOF {
+ return "", fmt.Errorf("read base image: %w", err)
+ }
+ return fmt.Sprintf("%x", h.Sum(nil))[:16], nil
+}
diff --git a/internal/qemu/manager.go b/internal/qemu/manager.go
index fda67737..706f566f 100644
--- a/internal/qemu/manager.go
+++ b/internal/qemu/manager.go
@@ -57,8 +57,9 @@ type VMInstance struct {
restoring chan struct{}
opMu sync.Mutex // serializes destructive VM ops (checkpoint, restore, hibernate)
archiveDone chan struct{} // closed when async hibernate archive completes (nil if no archive in flight)
- baseMemoryMB int // initial memory passed to -m (before virtio-mem)
- virtioMemRequestedMB int // additional memory via virtio-mem (beyond base)
+ baseMemoryMB int // initial memory passed to -m (before virtio-mem)
+ virtioMemRequestedMB int // additional memory via virtio-mem (beyond base)
+ goldenVersion string // golden version this sandbox was created from (empty if cold-booted)
}
// SandboxMeta is persisted to sandbox-meta.json for recovery after hard kills.
@@ -122,6 +123,7 @@ type Manager struct {
goldenCID uint32 // CID used when the golden snapshot was created
goldenGuestIP string // guest IP baked into the golden snapshot
goldenHostIP string // host IP of the golden subnet (for temp addr on TAP)
+ goldenVersion string // hash of base image — used for overlay-based migration
// Metadata service callbacks (set via SetMetadataCallbacks)
onSandboxReady func(sandboxID, guestIP, template string, startedAt time.Time)
@@ -205,6 +207,12 @@ func (m *Manager) SetSecretsProxy(sp SecretsProxyIntegration) {
m.secretsProxy = sp
}
+// GoldenVersion returns the hash identifying this worker's golden snapshot base image.
+// Empty string means no golden snapshot is available.
+func (m *Manager) GoldenVersion() string {
+ return m.goldenVersion
+}
+
// PrepareGoldenSnapshot boots a temporary VM, waits for the agent, then
// hibernates it to create a reusable snapshot. Subsequent Create() calls
// restore from this snapshot instead of cold-booting, cutting start time
@@ -221,21 +229,49 @@ func (m *Manager) PrepareGoldenSnapshot() error {
os.RemoveAll(goldenDir)
}
- // If golden snapshot already exists, just use it
+ // If golden snapshot already exists, check if the base image has changed
if (fileExists(memFile) || fileExists(memFile+".zst")) && (fileExists(rootfsFile) || fileExists(filepath.Join(goldenDir, "rootfs.ext4"))) {
- m.goldenDir = goldenDir
- // Read saved golden CID + guest IP
- if cidBytes, err := os.ReadFile(filepath.Join(goldenDir, "cid")); err == nil {
- fmt.Sscanf(string(cidBytes), "%d", &m.goldenCID)
+ // Load stored golden version
+ versionFile := filepath.Join(goldenDir, "version")
+ var storedVersion string
+ if vBytes, err := os.ReadFile(versionFile); err == nil {
+ storedVersion = string(vBytes)
}
- if ipBytes, err := os.ReadFile(filepath.Join(goldenDir, "guest_ip")); err == nil {
- m.goldenGuestIP = string(ipBytes)
+
+ // Check if the base image on disk matches the golden snapshot
+ stale := false
+ baseImage, _ := ResolveBaseImage(m.cfg.ImagesDir, "default")
+ if baseImage != "" && storedVersion != "" {
+ if currentHash, err := computeGoldenVersion(baseImage); err == nil && currentHash != storedVersion {
+ log.Printf("qemu: base image changed (golden=%s, disk=%s), rebuilding golden snapshot", storedVersion, currentHash)
+ stale = true
+ }
}
- if ipBytes, err := os.ReadFile(filepath.Join(goldenDir, "host_ip")); err == nil {
- m.goldenHostIP = string(ipBytes)
+
+ if !stale {
+ m.goldenDir = goldenDir
+ m.goldenVersion = storedVersion
+ if cidBytes, err := os.ReadFile(filepath.Join(goldenDir, "cid")); err == nil {
+ fmt.Sscanf(string(cidBytes), "%d", &m.goldenCID)
+ }
+ if ipBytes, err := os.ReadFile(filepath.Join(goldenDir, "guest_ip")); err == nil {
+ m.goldenGuestIP = string(ipBytes)
+ }
+ if ipBytes, err := os.ReadFile(filepath.Join(goldenDir, "host_ip")); err == nil {
+ m.goldenHostIP = string(ipBytes)
+ }
+ if storedVersion == "" && baseImage != "" {
+ if v, err := computeGoldenVersion(baseImage); err == nil {
+ m.goldenVersion = v
+ _ = os.WriteFile(versionFile, []byte(v), 0644)
+ }
+ }
+ log.Printf("qemu: golden snapshot already exists at %s (CID=%d, guestIP=%s, version=%s)", goldenDir, m.goldenCID, m.goldenGuestIP, m.goldenVersion)
+ return nil
}
- log.Printf("qemu: golden snapshot already exists at %s (CID=%d, guestIP=%s)", goldenDir, m.goldenCID, m.goldenGuestIP)
- return nil
+
+ // Stale — remove old golden and fall through to rebuild
+ os.RemoveAll(goldenDir)
}
log.Printf("qemu: preparing golden snapshot...")
@@ -437,6 +473,12 @@ func (m *Manager) PrepareGoldenSnapshot() error {
log.Printf("qemu: golden mem compressed with zstd")
}
+ // Compute and persist golden version hash
+ if v, err := computeGoldenVersion(baseImage); err == nil {
+ m.goldenVersion = v
+ _ = os.WriteFile(filepath.Join(goldenDir, "version"), []byte(v), 0644)
+ }
+
// Remove preparing marker — golden snapshot is complete
os.Remove(preparingMarker)
@@ -447,11 +489,55 @@ func (m *Manager) PrepareGoldenSnapshot() error {
_ = os.WriteFile(filepath.Join(goldenDir, "cid"), []byte(fmt.Sprintf("%d", goldenCID)), 0644)
_ = os.WriteFile(filepath.Join(goldenDir, "guest_ip"), []byte(netCfg.GuestIP), 0644)
_ = os.WriteFile(filepath.Join(goldenDir, "host_ip"), []byte(netCfg.HostIP), 0644)
- log.Printf("qemu: golden snapshot ready (%dms total, mem=%s, CID=%d, guestIP=%s)",
- time.Since(t0).Milliseconds(), memFile, goldenCID, netCfg.GuestIP)
+ log.Printf("qemu: golden snapshot ready (%dms total, mem=%s, CID=%d, guestIP=%s, version=%s)",
+ time.Since(t0).Milliseconds(), memFile, goldenCID, netCfg.GuestIP, m.goldenVersion)
return nil
}
+// RebuildGoldenSnapshot builds a new golden snapshot alongside the old one,
+// then atomically swaps to it. Existing sandboxes keep running on their
+// independent reflink copies — only new sandboxes use the new golden.
+// Returns the old and new golden version strings.
+func (m *Manager) RebuildGoldenSnapshot() (oldVersion, newVersion string, err error) {
+ oldVersion = m.goldenVersion
+ goldenDir := filepath.Join(m.cfg.DataDir, "golden")
+
+ // Build new golden in a staging directory
+ stagingDir := filepath.Join(m.cfg.DataDir, "golden-staging")
+ os.RemoveAll(stagingDir) // clean up any prior failed attempt
+
+ // Temporarily point goldenDir to staging so PrepareGoldenSnapshot builds there
+ oldGoldenDir := m.goldenDir
+ m.goldenDir = ""
+
+ // Rename current golden out of the way so PrepareGoldenSnapshot sees no existing snapshot
+ backupDir := filepath.Join(m.cfg.DataDir, "golden-old")
+ os.RemoveAll(backupDir)
+ if err := os.Rename(goldenDir, backupDir); err != nil && !os.IsNotExist(err) {
+ m.goldenDir = oldGoldenDir
+ return oldVersion, "", fmt.Errorf("backup old golden: %w", err)
+ }
+
+ // Build fresh golden snapshot
+ if err := m.PrepareGoldenSnapshot(); err != nil {
+ // Restore old golden on failure
+ os.RemoveAll(goldenDir)
+ if backupErr := os.Rename(backupDir, goldenDir); backupErr == nil {
+ m.goldenDir = oldGoldenDir
+ m.goldenVersion = oldVersion
+ }
+ return oldVersion, "", fmt.Errorf("rebuild golden: %w", err)
+ }
+
+ newVersion = m.goldenVersion
+
+ // Clean up old golden — sandboxes created from it have independent reflink copies
+ os.RemoveAll(backupDir)
+
+ log.Printf("qemu: golden snapshot rebuilt (old=%s, new=%s)", oldVersion, newVersion)
+ return oldVersion, newVersion, nil
+}
+
// createFromGolden creates a new VM by restoring from the golden snapshot.
// This skips kernel boot entirely — the VM resumes with the agent already running.
// After restore, we patch the network config inside the guest.
@@ -641,6 +727,7 @@ func (m *Manager) createFromGolden(ctx context.Context, cfg types.SandboxConfig,
guestMAC: guestMAC,
guestCID: guestCID,
bootArgs: bootArgs,
+ goldenVersion: m.goldenVersion,
}
// Connect to agent via Unix socket
diff --git a/internal/qemu/migration.go b/internal/qemu/migration.go
index ef823df3..04a5b29b 100644
--- a/internal/qemu/migration.go
+++ b/internal/qemu/migration.go
@@ -8,6 +8,7 @@ import (
"os"
"os/exec"
"path/filepath"
+ "strings"
"sync"
"time"
@@ -135,6 +136,97 @@ func (mc *MigrationCoordinator) MigrateToS3(ctx context.Context, sandboxID strin
return rootfsKey, workspaceKey, nil
}
+// MigrateToS3Flatten is like MigrateToS3 but flattens the rootfs qcow2 overlay
+// before uploading, merging the backing file (base ext4 image) into the qcow2.
+// This makes the uploaded rootfs self-contained for cross-golden-version migration.
+// Uses `qemu-img rebase -b ""` which preserves internal snapshots.
+func (mc *MigrationCoordinator) MigrateToS3Flatten(ctx context.Context, sandboxID string) (rootfsKey, workspaceKey string, err error) {
+ mc.mu.Lock()
+ state := &MigrationState{
+ SandboxID: sandboxID,
+ Phase: "pre-copy-flatten",
+ StartedAt: time.Now(),
+ }
+ mc.migrations[sandboxID] = state
+ mc.mu.Unlock()
+
+ defer func() {
+ mc.mu.Lock()
+ delete(mc.migrations, sandboxID)
+ mc.mu.Unlock()
+ }()
+
+ vm, err := mc.manager.getVM(sandboxID)
+ if err != nil {
+ return "", "", fmt.Errorf("vm not found: %w", err)
+ }
+
+ // Sync guest + reflink-copy drives under opMu
+ vm.opMu.Lock()
+ if vm.agent != nil {
+ syncCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
+ _, _ = vm.agent.Exec(syncCtx, &pb.ExecRequest{Command: "sync", RunAsRoot: true})
+ cancel()
+ }
+
+ sandboxDir := vm.sandboxDir
+ rootfsPath := detectDrivePath(sandboxDir, "rootfs")
+ workspacePath := detectDrivePath(sandboxDir, "workspace")
+
+ stagingDir, stageErr := os.MkdirTemp(mc.manager.cfg.DataDir, "migration-staging-")
+ if stageErr != nil {
+ vm.opMu.Unlock()
+ return "", "", fmt.Errorf("create staging dir: %w", stageErr)
+ }
+
+ stagedRootfs := filepath.Join(stagingDir, filepath.Base(rootfsPath))
+ stagedWorkspace := filepath.Join(stagingDir, filepath.Base(workspacePath))
+ if cpErr := copyFileReflink(rootfsPath, stagedRootfs); cpErr != nil {
+ vm.opMu.Unlock()
+ os.RemoveAll(stagingDir)
+ return "", "", fmt.Errorf("stage rootfs: %w", cpErr)
+ }
+ if cpErr := copyFileReflink(workspacePath, stagedWorkspace); cpErr != nil {
+ vm.opMu.Unlock()
+ os.RemoveAll(stagingDir)
+ return "", "", fmt.Errorf("stage workspace: %w", cpErr)
+ }
+ vm.opMu.Unlock()
+ defer os.RemoveAll(stagingDir)
+
+ // Flatten rootfs: merge backing file into overlay so it's self-contained.
+ // `rebase -b ""` preserves internal savevm snapshots unlike `convert`.
+ rebaseCmd := exec.Command("qemu-img", "rebase", "-b", "", stagedRootfs)
+ if out, err := rebaseCmd.CombinedOutput(); err != nil {
+ return "", "", fmt.Errorf("flatten rootfs: %w (%s)", err, strings.TrimSpace(string(out)))
+ }
+
+ rootfsKey = fmt.Sprintf("migrations/%s/rootfs.qcow2", sandboxID)
+ workspaceKey = fmt.Sprintf("migrations/%s/workspace.qcow2", sandboxID)
+
+ t0 := time.Now()
+
+ state.Phase = "upload-rootfs-flat"
+ rootfsSize, err := mc.uploadFile(ctx, stagedRootfs, rootfsKey)
+ if err != nil {
+ return "", "", fmt.Errorf("upload rootfs: %w", err)
+ }
+
+ state.Phase = "upload-workspace"
+ wsSize, err := mc.uploadFile(ctx, stagedWorkspace, workspaceKey)
+ if err != nil {
+ return "", "", fmt.Errorf("upload workspace: %w", err)
+ }
+
+ log.Printf("qemu: migration pre-copy-flatten %s: rootfs=%.1fMB workspace=%.1fMB (%dms)",
+ sandboxID,
+ float64(rootfsSize)/(1024*1024),
+ float64(wsSize)/(1024*1024),
+ time.Since(t0).Milliseconds())
+
+ return rootfsKey, workspaceKey, nil
+}
+
// LiveMigrate performs a full QEMU live migration to a target worker.
// Prerequisites: target worker has called PrepareIncomingMigration and returned the incoming address.
func (mc *MigrationCoordinator) LiveMigrate(ctx context.Context, sandboxID, incomingAddr string) error {
@@ -383,17 +475,37 @@ func (m *Manager) CompleteIncomingMigration(ctx context.Context, sandboxID strin
}
// PreCopyDrives uploads a sandbox's drives to S3 for cross-worker migration.
-func (m *Manager) PreCopyDrives(ctx context.Context, sandboxID string, checkpointStore *storage.CheckpointStore) (rootfsKey, workspaceKey string, err error) {
+// If flatten is true, the rootfs qcow2 overlay is flattened (backing file merged)
+// before upload, making it self-contained for cross-golden-version migration.
+// Returns the S3 keys and the sandbox's golden version.
+func (m *Manager) PreCopyDrives(ctx context.Context, sandboxID string, checkpointStore *storage.CheckpointStore, flatten bool) (rootfsKey, workspaceKey, goldenVer string, err error) {
+ // Look up golden version from the VM
+ m.mu.RLock()
+ vm, exists := m.vms[sandboxID]
+ if exists {
+ goldenVer = vm.goldenVersion
+ }
+ m.mu.RUnlock()
+
mc := &MigrationCoordinator{
manager: m,
checkpointStore: checkpointStore,
migrations: make(map[string]*MigrationState),
}
- return mc.MigrateToS3(ctx, sandboxID)
+
+ if flatten && goldenVer != "" {
+ // Flatten the rootfs before upload — merge backing file into overlay
+ rootfsKey, workspaceKey, err = mc.MigrateToS3Flatten(ctx, sandboxID)
+ } else {
+ rootfsKey, workspaceKey, err = mc.MigrateToS3(ctx, sandboxID)
+ }
+ return rootfsKey, workspaceKey, goldenVer, err
}
// PrepareIncomingMigrationWithS3 downloads drives from S3 then prepares incoming migration.
-func (m *Manager) PrepareIncomingMigrationWithS3(ctx context.Context, sandboxID, rootfsS3Key, workspaceS3Key string, cpus, memMB, guestPort int, template string, checkpointStore *storage.CheckpointStore) (incomingAddr string, hostPort int, err error) {
+// If overlayMode is true, the rootfs is a thin qcow2 overlay — rebase it to point to
+// the local base image instead of downloading a flattened file.
+func (m *Manager) PrepareIncomingMigrationWithS3(ctx context.Context, sandboxID, rootfsS3Key, workspaceS3Key string, cpus, memMB, guestPort int, template string, checkpointStore *storage.CheckpointStore, overlayMode bool) (incomingAddr string, hostPort int, err error) {
sandboxDir := filepath.Join(m.cfg.DataDir, "sandboxes", sandboxID)
if err := os.MkdirAll(sandboxDir, 0755); err != nil {
return "", 0, fmt.Errorf("mkdir: %w", err)
@@ -405,6 +517,21 @@ func (m *Manager) PrepareIncomingMigrationWithS3(ctx context.Context, sandboxID,
return "", 0, fmt.Errorf("download rootfs from S3: %w", err)
}
+ // In overlay mode, the rootfs is a thin overlay backed by the base ext4 image.
+ // Rebase it to point to this worker's local base image path.
+ if overlayMode {
+ baseImage, resolveErr := ResolveBaseImage(m.cfg.ImagesDir, "default")
+ if resolveErr != nil {
+ return "", 0, fmt.Errorf("resolve base image for overlay rebase: %w", resolveErr)
+ }
+ absBase, _ := filepath.Abs(baseImage)
+ rebaseCmd := exec.Command("qemu-img", "rebase", "-u", "-b", absBase, "-F", "raw", rootfsPath)
+ if out, err := rebaseCmd.CombinedOutput(); err != nil {
+ return "", 0, fmt.Errorf("rebase rootfs to local base: %w (%s)", err, strings.TrimSpace(string(out)))
+ }
+ log.Printf("qemu: migration %s: rootfs rebased to local base image (overlay mode)", sandboxID)
+ }
+
// Download workspace from S3
workspacePath := filepath.Join(sandboxDir, "workspace.qcow2")
if err := downloadS3ToFile(ctx, checkpointStore, workspaceS3Key, workspacePath); err != nil {
diff --git a/internal/qemu/snapshot.go b/internal/qemu/snapshot.go
index 42b91a8f..1ca23ee0 100644
--- a/internal/qemu/snapshot.go
+++ b/internal/qemu/snapshot.go
@@ -33,6 +33,7 @@ type SnapshotMeta struct {
BaseMemoryMB int `json:"baseMemoryMB,omitempty"`
Template string `json:"template"`
GuestPort int `json:"guestPort"`
+ GoldenVersion string `json:"goldenVersion,omitempty"`
SnapshotedAt time.Time `json:"snapshotedAt,omitempty"`
}
@@ -128,6 +129,7 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointSto
BaseMemoryMB: vm.baseMemoryMB,
Template: vm.Template,
GuestPort: vm.GuestPort,
+ GoldenVersion: vm.goldenVersion,
SnapshotedAt: time.Now(),
}
metaJSON, err := json.Marshal(meta)
@@ -190,7 +192,17 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointSto
return nil, fmt.Errorf("copy %s for archive staging: %w", driveFile, err)
}
}
- log.Printf("qemu: hibernate %s: archive staging ready (reflink copies)", sandboxID)
+ // Flatten staged rootfs for S3 portability — the qcow2 overlay references a
+ // local backing file (base ext4 image) that won't exist on other workers.
+ // `qemu-img rebase -b ""` merges backing file data into the overlay, making it
+ // self-contained while preserving internal savevm snapshots (unlike qemu-img convert).
+ stagedRootfs := filepath.Join(archiveDir, rootfsFile)
+ rebaseCmd := exec.Command("qemu-img", "rebase", "-b", "", stagedRootfs)
+ if out, err := rebaseCmd.CombinedOutput(); err != nil {
+ log.Printf("qemu: hibernate %s: rootfs rebase failed (archive may not be portable): %v (%s)",
+ sandboxID, err, strings.TrimSpace(string(out)))
+ }
+ log.Printf("qemu: hibernate %s: archive staging ready", sandboxID)
// Signal channel so destroyVM can wait for archive completion before deleting files.
archiveDone := make(chan struct{})
diff --git a/internal/worker/event_publisher.go b/internal/worker/event_publisher.go
index 812885ee..f97be74e 100644
--- a/internal/worker/event_publisher.go
+++ b/internal/worker/event_publisher.go
@@ -17,9 +17,10 @@ type EventPublisher struct {
js nats.JetStreamContext
sandboxDBs *sandbox.SandboxDBManager
region string
- workerID string
- stop chan struct{}
- wg sync.WaitGroup
+ workerID string
+ goldenVersion string
+ stop chan struct{}
+ wg sync.WaitGroup
}
// NATSEvent is the JSON payload published to NATS.
@@ -98,8 +99,13 @@ func (p *EventPublisher) Stop() {
p.nc.Close()
}
+// SetGoldenVersion sets the golden snapshot version hash for heartbeats.
+func (p *EventPublisher) SetGoldenVersion(v string) {
+ p.goldenVersion = v
+}
+
// PublishHeartbeat sends a worker heartbeat to NATS.
-func (p *EventPublisher) PublishHeartbeat(capacity, current int, cpuPct, memPct float64) {
+func (p *EventPublisher) PublishHeartbeat(capacity, current int, cpuPct, memPct, diskPct float64) {
subject := fmt.Sprintf("workers.heartbeat.%s.%s", p.region, p.workerID)
payload := map[string]interface{}{
"worker_id": p.workerID,
@@ -108,6 +114,8 @@ func (p *EventPublisher) PublishHeartbeat(capacity, current int, cpuPct, memPct
"current": current,
"cpu_pct": cpuPct,
"mem_pct": memPct,
+ "disk_pct": diskPct,
+ "golden_version": p.goldenVersion,
}
data, _ := json.Marshal(payload)
if err := p.nc.Publish(subject, data); err != nil {
@@ -116,7 +124,7 @@ func (p *EventPublisher) PublishHeartbeat(capacity, current int, cpuPct, memPct
}
// StartHeartbeat begins sending heartbeats every 5 seconds.
-func (p *EventPublisher) StartHeartbeat(getStats func() (capacity, current int, cpuPct, memPct float64)) {
+func (p *EventPublisher) StartHeartbeat(getStats func() (capacity, current int, cpuPct, memPct, diskPct float64)) {
p.wg.Add(1)
go func() {
defer p.wg.Done()
@@ -126,8 +134,8 @@ func (p *EventPublisher) StartHeartbeat(getStats func() (capacity, current int,
for {
select {
case <-ticker.C:
- cap, cur, cpu, mem := getStats()
- p.PublishHeartbeat(cap, cur, cpu, mem)
+ cap, cur, cpu, mem, disk := getStats()
+ p.PublishHeartbeat(cap, cur, cpu, mem, disk)
case <-p.stop:
return
}
diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.go
index d859d0a4..ea18db18 100644
--- a/internal/worker/grpc_server.go
+++ b/internal/worker/grpc_server.go
@@ -31,16 +31,23 @@ import (
// LiveMigrator is implemented by VM managers that support live migration (e.g. QEMU).
type LiveMigrator interface {
PrepareIncomingMigration(ctx context.Context, sandboxID, rootfsPath, workspacePath string, cpus, memMB, guestPort int, template string) (incomingAddr string, hostPort int, err error)
- PrepareIncomingMigrationWithS3(ctx context.Context, sandboxID, rootfsS3Key, workspaceS3Key string, cpus, memMB, guestPort int, template string, checkpointStore *storage.CheckpointStore) (incomingAddr string, hostPort int, err error)
- PreCopyDrives(ctx context.Context, sandboxID string, checkpointStore *storage.CheckpointStore) (rootfsKey, workspaceKey string, err error)
+ PrepareIncomingMigrationWithS3(ctx context.Context, sandboxID, rootfsS3Key, workspaceS3Key string, cpus, memMB, guestPort int, template string, checkpointStore *storage.CheckpointStore, overlayMode bool) (incomingAddr string, hostPort int, err error)
+ PreCopyDrives(ctx context.Context, sandboxID string, checkpointStore *storage.CheckpointStore, flatten bool) (rootfsKey, workspaceKey, goldenVersion string, err error)
CompleteIncomingMigration(ctx context.Context, sandboxID string) error
LiveMigrate(ctx context.Context, sandboxID, incomingAddr string) error
}
+// GoldenRebuilder is implemented by VM managers that support golden snapshot rebuild.
+type GoldenRebuilder interface {
+ RebuildGoldenSnapshot() (oldVersion, newVersion string, err error)
+ GoldenVersion() string
+}
+
type GRPCServer struct {
pb.UnimplementedSandboxWorkerServer
manager sandbox.Manager
- migrator LiveMigrator // optional, set if manager supports live migration
+ migrator LiveMigrator // optional, set if manager supports live migration
+ goldenRebuilder GoldenRebuilder // optional, set if manager supports golden rebuild
router *sandbox.SandboxRouter
ptyManager *sandbox.PTYManager
execSessionManager *sandbox.ExecSessionManager
@@ -841,17 +848,23 @@ func (s *GRPCServer) SetMigrator(m LiveMigrator) {
s.migrator = m
}
+// SetGoldenRebuilder sets the golden snapshot rebuild handler.
+func (s *GRPCServer) SetGoldenRebuilder(r GoldenRebuilder) {
+ s.goldenRebuilder = r
+}
+
func (s *GRPCServer) PreCopyDrives(ctx context.Context, req *pb.PreCopyDrivesRequest) (*pb.PreCopyDrivesResponse, error) {
if s.migrator == nil {
return nil, fmt.Errorf("live migration not supported on this worker")
}
- rootfsKey, workspaceKey, err := s.migrator.PreCopyDrives(ctx, req.SandboxId, s.checkpointStore)
+ rootfsKey, workspaceKey, goldenVersion, err := s.migrator.PreCopyDrives(ctx, req.SandboxId, s.checkpointStore, req.FlattenRootfs)
if err != nil {
return nil, fmt.Errorf("pre-copy drives: %w", err)
}
return &pb.PreCopyDrivesResponse{
- RootfsKey: rootfsKey,
- WorkspaceKey: workspaceKey,
+ RootfsKey: rootfsKey,
+ WorkspaceKey: workspaceKey,
+ GoldenVersion: goldenVersion,
}, nil
}
@@ -867,7 +880,7 @@ func (s *GRPCServer) PrepareMigrationIncoming(ctx context.Context, req *pb.Prepa
if req.RootfsS3Key != "" && req.WorkspaceS3Key != "" {
addr, hostPort, err = s.migrator.PrepareIncomingMigrationWithS3(ctx,
req.SandboxId, req.RootfsS3Key, req.WorkspaceS3Key,
- int(req.CpuCount), int(req.MemoryMb), int(req.GuestPort), req.Template, s.checkpointStore)
+ int(req.CpuCount), int(req.MemoryMb), int(req.GuestPort), req.Template, s.checkpointStore, req.OverlayMode)
} else {
addr, hostPort, err = s.migrator.PrepareIncomingMigration(ctx,
req.SandboxId, req.RootfsPath, req.WorkspacePath,
@@ -902,6 +915,20 @@ func (s *GRPCServer) CompleteMigrationIncoming(ctx context.Context, req *pb.Comp
return &pb.CompleteMigrationIncomingResponse{}, nil
}
+func (s *GRPCServer) RebuildGoldenSnapshot(ctx context.Context, req *pb.RebuildGoldenSnapshotRequest) (*pb.RebuildGoldenSnapshotResponse, error) {
+ if s.goldenRebuilder == nil {
+ return nil, fmt.Errorf("golden snapshot rebuild not supported on this worker")
+ }
+ oldVersion, newVersion, err := s.goldenRebuilder.RebuildGoldenSnapshot()
+ if err != nil {
+ return nil, fmt.Errorf("rebuild golden snapshot: %w", err)
+ }
+ return &pb.RebuildGoldenSnapshotResponse{
+ OldVersion: oldVersion,
+ NewVersion: newVersion,
+ }, nil
+}
+
func (s *GRPCServer) GetSandboxStats(ctx context.Context, req *pb.GetSandboxStatsRequest) (*pb.GetSandboxStatsResponse, error) {
stats, err := s.manager.Stats(ctx, req.SandboxId)
if err != nil {
diff --git a/internal/worker/redis_heartbeat.go b/internal/worker/redis_heartbeat.go
index 65be7e66..c2f1bfed 100644
--- a/internal/worker/redis_heartbeat.go
+++ b/internal/worker/redis_heartbeat.go
@@ -21,6 +21,8 @@ type redisHeartbeatPayload struct {
Current int `json:"current"`
CPUPct float64 `json:"cpu_pct"`
MemPct float64 `json:"mem_pct"`
+ DiskPct float64 `json:"disk_pct"`
+ GoldenVersion string `json:"golden_version,omitempty"`
}
// RedisHeartbeat publishes periodic heartbeats to Redis for worker discovery.
@@ -34,8 +36,9 @@ type RedisHeartbeat struct {
region string
grpcAddr string
httpAddr string
- getStats func() (capacity, current int, cpuPct, memPct float64)
- stop chan struct{}
+ getStats func() (capacity, current int, cpuPct, memPct, diskPct float64)
+ goldenVersion string
+ stop chan struct{}
}
// NewRedisHeartbeat creates a new heartbeat publisher.
@@ -69,8 +72,13 @@ func (h *RedisHeartbeat) SetMachineID(id string) {
h.machineID = id
}
+// SetGoldenVersion sets the golden snapshot version hash for the heartbeat.
+func (h *RedisHeartbeat) SetGoldenVersion(v string) {
+ h.goldenVersion = v
+}
+
// Start begins publishing heartbeats every 10 seconds.
-func (h *RedisHeartbeat) Start(getStats func() (int, int, float64, float64)) {
+func (h *RedisHeartbeat) Start(getStats func() (int, int, float64, float64, float64)) {
h.getStats = getStats
go func() {
@@ -92,7 +100,7 @@ func (h *RedisHeartbeat) Start(getStats func() (int, int, float64, float64)) {
}
func (h *RedisHeartbeat) publish() {
- capacity, current, cpuPct, memPct := h.getStats()
+ capacity, current, cpuPct, memPct, diskPct := h.getStats()
payload := redisHeartbeatPayload{
WorkerID: h.workerID,
@@ -104,6 +112,8 @@ func (h *RedisHeartbeat) publish() {
Current: current,
CPUPct: cpuPct,
MemPct: memPct,
+ DiskPct: diskPct,
+ GoldenVersion: h.goldenVersion,
}
data, err := json.Marshal(payload)
diff --git a/internal/worker/stats.go b/internal/worker/stats.go
index 61c59657..4131c72c 100644
--- a/internal/worker/stats.go
+++ b/internal/worker/stats.go
@@ -7,17 +7,20 @@ import (
"strconv"
"strings"
"sync"
+ "syscall"
"time"
)
-// SystemStats returns current CPU and memory usage percentages.
+// SystemStats returns current CPU, memory, and disk usage percentages.
// On Linux, reads from /proc. On other platforms, returns 0.0 gracefully.
-func SystemStats() (cpuPct, memPct float64) {
+// Disk usage uses syscall.Statfs which works on both Linux and macOS.
+func SystemStats() (cpuPct, memPct, diskPct float64) {
if runtime.GOOS == "linux" {
memPct = linuxMemoryPercent()
cpuPct = linuxCPUPercent()
}
- return cpuPct, memPct
+ diskPct = diskPercent()
+ return cpuPct, memPct, diskPct
}
func linuxMemoryPercent() float64 {
@@ -129,3 +132,18 @@ func readProcStat() (total, idle uint64) {
}
return total, idle
}
+
+// diskPercent returns the disk usage percentage for the root filesystem.
+// Uses syscall.Statfs which works on both Linux and macOS.
+func diskPercent() float64 {
+ var stat syscall.Statfs_t
+ if err := syscall.Statfs("/", &stat); err != nil {
+ return 0.0
+ }
+ total := stat.Blocks * uint64(stat.Bsize)
+ free := stat.Bfree * uint64(stat.Bsize)
+ if total == 0 {
+ return 0.0
+ }
+ return float64(total-free) / float64(total) * 100.0
+}
diff --git a/proto/worker/worker.pb.go b/proto/worker/worker.pb.go
index ff179e05..9a6cbf55 100644
--- a/proto/worker/worker.pb.go
+++ b/proto/worker/worker.pb.go
@@ -2714,6 +2714,7 @@ func (*SetSandboxLimitsResponse) Descriptor() ([]byte, []int) {
type PreCopyDrivesRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`
+ FlattenRootfs bool `protobuf:"varint,2,opt,name=flatten_rootfs,json=flattenRootfs,proto3" json:"flatten_rootfs,omitempty"` // if true, flatten qcow2 overlay before upload (cross-golden-version)
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -2755,10 +2756,18 @@ func (x *PreCopyDrivesRequest) GetSandboxId() string {
return ""
}
+func (x *PreCopyDrivesRequest) GetFlattenRootfs() bool {
+ if x != nil {
+ return x.FlattenRootfs
+ }
+ return false
+}
+
type PreCopyDrivesResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
- RootfsKey string `protobuf:"bytes,1,opt,name=rootfs_key,json=rootfsKey,proto3" json:"rootfs_key,omitempty"` // S3 key for rootfs qcow2
- WorkspaceKey string `protobuf:"bytes,2,opt,name=workspace_key,json=workspaceKey,proto3" json:"workspace_key,omitempty"` // S3 key for workspace qcow2
+ RootfsKey string `protobuf:"bytes,1,opt,name=rootfs_key,json=rootfsKey,proto3" json:"rootfs_key,omitempty"` // S3 key for rootfs qcow2
+ WorkspaceKey string `protobuf:"bytes,2,opt,name=workspace_key,json=workspaceKey,proto3" json:"workspace_key,omitempty"` // S3 key for workspace qcow2
+ GoldenVersion string `protobuf:"bytes,3,opt,name=golden_version,json=goldenVersion,proto3" json:"golden_version,omitempty"` // golden version the sandbox was created from
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -2807,6 +2816,13 @@ func (x *PreCopyDrivesResponse) GetWorkspaceKey() string {
return ""
}
+func (x *PreCopyDrivesResponse) GetGoldenVersion() string {
+ if x != nil {
+ return x.GoldenVersion
+ }
+ return ""
+}
+
type PrepareMigrationIncomingRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`
@@ -2818,6 +2834,7 @@ type PrepareMigrationIncomingRequest struct {
Template string `protobuf:"bytes,7,opt,name=template,proto3" json:"template,omitempty"`
RootfsS3Key string `protobuf:"bytes,8,opt,name=rootfs_s3_key,json=rootfsS3Key,proto3" json:"rootfs_s3_key,omitempty"` // if set, download from S3 instead of using local rootfs_path
WorkspaceS3Key string `protobuf:"bytes,9,opt,name=workspace_s3_key,json=workspaceS3Key,proto3" json:"workspace_s3_key,omitempty"` // if set, download from S3 instead of using local workspace_path
+ OverlayMode bool `protobuf:"varint,10,opt,name=overlay_mode,json=overlayMode,proto3" json:"overlay_mode,omitempty"` // if true, rootfs is thin overlay — rebase to local golden on target
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -2915,6 +2932,13 @@ func (x *PrepareMigrationIncomingRequest) GetWorkspaceS3Key() string {
return ""
}
+func (x *PrepareMigrationIncomingRequest) GetOverlayMode() bool {
+ if x != nil {
+ return x.OverlayMode
+ }
+ return false
+}
+
type PrepareMigrationIncomingResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
IncomingAddr string `protobuf:"bytes,1,opt,name=incoming_addr,json=incomingAddr,proto3" json:"incoming_addr,omitempty"` // TCP address for source to migrate to (e.g. "10.100.1.7:49152")
@@ -3135,6 +3159,95 @@ func (*CompleteMigrationIncomingResponse) Descriptor() ([]byte, []int) {
return file_proto_worker_worker_proto_rawDescGZIP(), []int{53}
}
+// Golden snapshot management
+type RebuildGoldenSnapshotRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *RebuildGoldenSnapshotRequest) Reset() {
+ *x = RebuildGoldenSnapshotRequest{}
+ mi := &file_proto_worker_worker_proto_msgTypes[54]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *RebuildGoldenSnapshotRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*RebuildGoldenSnapshotRequest) ProtoMessage() {}
+
+func (x *RebuildGoldenSnapshotRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_worker_worker_proto_msgTypes[54]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use RebuildGoldenSnapshotRequest.ProtoReflect.Descriptor instead.
+func (*RebuildGoldenSnapshotRequest) Descriptor() ([]byte, []int) {
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{54}
+}
+
+type RebuildGoldenSnapshotResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ OldVersion string `protobuf:"bytes,1,opt,name=old_version,json=oldVersion,proto3" json:"old_version,omitempty"` // previous golden version (empty if none)
+ NewVersion string `protobuf:"bytes,2,opt,name=new_version,json=newVersion,proto3" json:"new_version,omitempty"` // new golden version after rebuild
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *RebuildGoldenSnapshotResponse) Reset() {
+ *x = RebuildGoldenSnapshotResponse{}
+ mi := &file_proto_worker_worker_proto_msgTypes[55]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *RebuildGoldenSnapshotResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*RebuildGoldenSnapshotResponse) ProtoMessage() {}
+
+func (x *RebuildGoldenSnapshotResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_worker_worker_proto_msgTypes[55]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use RebuildGoldenSnapshotResponse.ProtoReflect.Descriptor instead.
+func (*RebuildGoldenSnapshotResponse) Descriptor() ([]byte, []int) {
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{55}
+}
+
+func (x *RebuildGoldenSnapshotResponse) GetOldVersion() string {
+ if x != nil {
+ return x.OldVersion
+ }
+ return ""
+}
+
+func (x *RebuildGoldenSnapshotResponse) GetNewVersion() string {
+ if x != nil {
+ return x.NewVersion
+ }
+ return ""
+}
+
var File_proto_worker_worker_proto protoreflect.FileDescriptor
const file_proto_worker_worker_proto_rawDesc = "" +
@@ -3360,14 +3473,16 @@ const file_proto_worker_worker_proto_rawDesc = "" +
"\fcpu_max_usec\x18\x04 \x01(\x03R\n" +
"cpuMaxUsec\x12&\n" +
"\x0fcpu_period_usec\x18\x05 \x01(\x03R\rcpuPeriodUsec\"\x1a\n" +
- "\x18SetSandboxLimitsResponse\"5\n" +
+ "\x18SetSandboxLimitsResponse\"\\\n" +
"\x14PreCopyDrivesRequest\x12\x1d\n" +
"\n" +
- "sandbox_id\x18\x01 \x01(\tR\tsandboxId\"[\n" +
+ "sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12%\n" +
+ "\x0eflatten_rootfs\x18\x02 \x01(\bR\rflattenRootfs\"\x82\x01\n" +
"\x15PreCopyDrivesResponse\x12\x1d\n" +
"\n" +
"rootfs_key\x18\x01 \x01(\tR\trootfsKey\x12#\n" +
- "\rworkspace_key\x18\x02 \x01(\tR\fworkspaceKey\"\xcb\x02\n" +
+ "\rworkspace_key\x18\x02 \x01(\tR\fworkspaceKey\x12%\n" +
+ "\x0egolden_version\x18\x03 \x01(\tR\rgoldenVersion\"\xee\x02\n" +
"\x1fPrepareMigrationIncomingRequest\x12\x1d\n" +
"\n" +
"sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12\x1f\n" +
@@ -3380,7 +3495,9 @@ const file_proto_worker_worker_proto_rawDesc = "" +
"guest_port\x18\x06 \x01(\x05R\tguestPort\x12\x1a\n" +
"\btemplate\x18\a \x01(\tR\btemplate\x12\"\n" +
"\rrootfs_s3_key\x18\b \x01(\tR\vrootfsS3Key\x12(\n" +
- "\x10workspace_s3_key\x18\t \x01(\tR\x0eworkspaceS3Key\"d\n" +
+ "\x10workspace_s3_key\x18\t \x01(\tR\x0eworkspaceS3Key\x12!\n" +
+ "\foverlay_mode\x18\n" +
+ " \x01(\bR\voverlayMode\"d\n" +
" PrepareMigrationIncomingResponse\x12#\n" +
"\rincoming_addr\x18\x01 \x01(\tR\fincomingAddr\x12\x1b\n" +
"\thost_port\x18\x02 \x01(\x05R\bhostPort\"X\n" +
@@ -3392,7 +3509,13 @@ const file_proto_worker_worker_proto_rawDesc = "" +
" CompleteMigrationIncomingRequest\x12\x1d\n" +
"\n" +
"sandbox_id\x18\x01 \x01(\tR\tsandboxId\"#\n" +
- "!CompleteMigrationIncomingResponse2\x9d\x10\n" +
+ "!CompleteMigrationIncomingResponse\"\x1e\n" +
+ "\x1cRebuildGoldenSnapshotRequest\"a\n" +
+ "\x1dRebuildGoldenSnapshotResponse\x12\x1f\n" +
+ "\vold_version\x18\x01 \x01(\tR\n" +
+ "oldVersion\x12\x1f\n" +
+ "\vnew_version\x18\x02 \x01(\tR\n" +
+ "newVersion2\x83\x11\n" +
"\rSandboxWorker\x12L\n" +
"\rCreateSandbox\x12\x1c.worker.CreateSandboxRequest\x1a\x1d.worker.CreateSandboxResponse\x12O\n" +
"\x0eDestroySandbox\x12\x1d.worker.DestroySandboxRequest\x1a\x1e.worker.DestroySandboxResponse\x12C\n" +
@@ -3420,7 +3543,8 @@ const file_proto_worker_worker_proto_rawDesc = "" +
"\rPreCopyDrives\x12\x1c.worker.PreCopyDrivesRequest\x1a\x1d.worker.PreCopyDrivesResponse\x12m\n" +
"\x18PrepareMigrationIncoming\x12'.worker.PrepareMigrationIncomingRequest\x1a(.worker.PrepareMigrationIncomingResponse\x12F\n" +
"\vLiveMigrate\x12\x1a.worker.LiveMigrateRequest\x1a\x1b.worker.LiveMigrateResponse\x12p\n" +
- "\x19CompleteMigrationIncoming\x12(.worker.CompleteMigrationIncomingRequest\x1a).worker.CompleteMigrationIncomingResponseB1Z/github.com/opensandbox/opensandbox/proto/workerb\x06proto3"
+ "\x19CompleteMigrationIncoming\x12(.worker.CompleteMigrationIncomingRequest\x1a).worker.CompleteMigrationIncomingResponse\x12d\n" +
+ "\x15RebuildGoldenSnapshot\x12$.worker.RebuildGoldenSnapshotRequest\x1a%.worker.RebuildGoldenSnapshotResponseB1Z/github.com/opensandbox/opensandbox/proto/workerb\x06proto3"
var (
file_proto_worker_worker_proto_rawDescOnce sync.Once
@@ -3435,7 +3559,7 @@ func file_proto_worker_worker_proto_rawDescGZIP() []byte {
}
var file_proto_worker_worker_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
-var file_proto_worker_worker_proto_msgTypes = make([]protoimpl.MessageInfo, 58)
+var file_proto_worker_worker_proto_msgTypes = make([]protoimpl.MessageInfo, 60)
var file_proto_worker_worker_proto_goTypes = []any{
(ExecOutputChunk_Stream)(0), // 0: worker.ExecOutputChunk.Stream
(*CreateSandboxRequest)(nil), // 1: worker.CreateSandboxRequest
@@ -3492,20 +3616,22 @@ var file_proto_worker_worker_proto_goTypes = []any{
(*LiveMigrateResponse)(nil), // 52: worker.LiveMigrateResponse
(*CompleteMigrationIncomingRequest)(nil), // 53: worker.CompleteMigrationIncomingRequest
(*CompleteMigrationIncomingResponse)(nil), // 54: worker.CompleteMigrationIncomingResponse
- nil, // 55: worker.CreateSandboxRequest.EnvsEntry
- nil, // 56: worker.CreateSandboxRequest.SecretAllowedHostsEntry
- nil, // 57: worker.ExecCommandRequest.EnvsEntry
- nil, // 58: worker.ExecSessionCreateRequest.EnvsEntry
+ (*RebuildGoldenSnapshotRequest)(nil), // 55: worker.RebuildGoldenSnapshotRequest
+ (*RebuildGoldenSnapshotResponse)(nil), // 56: worker.RebuildGoldenSnapshotResponse
+ nil, // 57: worker.CreateSandboxRequest.EnvsEntry
+ nil, // 58: worker.CreateSandboxRequest.SecretAllowedHostsEntry
+ nil, // 59: worker.ExecCommandRequest.EnvsEntry
+ nil, // 60: worker.ExecSessionCreateRequest.EnvsEntry
}
var file_proto_worker_worker_proto_depIdxs = []int32{
- 55, // 0: worker.CreateSandboxRequest.envs:type_name -> worker.CreateSandboxRequest.EnvsEntry
- 56, // 1: worker.CreateSandboxRequest.secret_allowed_hosts:type_name -> worker.CreateSandboxRequest.SecretAllowedHostsEntry
+ 57, // 0: worker.CreateSandboxRequest.envs:type_name -> worker.CreateSandboxRequest.EnvsEntry
+ 58, // 1: worker.CreateSandboxRequest.secret_allowed_hosts:type_name -> worker.CreateSandboxRequest.SecretAllowedHostsEntry
6, // 2: worker.ListSandboxesResponse.sandboxes:type_name -> worker.GetSandboxResponse
- 57, // 3: worker.ExecCommandRequest.envs:type_name -> worker.ExecCommandRequest.EnvsEntry
+ 59, // 3: worker.ExecCommandRequest.envs:type_name -> worker.ExecCommandRequest.EnvsEntry
0, // 4: worker.ExecOutputChunk.stream:type_name -> worker.ExecOutputChunk.Stream
17, // 5: worker.ListDirResponse.entries:type_name -> worker.DirEntry
22, // 6: worker.PTYInput.resize:type_name -> worker.PTYResize
- 58, // 7: worker.ExecSessionCreateRequest.envs:type_name -> worker.ExecSessionCreateRequest.EnvsEntry
+ 60, // 7: worker.ExecSessionCreateRequest.envs:type_name -> worker.ExecSessionCreateRequest.EnvsEntry
36, // 8: worker.ExecSessionListResponse.sessions:type_name -> worker.ExecSessionInfoEntry
1, // 9: worker.SandboxWorker.CreateSandbox:input_type -> worker.CreateSandboxRequest
3, // 10: worker.SandboxWorker.DestroySandbox:input_type -> worker.DestroySandboxRequest
@@ -3533,34 +3659,36 @@ var file_proto_worker_worker_proto_depIdxs = []int32{
49, // 32: worker.SandboxWorker.PrepareMigrationIncoming:input_type -> worker.PrepareMigrationIncomingRequest
51, // 33: worker.SandboxWorker.LiveMigrate:input_type -> worker.LiveMigrateRequest
53, // 34: worker.SandboxWorker.CompleteMigrationIncoming:input_type -> worker.CompleteMigrationIncomingRequest
- 2, // 35: worker.SandboxWorker.CreateSandbox:output_type -> worker.CreateSandboxResponse
- 4, // 36: worker.SandboxWorker.DestroySandbox:output_type -> worker.DestroySandboxResponse
- 6, // 37: worker.SandboxWorker.GetSandbox:output_type -> worker.GetSandboxResponse
- 8, // 38: worker.SandboxWorker.ListSandboxes:output_type -> worker.ListSandboxesResponse
- 10, // 39: worker.SandboxWorker.ExecCommand:output_type -> worker.ExecCommandResponse
- 11, // 40: worker.SandboxWorker.ExecCommandStream:output_type -> worker.ExecOutputChunk
- 13, // 41: worker.SandboxWorker.ReadFile:output_type -> worker.ReadFileResponse
- 15, // 42: worker.SandboxWorker.WriteFile:output_type -> worker.WriteFileResponse
- 18, // 43: worker.SandboxWorker.ListDir:output_type -> worker.ListDirResponse
- 20, // 44: worker.SandboxWorker.CreatePTY:output_type -> worker.CreatePTYResponse
- 23, // 45: worker.SandboxWorker.PTYStream:output_type -> worker.PTYOutput
- 33, // 46: worker.SandboxWorker.ExecSessionCreate:output_type -> worker.ExecSessionCreateResponse
- 35, // 47: worker.SandboxWorker.ExecSessionList:output_type -> worker.ExecSessionListResponse
- 38, // 48: worker.SandboxWorker.ExecSessionKill:output_type -> worker.ExecSessionKillResponse
- 25, // 49: worker.SandboxWorker.HibernateSandbox:output_type -> worker.HibernateSandboxResponse
- 27, // 50: worker.SandboxWorker.WakeSandbox:output_type -> worker.WakeSandboxResponse
- 29, // 51: worker.SandboxWorker.SaveAsTemplate:output_type -> worker.SaveAsTemplateResponse
- 42, // 52: worker.SandboxWorker.CreateCheckpoint:output_type -> worker.CreateCheckpointResponse
- 44, // 53: worker.SandboxWorker.RestoreCheckpoint:output_type -> worker.RestoreCheckpointResponse
- 31, // 54: worker.SandboxWorker.BuildTemplate:output_type -> worker.BuildTemplateResponse
- 40, // 55: worker.SandboxWorker.GetSandboxStats:output_type -> worker.GetSandboxStatsResponse
- 46, // 56: worker.SandboxWorker.SetSandboxLimits:output_type -> worker.SetSandboxLimitsResponse
- 48, // 57: worker.SandboxWorker.PreCopyDrives:output_type -> worker.PreCopyDrivesResponse
- 50, // 58: worker.SandboxWorker.PrepareMigrationIncoming:output_type -> worker.PrepareMigrationIncomingResponse
- 52, // 59: worker.SandboxWorker.LiveMigrate:output_type -> worker.LiveMigrateResponse
- 54, // 60: worker.SandboxWorker.CompleteMigrationIncoming:output_type -> worker.CompleteMigrationIncomingResponse
- 35, // [35:61] is the sub-list for method output_type
- 9, // [9:35] is the sub-list for method input_type
+ 55, // 35: worker.SandboxWorker.RebuildGoldenSnapshot:input_type -> worker.RebuildGoldenSnapshotRequest
+ 2, // 36: worker.SandboxWorker.CreateSandbox:output_type -> worker.CreateSandboxResponse
+ 4, // 37: worker.SandboxWorker.DestroySandbox:output_type -> worker.DestroySandboxResponse
+ 6, // 38: worker.SandboxWorker.GetSandbox:output_type -> worker.GetSandboxResponse
+ 8, // 39: worker.SandboxWorker.ListSandboxes:output_type -> worker.ListSandboxesResponse
+ 10, // 40: worker.SandboxWorker.ExecCommand:output_type -> worker.ExecCommandResponse
+ 11, // 41: worker.SandboxWorker.ExecCommandStream:output_type -> worker.ExecOutputChunk
+ 13, // 42: worker.SandboxWorker.ReadFile:output_type -> worker.ReadFileResponse
+ 15, // 43: worker.SandboxWorker.WriteFile:output_type -> worker.WriteFileResponse
+ 18, // 44: worker.SandboxWorker.ListDir:output_type -> worker.ListDirResponse
+ 20, // 45: worker.SandboxWorker.CreatePTY:output_type -> worker.CreatePTYResponse
+ 23, // 46: worker.SandboxWorker.PTYStream:output_type -> worker.PTYOutput
+ 33, // 47: worker.SandboxWorker.ExecSessionCreate:output_type -> worker.ExecSessionCreateResponse
+ 35, // 48: worker.SandboxWorker.ExecSessionList:output_type -> worker.ExecSessionListResponse
+ 38, // 49: worker.SandboxWorker.ExecSessionKill:output_type -> worker.ExecSessionKillResponse
+ 25, // 50: worker.SandboxWorker.HibernateSandbox:output_type -> worker.HibernateSandboxResponse
+ 27, // 51: worker.SandboxWorker.WakeSandbox:output_type -> worker.WakeSandboxResponse
+ 29, // 52: worker.SandboxWorker.SaveAsTemplate:output_type -> worker.SaveAsTemplateResponse
+ 42, // 53: worker.SandboxWorker.CreateCheckpoint:output_type -> worker.CreateCheckpointResponse
+ 44, // 54: worker.SandboxWorker.RestoreCheckpoint:output_type -> worker.RestoreCheckpointResponse
+ 31, // 55: worker.SandboxWorker.BuildTemplate:output_type -> worker.BuildTemplateResponse
+ 40, // 56: worker.SandboxWorker.GetSandboxStats:output_type -> worker.GetSandboxStatsResponse
+ 46, // 57: worker.SandboxWorker.SetSandboxLimits:output_type -> worker.SetSandboxLimitsResponse
+ 48, // 58: worker.SandboxWorker.PreCopyDrives:output_type -> worker.PreCopyDrivesResponse
+ 50, // 59: worker.SandboxWorker.PrepareMigrationIncoming:output_type -> worker.PrepareMigrationIncomingResponse
+ 52, // 60: worker.SandboxWorker.LiveMigrate:output_type -> worker.LiveMigrateResponse
+ 54, // 61: worker.SandboxWorker.CompleteMigrationIncoming:output_type -> worker.CompleteMigrationIncomingResponse
+ 56, // 62: worker.SandboxWorker.RebuildGoldenSnapshot:output_type -> worker.RebuildGoldenSnapshotResponse
+ 36, // [36:63] is the sub-list for method output_type
+ 9, // [9:36] is the sub-list for method input_type
9, // [9:9] is the sub-list for extension type_name
9, // [9:9] is the sub-list for extension extendee
0, // [0:9] is the sub-list for field type_name
@@ -3581,7 +3709,7 @@ func file_proto_worker_worker_proto_init() {
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_proto_worker_worker_proto_rawDesc), len(file_proto_worker_worker_proto_rawDesc)),
NumEnums: 1,
- NumMessages: 58,
+ NumMessages: 60,
NumExtensions: 0,
NumServices: 1,
},
diff --git a/proto/worker/worker.proto b/proto/worker/worker.proto
index c777b467..dae422a6 100644
--- a/proto/worker/worker.proto
+++ b/proto/worker/worker.proto
@@ -43,6 +43,9 @@ service SandboxWorker {
rpc PrepareMigrationIncoming(PrepareMigrationIncomingRequest) returns (PrepareMigrationIncomingResponse);
rpc LiveMigrate(LiveMigrateRequest) returns (LiveMigrateResponse);
rpc CompleteMigrationIncoming(CompleteMigrationIncomingRequest) returns (CompleteMigrationIncomingResponse);
+
+ // Golden snapshot management
+ rpc RebuildGoldenSnapshot(RebuildGoldenSnapshotRequest) returns (RebuildGoldenSnapshotResponse);
}
message CreateSandboxRequest {
@@ -315,11 +318,13 @@ message SetSandboxLimitsResponse {}
// Live migration messages
message PreCopyDrivesRequest {
string sandbox_id = 1;
+ bool flatten_rootfs = 2; // if true, flatten qcow2 overlay before upload (cross-golden-version)
}
message PreCopyDrivesResponse {
- string rootfs_key = 1; // S3 key for rootfs qcow2
- string workspace_key = 2; // S3 key for workspace qcow2
+ string rootfs_key = 1; // S3 key for rootfs qcow2
+ string workspace_key = 2; // S3 key for workspace qcow2
+ string golden_version = 3; // golden version the sandbox was created from
}
message PrepareMigrationIncomingRequest {
@@ -332,6 +337,7 @@ message PrepareMigrationIncomingRequest {
string template = 7;
string rootfs_s3_key = 8; // if set, download from S3 instead of using local rootfs_path
string workspace_s3_key = 9; // if set, download from S3 instead of using local workspace_path
+ bool overlay_mode = 10; // if true, rootfs is thin overlay — rebase to local golden on target
}
message PrepareMigrationIncomingResponse {
@@ -351,3 +357,11 @@ message CompleteMigrationIncomingRequest {
}
message CompleteMigrationIncomingResponse {}
+
+// Golden snapshot management
+message RebuildGoldenSnapshotRequest {}
+
+message RebuildGoldenSnapshotResponse {
+ string old_version = 1; // previous golden version (empty if none)
+ string new_version = 2; // new golden version after rebuild
+}
diff --git a/proto/worker/worker_grpc.pb.go b/proto/worker/worker_grpc.pb.go
index a75724a9..d8fb4551 100644
--- a/proto/worker/worker_grpc.pb.go
+++ b/proto/worker/worker_grpc.pb.go
@@ -45,6 +45,7 @@ const (
SandboxWorker_PrepareMigrationIncoming_FullMethodName = "/worker.SandboxWorker/PrepareMigrationIncoming"
SandboxWorker_LiveMigrate_FullMethodName = "/worker.SandboxWorker/LiveMigrate"
SandboxWorker_CompleteMigrationIncoming_FullMethodName = "/worker.SandboxWorker/CompleteMigrationIncoming"
+ SandboxWorker_RebuildGoldenSnapshot_FullMethodName = "/worker.SandboxWorker/RebuildGoldenSnapshot"
)
// SandboxWorkerClient is the client API for SandboxWorker service.
@@ -78,6 +79,8 @@ type SandboxWorkerClient interface {
PrepareMigrationIncoming(ctx context.Context, in *PrepareMigrationIncomingRequest, opts ...grpc.CallOption) (*PrepareMigrationIncomingResponse, error)
LiveMigrate(ctx context.Context, in *LiveMigrateRequest, opts ...grpc.CallOption) (*LiveMigrateResponse, error)
CompleteMigrationIncoming(ctx context.Context, in *CompleteMigrationIncomingRequest, opts ...grpc.CallOption) (*CompleteMigrationIncomingResponse, error)
+ // Golden snapshot management
+ RebuildGoldenSnapshot(ctx context.Context, in *RebuildGoldenSnapshotRequest, opts ...grpc.CallOption) (*RebuildGoldenSnapshotResponse, error)
}
type sandboxWorkerClient struct {
@@ -360,6 +363,16 @@ func (c *sandboxWorkerClient) CompleteMigrationIncoming(ctx context.Context, in
return out, nil
}
+func (c *sandboxWorkerClient) RebuildGoldenSnapshot(ctx context.Context, in *RebuildGoldenSnapshotRequest, opts ...grpc.CallOption) (*RebuildGoldenSnapshotResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(RebuildGoldenSnapshotResponse)
+ err := c.cc.Invoke(ctx, SandboxWorker_RebuildGoldenSnapshot_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
// SandboxWorkerServer is the server API for SandboxWorker service.
// All implementations must embed UnimplementedSandboxWorkerServer
// for forward compatibility.
@@ -391,6 +404,8 @@ type SandboxWorkerServer interface {
PrepareMigrationIncoming(context.Context, *PrepareMigrationIncomingRequest) (*PrepareMigrationIncomingResponse, error)
LiveMigrate(context.Context, *LiveMigrateRequest) (*LiveMigrateResponse, error)
CompleteMigrationIncoming(context.Context, *CompleteMigrationIncomingRequest) (*CompleteMigrationIncomingResponse, error)
+ // Golden snapshot management
+ RebuildGoldenSnapshot(context.Context, *RebuildGoldenSnapshotRequest) (*RebuildGoldenSnapshotResponse, error)
mustEmbedUnimplementedSandboxWorkerServer()
}
@@ -479,6 +494,9 @@ func (UnimplementedSandboxWorkerServer) LiveMigrate(context.Context, *LiveMigrat
func (UnimplementedSandboxWorkerServer) CompleteMigrationIncoming(context.Context, *CompleteMigrationIncomingRequest) (*CompleteMigrationIncomingResponse, error) {
return nil, status.Error(codes.Unimplemented, "method CompleteMigrationIncoming not implemented")
}
+func (UnimplementedSandboxWorkerServer) RebuildGoldenSnapshot(context.Context, *RebuildGoldenSnapshotRequest) (*RebuildGoldenSnapshotResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method RebuildGoldenSnapshot not implemented")
+}
func (UnimplementedSandboxWorkerServer) mustEmbedUnimplementedSandboxWorkerServer() {}
func (UnimplementedSandboxWorkerServer) testEmbeddedByValue() {}
@@ -950,6 +968,24 @@ func _SandboxWorker_CompleteMigrationIncoming_Handler(srv interface{}, ctx conte
return interceptor(ctx, in, info, handler)
}
+func _SandboxWorker_RebuildGoldenSnapshot_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(RebuildGoldenSnapshotRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(SandboxWorkerServer).RebuildGoldenSnapshot(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: SandboxWorker_RebuildGoldenSnapshot_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(SandboxWorkerServer).RebuildGoldenSnapshot(ctx, req.(*RebuildGoldenSnapshotRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
// SandboxWorker_ServiceDesc is the grpc.ServiceDesc for SandboxWorker service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
@@ -1053,6 +1089,10 @@ var SandboxWorker_ServiceDesc = grpc.ServiceDesc{
MethodName: "CompleteMigrationIncoming",
Handler: _SandboxWorker_CompleteMigrationIncoming_Handler,
},
+ {
+ MethodName: "RebuildGoldenSnapshot",
+ Handler: _SandboxWorker_RebuildGoldenSnapshot_Handler,
+ },
},
Streams: []grpc.StreamDesc{
{