Skip to content

An open-source, faster Devin alternative

TypeScript

autoscaling wip

Brian Reardon03f1d4b19178
diff --git a/cmd/server/main.go b/cmd/server/main.go
index 233ad318..007e6cd7 100644
--- a/cmd/server/main.go
+++ b/cmd/server/main.go
@@ -247,6 +247,7 @@ func main() {
scaler := controlplane.NewScaler(controlplane.ScalerConfig{
Pool: pool,
Registry: redisRegistry,
+ Store: opts.Store,
WorkerImage: cfg.EC2WorkerImage,
Cooldown: time.Duration(cfg.ScaleCooldownSec) * time.Second,
MinWorkers: cfg.MinWorkersPerRegion,
diff --git a/internal/controlplane/scaler.go b/internal/controlplane/scaler.go
index 67ffff8a..a96f6200 100644
--- a/internal/controlplane/scaler.go
+++ b/internal/controlplane/scaler.go
@@ -2,6 +2,7 @@ package controlplane
import (
"context"
+ "encoding/json"
"fmt"
"log"
"strings"
@@ -9,6 +10,8 @@ import (
"time"
"github.com/opensandbox/opensandbox/internal/compute"
+ "github.com/opensandbox/opensandbox/internal/db"
+ pb "github.com/opensandbox/opensandbox/proto/worker"
)
const (
@@ -20,6 +23,13 @@ const (
// 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%
+
+ // Evacuation thresholds (per-worker, triggers live migration of sandboxes OFF the hot worker)
+ evacuationCPUThreshold = 90.0
+ evacuationMemThreshold = 90.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
)
// ScalerRegistry is the interface the Scaler uses to query worker state.
@@ -29,12 +39,14 @@ type ScalerRegistry interface {
GetWorkersByRegion(region string) []*WorkerInfo
RegionUtilization(region string) float64
RegionResourcePressure(region string) (maxCPU, maxMem float64)
+ GetWorkerClient(workerID string) (pb.SandboxWorkerClient, error)
}
// ScalerConfig configures the autoscaler.
type ScalerConfig struct {
Pool compute.Pool
Registry ScalerRegistry
+ Store *db.Store // for updating session worker_id after migration
WorkerImage string
Cooldown time.Duration // minimum time between scale-up actions per region
Interval time.Duration // how often to evaluate scaling (0 = default 30s)
@@ -48,10 +60,19 @@ type pendingLaunch struct {
launchedAt time.Time
}
+// drainState tracks a worker being drained for scale-down.
+type drainState struct {
+ workerID string
+ machineID string
+ region string
+ startedAt time.Time
+}
+
// Scaler manages autoscaling of workers via the compute Pool.
type Scaler struct {
pool compute.Pool
registry ScalerRegistry
+ store *db.Store
image string
cooldown time.Duration
interval time.Duration
@@ -61,6 +82,11 @@ type Scaler struct {
pending map[string][]pendingLaunch // region -> pending (unregistered) launches
stop chan struct{}
wg sync.WaitGroup
+
+ // Drain & evacuation state
+ draining map[string]*drainState // machineID -> state (workers being drained for scale-down)
+ lastEvacuation map[string]time.Time // workerID -> last evacuation time
+ migrating sync.Map // sandboxID -> struct{} (prevent double-migrate)
}
// NewScaler creates a new autoscaling controller.
@@ -82,16 +108,19 @@ func NewScaler(cfg ScalerConfig) *Scaler {
maxWorkers = maxWorkersPerRegion
}
return &Scaler{
- pool: cfg.Pool,
- registry: cfg.Registry,
- image: cfg.WorkerImage,
- cooldown: cooldown,
- interval: interval,
- minWorkers: minWorkers,
- maxWorkers: maxWorkers,
- lastScaleUp: make(map[string]time.Time),
- pending: make(map[string][]pendingLaunch),
- stop: make(chan struct{}),
+ pool: cfg.Pool,
+ registry: cfg.Registry,
+ store: cfg.Store,
+ image: cfg.WorkerImage,
+ cooldown: cooldown,
+ interval: interval,
+ minWorkers: minWorkers,
+ maxWorkers: maxWorkers,
+ lastScaleUp: make(map[string]time.Time),
+ pending: make(map[string][]pendingLaunch),
+ stop: make(chan struct{}),
+ draining: make(map[string]*drainState),
+ lastEvacuation: make(map[string]time.Time),
}
}
@@ -148,7 +177,13 @@ func (s *Scaler) evaluateRegion(ctx context.Context, region string) {
// Expire stale pending launches
s.expirePending(region)
- // Determine if we need to scale up: count-based OR resource-based
+ // Phase 1: Check progress on workers being drained
+ s.checkDrainingWorkers(ctx, region)
+
+ // Phase 2: Evacuate overloaded workers (live-migrate sandboxes off hot workers)
+ s.evacuateHotWorkers(ctx, region, workers)
+
+ // Phase 3: Determine if we need to scale up (count-based OR resource-based)
needsScaleUp := false
reason := ""
@@ -194,9 +229,15 @@ func (s *Scaler) evaluateRegion(ctx context.Context, region string) {
return
}
- // Don't exceed max workers per region
- if totalWorkers >= s.maxWorkers {
- log.Printf("scaler: region %s at max workers (%d/%d), skipping scale-up", region, totalWorkers, s.maxWorkers)
+ // Don't exceed max workers per region (exclude draining workers from capacity)
+ effectiveWorkers := 0
+ for _, w := range workers {
+ if _, isDraining := s.draining[w.MachineID]; !isDraining {
+ effectiveWorkers++
+ }
+ }
+ if effectiveWorkers+len(s.pending[region]) >= s.maxWorkers {
+ log.Printf("scaler: region %s at max workers (%d/%d), skipping scale-up", region, effectiveWorkers, s.maxWorkers)
return
}
@@ -204,8 +245,9 @@ func (s *Scaler) evaluateRegion(ctx context.Context, region string) {
region, reason, maxCPU, maxMem, utilization*100)
s.scaleUp(ctx, region)
} else if utilization < scaleDownThreshold && len(workers) > s.minWorkers {
- log.Printf("scaler: region %s utilization %.1f%% < %.0f%%, scaling down", region, utilization*100, scaleDownThreshold*100)
- s.scaleDown(ctx, region, workers)
+ // Phase 4: Scale down via smart drain (live-migrate sandboxes, then destroy)
+ log.Printf("scaler: region %s utilization %.1f%% < %.0f%%, initiating smart drain", region, utilization*100, scaleDownThreshold*100)
+ s.smartScaleDown(ctx, region, workers)
}
}
@@ -274,10 +316,107 @@ func (s *Scaler) expirePending(region string) {
s.pending[region] = remaining
}
-func (s *Scaler) scaleDown(ctx context.Context, region string, workers []*WorkerInfo) {
+// --- Pressure Evacuation ---
+
+// 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 {
+ continue
+ }
+ // Skip if already being drained for scale-down
+ if _, ok := s.draining[w.MachineID]; ok {
+ continue
+ }
+ // Cooldown — don't evacuate the same worker every tick
+ if last, ok := s.lastEvacuation[w.ID]; ok && time.Since(last) < evacuationCooldown {
+ continue
+ }
+
+ // 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)
+ 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)
+
+ s.lastEvacuation[w.ID] = time.Now()
+ go s.evacuateBatch(w.ID, target.ID, evacuationBatchSize)
+ }
+}
+
+// findMigrationTarget returns the best worker to receive migrated sandboxes.
+func (s *Scaler) findMigrationTarget(region, excludeWorkerID string) *WorkerInfo {
+ workers := s.registry.GetWorkersByRegion(region)
+ var best *WorkerInfo
+ bestScore := -1.0
+ for _, w := range workers {
+ if w.ID == excludeWorkerID {
+ continue
+ }
+ if _, isDraining := s.draining[w.MachineID]; isDraining {
+ continue
+ }
+ remaining := w.Capacity - w.Current
+ if remaining <= 0 || w.CPUPct > 85 || w.MemPct > 85 {
+ continue
+ }
+ resourceScore := (100.0 - w.CPUPct) / 100.0 * (100.0 - w.MemPct) / 100.0
+ score := float64(remaining) * resourceScore
+ if score > bestScore {
+ best = w
+ bestScore = score
+ }
+ }
+ return best
+}
+
+// evacuateBatch live-migrates up to count sandboxes from sourceWorker to targetWorker.
+func (s *Scaler) evacuateBatch(sourceWorkerID, targetWorkerID string, count int) {
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
+ defer cancel()
+
+ sourceClient, err := s.registry.GetWorkerClient(sourceWorkerID)
+ if err != nil {
+ log.Printf("scaler: evacuate: no gRPC client for source %s: %v", sourceWorkerID, err)
+ return
+ }
+
+ listResp, err := sourceClient.ListSandboxes(ctx, &pb.ListSandboxesRequest{})
+ if err != nil {
+ log.Printf("scaler: evacuate: ListSandboxes failed for %s: %v", sourceWorkerID, err)
+ return
+ }
+
+ migrated := 0
+ for _, sb := range listResp.Sandboxes {
+ if migrated >= count {
+ break
+ }
+ if sb.Status != "running" {
+ continue
+ }
+ if err := s.liveMigrateSandbox(ctx, sb.SandboxId, sourceWorkerID, targetWorkerID); err != nil {
+ log.Printf("scaler: evacuate: migrate %s failed: %v", sb.SandboxId, err)
+ continue
+ }
+ migrated++
+ }
+
+ log.Printf("scaler: evacuation batch complete for %s: %d/%d migrated to %s",
+ sourceWorkerID, migrated, count, targetWorkerID)
+}
+
+// --- Smart Scale-Down ---
+
+// smartScaleDown initiates draining of the least-loaded autoscaler-created worker
+// by live-migrating its sandboxes to other workers before destroying the machine.
+func (s *Scaler) smartScaleDown(_ context.Context, region string, workers []*WorkerInfo) {
// Find the least-loaded worker that was created by the autoscaler.
- // Only target workers whose machine ID matches the naming convention (osb-worker-*).
- // This skips manually created workers (hostname like "localhost.localdomain" or "osb-worker-1").
var target *WorkerInfo
for _, w := range workers {
if w.MachineID == "" {
@@ -286,8 +425,11 @@ func (s *Scaler) scaleDown(ctx context.Context, region string, workers []*Worker
if !strings.HasPrefix(w.MachineID, "osb-worker-") {
continue // not created by autoscaler
}
- // Skip the static worker-1 (manually created, not autoscaled)
if w.MachineID == "osb-worker-1" {
+ continue // static worker, not autoscaled
+ }
+ // Skip workers already being drained
+ if _, ok := s.draining[w.MachineID]; ok {
continue
}
if target == nil || w.Current < target.Current {
@@ -299,22 +441,239 @@ func (s *Scaler) scaleDown(ctx context.Context, region string, workers []*Worker
return
}
- machineID := target.MachineID
- log.Printf("scaler: draining worker %s (machine=%s) in %s (current=%d)", target.ID, machineID, region, target.Current)
+ log.Printf("scaler: initiating smart drain of worker %s (machine=%s, sandboxes=%d)",
+ target.ID, target.MachineID, target.Current)
+
+ s.draining[target.MachineID] = &drainState{
+ workerID: target.ID,
+ machineID: target.MachineID,
+ region: region,
+ startedAt: time.Now(),
+ }
+
+ go s.drainWorker(target.ID, target.MachineID, region)
+}
+
+// drainWorker live-migrates all sandboxes off a worker, then signals completion
+// via the draining map (checkDrainingWorkers will destroy the machine).
+func (s *Scaler) drainWorker(workerID, machineID, region string) {
+ ctx, cancel := context.WithTimeout(context.Background(), drainTimeout)
+ defer cancel()
+
+ sourceClient, err := s.registry.GetWorkerClient(workerID)
+ if err != nil {
+ log.Printf("scaler: drain: no gRPC client for %s, will force-destroy on timeout", workerID)
+ return
+ }
+
+ for {
+ select {
+ case <-ctx.Done():
+ log.Printf("scaler: drain: timeout reached for worker %s", workerID)
+ return
+ default:
+ }
+
+ listResp, err := sourceClient.ListSandboxes(ctx, &pb.ListSandboxesRequest{})
+ if err != nil {
+ log.Printf("scaler: drain: ListSandboxes failed for %s: %v", workerID, err)
+ return
+ }
+
+ // Count running sandboxes
+ var running []string
+ for _, sb := range listResp.Sandboxes {
+ if sb.Status == "running" {
+ running = append(running, sb.SandboxId)
+ }
+ }
+ if len(running) == 0 {
+ log.Printf("scaler: drain: worker %s fully drained", workerID)
+ return
+ }
+
+ // Find target for this batch
+ target := s.findMigrationTarget(region, workerID)
+ if target == nil {
+ log.Printf("scaler: drain: no migration target for %s, waiting...", workerID)
+ time.Sleep(10 * time.Second)
+ continue
+ }
+
+ // Migrate a batch
+ batch := running
+ if len(batch) > evacuationBatchSize {
+ batch = batch[:evacuationBatchSize]
+ }
+
+ for _, sandboxID := range batch {
+ if err := s.liveMigrateSandbox(ctx, sandboxID, workerID, target.ID); err != nil {
+ log.Printf("scaler: drain: migrate %s failed: %v", sandboxID, err)
+ }
+ }
+
+ // Brief pause between batches
+ time.Sleep(2 * time.Second)
+ }
+}
+
+// checkDrainingWorkers checks if draining workers are empty and destroys them.
+func (s *Scaler) checkDrainingWorkers(ctx context.Context, region string) {
+ for machineID, state := range s.draining {
+ if state.region != region {
+ continue
+ }
+
+ // Check if drain timed out
+ if time.Since(state.startedAt) > drainTimeout {
+ log.Printf("scaler: drain timeout for worker %s (machine=%s), force-destroying",
+ state.workerID, machineID)
+ s.destroyDrainedMachine(machineID)
+ delete(s.draining, machineID)
+ continue
+ }
- // Run drain+destroy in background — Azure VM deletion takes 1-3 minutes
+ // Check if worker has 0 sandboxes
+ workers := s.registry.GetWorkersByRegion(region)
+ for _, w := range workers {
+ if w.MachineID == machineID && w.Current == 0 {
+ log.Printf("scaler: worker %s fully drained (0 sandboxes), destroying machine %s",
+ state.workerID, machineID)
+ s.destroyDrainedMachine(machineID)
+ delete(s.draining, machineID)
+ break
+ }
+ }
+ }
+}
+
+// destroyDrainedMachine tags and terminates a machine after drain.
+func (s *Scaler) destroyDrainedMachine(machineID string) {
go func() {
- destroyCtx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
- if err := s.pool.DrainMachine(destroyCtx, machineID); err != nil {
- log.Printf("scaler: failed to drain machine %s: %v", machineID, err)
+ if err := s.pool.DrainMachine(ctx, machineID); err != nil {
+ log.Printf("scaler: DrainMachine tag failed for %s: %v", machineID, err)
}
- if err := s.pool.DestroyMachine(destroyCtx, machineID); err != nil {
- log.Printf("scaler: failed to destroy machine %s: %v", machineID, err)
+ if err := s.pool.DestroyMachine(ctx, machineID); err != nil {
+ log.Printf("scaler: DestroyMachine failed for %s: %v", machineID, err)
} else {
log.Printf("scaler: machine %s destroyed successfully", machineID)
}
}()
}
+
+// --- Live Migration Orchestration ---
+
+// liveMigrateSandbox performs a full live migration of a sandbox between workers.
+// Steps: pre-copy drives to S3 → prepare target → QMP migrate → complete → update DB.
+func (s *Scaler) liveMigrateSandbox(ctx context.Context, sandboxID, sourceWorkerID, targetWorkerID string) error {
+ // Prevent double-migrate
+ if _, loaded := s.migrating.LoadOrStore(sandboxID, struct{}{}); loaded {
+ return fmt.Errorf("migration already in progress for %s", sandboxID)
+ }
+ defer s.migrating.Delete(sandboxID)
+
+ sourceClient, err := s.registry.GetWorkerClient(sourceWorkerID)
+ if err != nil {
+ return fmt.Errorf("source worker %s unreachable: %w", sourceWorkerID, err)
+ }
+ targetClient, err := s.registry.GetWorkerClient(targetWorkerID)
+ if err != nil {
+ return fmt.Errorf("target worker %s unreachable: %w", targetWorkerID, err)
+ }
+
+ t0 := time.Now()
+
+ // 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,
+ })
+ 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())
+
+ // Step 2: Prepare target (downloads from S3, starts QEMU -incoming)
+ // Get sandbox config from DB for CPU/memory/port
+ cpuCount, memoryMB, guestPort, template := int32(1), int32(1024), int32(80), "base"
+ if s.store != nil {
+ session, err := s.store.GetSandboxSession(ctx, sandboxID)
+ if err == nil && session != nil {
+ if session.Template != "" {
+ template = session.Template
+ }
+ // Parse CPU/memory from session config JSON
+ var cfg struct {
+ CPUCount int32 `json:"cpu_count"`
+ MemoryMB int32 `json:"memory_mb"`
+ Port int32 `json:"port"`
+ }
+ if json.Unmarshal(session.Config, &cfg) == nil {
+ if cfg.CPUCount > 0 {
+ cpuCount = cfg.CPUCount
+ }
+ if cfg.MemoryMB > 0 {
+ memoryMB = cfg.MemoryMB
+ }
+ if cfg.Port > 0 {
+ guestPort = cfg.Port
+ }
+ }
+ }
+ }
+
+ prepCtx, prepCancel := context.WithTimeout(ctx, 3*time.Minute)
+ defer prepCancel()
+ prepResp, err := targetClient.PrepareMigrationIncoming(prepCtx, &pb.PrepareMigrationIncomingRequest{
+ SandboxId: sandboxID,
+ CpuCount: cpuCount,
+ MemoryMb: memoryMB,
+ GuestPort: guestPort,
+ Template: template,
+ RootfsS3Key: preCopyResp.RootfsKey,
+ WorkspaceS3Key: preCopyResp.WorkspaceKey,
+ })
+ if err != nil {
+ return fmt.Errorf("prepare target: %w", err)
+ }
+
+ log.Printf("scaler: migrate %s: target prepared at %s (%dms)", sandboxID, prepResp.IncomingAddr, time.Since(t0).Milliseconds())
+
+ // Step 3: Live migrate (source QMP → target)
+ migrateCtx, migrateCancel := context.WithTimeout(ctx, 5*time.Minute)
+ defer migrateCancel()
+ _, err = sourceClient.LiveMigrate(migrateCtx, &pb.LiveMigrateRequest{
+ SandboxId: sandboxID,
+ IncomingAddr: prepResp.IncomingAddr,
+ })
+ if err != nil {
+ return fmt.Errorf("live migrate: %w", err)
+ }
+
+ log.Printf("scaler: migrate %s: QMP migration complete (%dms)", sandboxID, time.Since(t0).Milliseconds())
+
+ // Step 4: Complete on target (reconnect agent, patch network)
+ completeCtx, completeCancel := context.WithTimeout(ctx, 30*time.Second)
+ defer completeCancel()
+ _, err = targetClient.CompleteMigrationIncoming(completeCtx, &pb.CompleteMigrationIncomingRequest{
+ SandboxId: sandboxID,
+ })
+ if err != nil {
+ return fmt.Errorf("complete migration: %w", err)
+ }
+
+ // Step 5: Update DB — sandbox now on target worker
+ if s.store != nil {
+ _, _ = s.store.Pool().Exec(ctx, "UPDATE sandbox_sessions SET worker_id = $1 WHERE sandbox_id = $2", targetWorkerID, sandboxID)
+ }
+
+ elapsed := time.Since(t0).Milliseconds()
+ log.Printf("scaler: migrate %s: complete in %dms (source=%s target=%s)", sandboxID, elapsed, sourceWorkerID, targetWorkerID)
+ return nil
+}
diff --git a/internal/controlplane/worker_registry.go b/internal/controlplane/worker_registry.go
index c646e7b6..c07520a2 100644
--- a/internal/controlplane/worker_registry.go
+++ b/internal/controlplane/worker_registry.go
@@ -2,11 +2,13 @@ package controlplane
import (
"encoding/json"
+ "fmt"
"log"
"sync"
"time"
"github.com/nats-io/nats.go"
+ pb "github.com/opensandbox/opensandbox/proto/worker"
)
// WorkerInfo represents a registered worker.
@@ -206,6 +208,11 @@ func (r *WorkerRegistry) Regions() []string {
return regions
}
+// GetWorkerClient is not supported on the NATS-based registry (no gRPC pool).
+func (r *WorkerRegistry) GetWorkerClient(workerID string) (pb.SandboxWorkerClient, error) {
+ return nil, fmt.Errorf("GetWorkerClient not supported on NATS registry (worker %s)", workerID)
+}
+
func (r *WorkerRegistry) handleHeartbeat(msg *nats.Msg) {
var hb WorkerInfo
if err := json.Unmarshal(msg.Data, &hb); err != nil {
diff --git a/internal/qemu/migration.go b/internal/qemu/migration.go
index 8e3cc07e..bd8a1143 100644
--- a/internal/qemu/migration.go
+++ b/internal/qemu/migration.go
@@ -3,6 +3,7 @@ package qemu
import (
"context"
"fmt"
+ "io"
"log"
"os"
"os/exec"
@@ -359,6 +360,58 @@ func (m *Manager) CompleteIncomingMigration(ctx context.Context, sandboxID strin
return nil
}
+// 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) {
+ mc := &MigrationCoordinator{
+ manager: m,
+ checkpointStore: checkpointStore,
+ migrations: make(map[string]*MigrationState),
+ }
+ return mc.MigrateToS3(ctx, sandboxID)
+}
+
+// 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) {
+ sandboxDir := filepath.Join(m.cfg.DataDir, "sandboxes", sandboxID)
+ if err := os.MkdirAll(sandboxDir, 0755); err != nil {
+ return "", 0, fmt.Errorf("mkdir: %w", err)
+ }
+
+ // Download rootfs from S3
+ rootfsPath := filepath.Join(sandboxDir, "rootfs.qcow2")
+ if err := downloadS3ToFile(ctx, checkpointStore, rootfsS3Key, rootfsPath); err != nil {
+ return "", 0, fmt.Errorf("download rootfs from S3: %w", err)
+ }
+
+ // Download workspace from S3
+ workspacePath := filepath.Join(sandboxDir, "workspace.qcow2")
+ if err := downloadS3ToFile(ctx, checkpointStore, workspaceS3Key, workspacePath); err != nil {
+ return "", 0, fmt.Errorf("download workspace from S3: %w", err)
+ }
+
+ return m.PrepareIncomingMigration(ctx, sandboxID, rootfsPath, workspacePath, cpus, memMB, guestPort, template)
+}
+
+// downloadS3ToFile downloads an S3 object to a local file.
+func downloadS3ToFile(ctx context.Context, store *storage.CheckpointStore, key, localPath string) error {
+ rc, err := store.Download(ctx, key)
+ if err != nil {
+ return err
+ }
+ defer rc.Close()
+
+ f, err := os.Create(localPath)
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+
+ if _, err := io.Copy(f, rc); err != nil {
+ return err
+ }
+ return f.Sync()
+}
+
// LiveMigrate on Manager delegates to a MigrationCoordinator.
func (m *Manager) LiveMigrate(ctx context.Context, sandboxID, incomingAddr string) error {
mc := &MigrationCoordinator{
diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.go
index d06d4921..c49f1e0e 100644
--- a/internal/worker/grpc_server.go
+++ b/internal/worker/grpc_server.go
@@ -31,6 +31,8 @@ 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)
CompleteIncomingMigration(ctx context.Context, sandboxID string) error
LiveMigrate(ctx context.Context, sandboxID, incomingAddr string) error
}
@@ -837,13 +839,38 @@ func (s *GRPCServer) SetMigrator(m LiveMigrator) {
s.migrator = m
}
+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)
+ if err != nil {
+ return nil, fmt.Errorf("pre-copy drives: %w", err)
+ }
+ return &pb.PreCopyDrivesResponse{
+ RootfsKey: rootfsKey,
+ WorkspaceKey: workspaceKey,
+ }, nil
+}
+
func (s *GRPCServer) PrepareMigrationIncoming(ctx context.Context, req *pb.PrepareMigrationIncomingRequest) (*pb.PrepareMigrationIncomingResponse, error) {
if s.migrator == nil {
return nil, fmt.Errorf("live migration not supported on this worker")
}
- addr, hostPort, err := s.migrator.PrepareIncomingMigration(ctx,
- req.SandboxId, req.RootfsPath, req.WorkspacePath,
- int(req.CpuCount), int(req.MemoryMb), int(req.GuestPort), req.Template)
+ var (
+ addr string
+ hostPort int
+ err error
+ )
+ 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)
+ } else {
+ addr, hostPort, err = s.migrator.PrepareIncomingMigration(ctx,
+ req.SandboxId, req.RootfsPath, req.WorkspacePath,
+ int(req.CpuCount), int(req.MemoryMb), int(req.GuestPort), req.Template)
+ }
if err != nil {
return nil, fmt.Errorf("prepare incoming migration: %w", err)
}
diff --git a/proto/worker/worker.pb.go b/proto/worker/worker.pb.go
index 973d0dee..ff179e05 100644
--- a/proto/worker/worker.pb.go
+++ b/proto/worker/worker.pb.go
@@ -2711,22 +2711,120 @@ func (*SetSandboxLimitsResponse) Descriptor() ([]byte, []int) {
}
// Live migration messages
-type PrepareMigrationIncomingRequest struct {
+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"`
- RootfsPath string `protobuf:"bytes,2,opt,name=rootfs_path,json=rootfsPath,proto3" json:"rootfs_path,omitempty"` // local path to rootfs on target (pre-copied)
- WorkspacePath string `protobuf:"bytes,3,opt,name=workspace_path,json=workspacePath,proto3" json:"workspace_path,omitempty"` // local path to workspace on target (pre-copied)
- CpuCount int32 `protobuf:"varint,4,opt,name=cpu_count,json=cpuCount,proto3" json:"cpu_count,omitempty"`
- MemoryMb int32 `protobuf:"varint,5,opt,name=memory_mb,json=memoryMb,proto3" json:"memory_mb,omitempty"`
- GuestPort int32 `protobuf:"varint,6,opt,name=guest_port,json=guestPort,proto3" json:"guest_port,omitempty"`
- Template string `protobuf:"bytes,7,opt,name=template,proto3" json:"template,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
+func (x *PreCopyDrivesRequest) Reset() {
+ *x = PreCopyDrivesRequest{}
+ mi := &file_proto_worker_worker_proto_msgTypes[46]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *PreCopyDrivesRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*PreCopyDrivesRequest) ProtoMessage() {}
+
+func (x *PreCopyDrivesRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_worker_worker_proto_msgTypes[46]
+ 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 PreCopyDrivesRequest.ProtoReflect.Descriptor instead.
+func (*PreCopyDrivesRequest) Descriptor() ([]byte, []int) {
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{46}
+}
+
+func (x *PreCopyDrivesRequest) GetSandboxId() string {
+ if x != nil {
+ return x.SandboxId
+ }
+ return ""
+}
+
+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
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *PreCopyDrivesResponse) Reset() {
+ *x = PreCopyDrivesResponse{}
+ mi := &file_proto_worker_worker_proto_msgTypes[47]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *PreCopyDrivesResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*PreCopyDrivesResponse) ProtoMessage() {}
+
+func (x *PreCopyDrivesResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_worker_worker_proto_msgTypes[47]
+ 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 PreCopyDrivesResponse.ProtoReflect.Descriptor instead.
+func (*PreCopyDrivesResponse) Descriptor() ([]byte, []int) {
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{47}
+}
+
+func (x *PreCopyDrivesResponse) GetRootfsKey() string {
+ if x != nil {
+ return x.RootfsKey
+ }
+ return ""
+}
+
+func (x *PreCopyDrivesResponse) GetWorkspaceKey() string {
+ if x != nil {
+ return x.WorkspaceKey
+ }
+ 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"`
+ RootfsPath string `protobuf:"bytes,2,opt,name=rootfs_path,json=rootfsPath,proto3" json:"rootfs_path,omitempty"` // local path to rootfs on target (pre-copied)
+ WorkspacePath string `protobuf:"bytes,3,opt,name=workspace_path,json=workspacePath,proto3" json:"workspace_path,omitempty"` // local path to workspace on target (pre-copied)
+ CpuCount int32 `protobuf:"varint,4,opt,name=cpu_count,json=cpuCount,proto3" json:"cpu_count,omitempty"`
+ MemoryMb int32 `protobuf:"varint,5,opt,name=memory_mb,json=memoryMb,proto3" json:"memory_mb,omitempty"`
+ GuestPort int32 `protobuf:"varint,6,opt,name=guest_port,json=guestPort,proto3" json:"guest_port,omitempty"`
+ 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
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
func (x *PrepareMigrationIncomingRequest) Reset() {
*x = PrepareMigrationIncomingRequest{}
- mi := &file_proto_worker_worker_proto_msgTypes[46]
+ mi := &file_proto_worker_worker_proto_msgTypes[48]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2738,7 +2836,7 @@ func (x *PrepareMigrationIncomingRequest) String() string {
func (*PrepareMigrationIncomingRequest) ProtoMessage() {}
func (x *PrepareMigrationIncomingRequest) ProtoReflect() protoreflect.Message {
- mi := &file_proto_worker_worker_proto_msgTypes[46]
+ mi := &file_proto_worker_worker_proto_msgTypes[48]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2751,7 +2849,7 @@ func (x *PrepareMigrationIncomingRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use PrepareMigrationIncomingRequest.ProtoReflect.Descriptor instead.
func (*PrepareMigrationIncomingRequest) Descriptor() ([]byte, []int) {
- return file_proto_worker_worker_proto_rawDescGZIP(), []int{46}
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{48}
}
func (x *PrepareMigrationIncomingRequest) GetSandboxId() string {
@@ -2803,6 +2901,20 @@ func (x *PrepareMigrationIncomingRequest) GetTemplate() string {
return ""
}
+func (x *PrepareMigrationIncomingRequest) GetRootfsS3Key() string {
+ if x != nil {
+ return x.RootfsS3Key
+ }
+ return ""
+}
+
+func (x *PrepareMigrationIncomingRequest) GetWorkspaceS3Key() string {
+ if x != nil {
+ return x.WorkspaceS3Key
+ }
+ return ""
+}
+
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")
@@ -2813,7 +2925,7 @@ type PrepareMigrationIncomingResponse struct {
func (x *PrepareMigrationIncomingResponse) Reset() {
*x = PrepareMigrationIncomingResponse{}
- mi := &file_proto_worker_worker_proto_msgTypes[47]
+ mi := &file_proto_worker_worker_proto_msgTypes[49]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2825,7 +2937,7 @@ func (x *PrepareMigrationIncomingResponse) String() string {
func (*PrepareMigrationIncomingResponse) ProtoMessage() {}
func (x *PrepareMigrationIncomingResponse) ProtoReflect() protoreflect.Message {
- mi := &file_proto_worker_worker_proto_msgTypes[47]
+ mi := &file_proto_worker_worker_proto_msgTypes[49]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2838,7 +2950,7 @@ func (x *PrepareMigrationIncomingResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use PrepareMigrationIncomingResponse.ProtoReflect.Descriptor instead.
func (*PrepareMigrationIncomingResponse) Descriptor() ([]byte, []int) {
- return file_proto_worker_worker_proto_rawDescGZIP(), []int{47}
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{49}
}
func (x *PrepareMigrationIncomingResponse) GetIncomingAddr() string {
@@ -2865,7 +2977,7 @@ type LiveMigrateRequest struct {
func (x *LiveMigrateRequest) Reset() {
*x = LiveMigrateRequest{}
- mi := &file_proto_worker_worker_proto_msgTypes[48]
+ mi := &file_proto_worker_worker_proto_msgTypes[50]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2877,7 +2989,7 @@ func (x *LiveMigrateRequest) String() string {
func (*LiveMigrateRequest) ProtoMessage() {}
func (x *LiveMigrateRequest) ProtoReflect() protoreflect.Message {
- mi := &file_proto_worker_worker_proto_msgTypes[48]
+ mi := &file_proto_worker_worker_proto_msgTypes[50]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2890,7 +3002,7 @@ func (x *LiveMigrateRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use LiveMigrateRequest.ProtoReflect.Descriptor instead.
func (*LiveMigrateRequest) Descriptor() ([]byte, []int) {
- return file_proto_worker_worker_proto_rawDescGZIP(), []int{48}
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{50}
}
func (x *LiveMigrateRequest) GetSandboxId() string {
@@ -2915,7 +3027,7 @@ type LiveMigrateResponse struct {
func (x *LiveMigrateResponse) Reset() {
*x = LiveMigrateResponse{}
- mi := &file_proto_worker_worker_proto_msgTypes[49]
+ mi := &file_proto_worker_worker_proto_msgTypes[51]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2927,7 +3039,7 @@ func (x *LiveMigrateResponse) String() string {
func (*LiveMigrateResponse) ProtoMessage() {}
func (x *LiveMigrateResponse) ProtoReflect() protoreflect.Message {
- mi := &file_proto_worker_worker_proto_msgTypes[49]
+ mi := &file_proto_worker_worker_proto_msgTypes[51]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2940,7 +3052,7 @@ func (x *LiveMigrateResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use LiveMigrateResponse.ProtoReflect.Descriptor instead.
func (*LiveMigrateResponse) Descriptor() ([]byte, []int) {
- return file_proto_worker_worker_proto_rawDescGZIP(), []int{49}
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{51}
}
type CompleteMigrationIncomingRequest struct {
@@ -2952,7 +3064,7 @@ type CompleteMigrationIncomingRequest struct {
func (x *CompleteMigrationIncomingRequest) Reset() {
*x = CompleteMigrationIncomingRequest{}
- mi := &file_proto_worker_worker_proto_msgTypes[50]
+ mi := &file_proto_worker_worker_proto_msgTypes[52]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2964,7 +3076,7 @@ func (x *CompleteMigrationIncomingRequest) String() string {
func (*CompleteMigrationIncomingRequest) ProtoMessage() {}
func (x *CompleteMigrationIncomingRequest) ProtoReflect() protoreflect.Message {
- mi := &file_proto_worker_worker_proto_msgTypes[50]
+ mi := &file_proto_worker_worker_proto_msgTypes[52]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2977,7 +3089,7 @@ func (x *CompleteMigrationIncomingRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use CompleteMigrationIncomingRequest.ProtoReflect.Descriptor instead.
func (*CompleteMigrationIncomingRequest) Descriptor() ([]byte, []int) {
- return file_proto_worker_worker_proto_rawDescGZIP(), []int{50}
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{52}
}
func (x *CompleteMigrationIncomingRequest) GetSandboxId() string {
@@ -2995,7 +3107,7 @@ type CompleteMigrationIncomingResponse struct {
func (x *CompleteMigrationIncomingResponse) Reset() {
*x = CompleteMigrationIncomingResponse{}
- mi := &file_proto_worker_worker_proto_msgTypes[51]
+ mi := &file_proto_worker_worker_proto_msgTypes[53]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -3007,7 +3119,7 @@ func (x *CompleteMigrationIncomingResponse) String() string {
func (*CompleteMigrationIncomingResponse) ProtoMessage() {}
func (x *CompleteMigrationIncomingResponse) ProtoReflect() protoreflect.Message {
- mi := &file_proto_worker_worker_proto_msgTypes[51]
+ mi := &file_proto_worker_worker_proto_msgTypes[53]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -3020,7 +3132,7 @@ func (x *CompleteMigrationIncomingResponse) ProtoReflect() protoreflect.Message
// Deprecated: Use CompleteMigrationIncomingResponse.ProtoReflect.Descriptor instead.
func (*CompleteMigrationIncomingResponse) Descriptor() ([]byte, []int) {
- return file_proto_worker_worker_proto_rawDescGZIP(), []int{51}
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{53}
}
var File_proto_worker_worker_proto protoreflect.FileDescriptor
@@ -3248,7 +3360,14 @@ 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\"\xfd\x01\n" +
+ "\x18SetSandboxLimitsResponse\"5\n" +
+ "\x14PreCopyDrivesRequest\x12\x1d\n" +
+ "\n" +
+ "sandbox_id\x18\x01 \x01(\tR\tsandboxId\"[\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" +
"\x1fPrepareMigrationIncomingRequest\x12\x1d\n" +
"\n" +
"sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12\x1f\n" +
@@ -3259,7 +3378,9 @@ const file_proto_worker_worker_proto_rawDesc = "" +
"\tmemory_mb\x18\x05 \x01(\x05R\bmemoryMb\x12\x1d\n" +
"\n" +
"guest_port\x18\x06 \x01(\x05R\tguestPort\x12\x1a\n" +
- "\btemplate\x18\a \x01(\tR\btemplate\"d\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" +
" PrepareMigrationIncomingResponse\x12#\n" +
"\rincoming_addr\x18\x01 \x01(\tR\fincomingAddr\x12\x1b\n" +
"\thost_port\x18\x02 \x01(\x05R\bhostPort\"X\n" +
@@ -3271,7 +3392,7 @@ const file_proto_worker_worker_proto_rawDesc = "" +
" CompleteMigrationIncomingRequest\x12\x1d\n" +
"\n" +
"sandbox_id\x18\x01 \x01(\tR\tsandboxId\"#\n" +
- "!CompleteMigrationIncomingResponse2\xcf\x0f\n" +
+ "!CompleteMigrationIncomingResponse2\x9d\x10\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" +
@@ -3295,7 +3416,8 @@ const file_proto_worker_worker_proto_rawDesc = "" +
"\x11RestoreCheckpoint\x12 .worker.RestoreCheckpointRequest\x1a!.worker.RestoreCheckpointResponse\x12L\n" +
"\rBuildTemplate\x12\x1c.worker.BuildTemplateRequest\x1a\x1d.worker.BuildTemplateResponse\x12R\n" +
"\x0fGetSandboxStats\x12\x1e.worker.GetSandboxStatsRequest\x1a\x1f.worker.GetSandboxStatsResponse\x12U\n" +
- "\x10SetSandboxLimits\x12\x1f.worker.SetSandboxLimitsRequest\x1a .worker.SetSandboxLimitsResponse\x12m\n" +
+ "\x10SetSandboxLimits\x12\x1f.worker.SetSandboxLimitsRequest\x1a .worker.SetSandboxLimitsResponse\x12L\n" +
+ "\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"
@@ -3313,7 +3435,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, 56)
+var file_proto_worker_worker_proto_msgTypes = make([]protoimpl.MessageInfo, 58)
var file_proto_worker_worker_proto_goTypes = []any{
(ExecOutputChunk_Stream)(0), // 0: worker.ExecOutputChunk.Stream
(*CreateSandboxRequest)(nil), // 1: worker.CreateSandboxRequest
@@ -3362,26 +3484,28 @@ var file_proto_worker_worker_proto_goTypes = []any{
(*RestoreCheckpointResponse)(nil), // 44: worker.RestoreCheckpointResponse
(*SetSandboxLimitsRequest)(nil), // 45: worker.SetSandboxLimitsRequest
(*SetSandboxLimitsResponse)(nil), // 46: worker.SetSandboxLimitsResponse
- (*PrepareMigrationIncomingRequest)(nil), // 47: worker.PrepareMigrationIncomingRequest
- (*PrepareMigrationIncomingResponse)(nil), // 48: worker.PrepareMigrationIncomingResponse
- (*LiveMigrateRequest)(nil), // 49: worker.LiveMigrateRequest
- (*LiveMigrateResponse)(nil), // 50: worker.LiveMigrateResponse
- (*CompleteMigrationIncomingRequest)(nil), // 51: worker.CompleteMigrationIncomingRequest
- (*CompleteMigrationIncomingResponse)(nil), // 52: worker.CompleteMigrationIncomingResponse
- nil, // 53: worker.CreateSandboxRequest.EnvsEntry
- nil, // 54: worker.CreateSandboxRequest.SecretAllowedHostsEntry
- nil, // 55: worker.ExecCommandRequest.EnvsEntry
- nil, // 56: worker.ExecSessionCreateRequest.EnvsEntry
+ (*PreCopyDrivesRequest)(nil), // 47: worker.PreCopyDrivesRequest
+ (*PreCopyDrivesResponse)(nil), // 48: worker.PreCopyDrivesResponse
+ (*PrepareMigrationIncomingRequest)(nil), // 49: worker.PrepareMigrationIncomingRequest
+ (*PrepareMigrationIncomingResponse)(nil), // 50: worker.PrepareMigrationIncomingResponse
+ (*LiveMigrateRequest)(nil), // 51: worker.LiveMigrateRequest
+ (*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
}
var file_proto_worker_worker_proto_depIdxs = []int32{
- 53, // 0: worker.CreateSandboxRequest.envs:type_name -> worker.CreateSandboxRequest.EnvsEntry
- 54, // 1: worker.CreateSandboxRequest.secret_allowed_hosts:type_name -> worker.CreateSandboxRequest.SecretAllowedHostsEntry
+ 55, // 0: worker.CreateSandboxRequest.envs:type_name -> worker.CreateSandboxRequest.EnvsEntry
+ 56, // 1: worker.CreateSandboxRequest.secret_allowed_hosts:type_name -> worker.CreateSandboxRequest.SecretAllowedHostsEntry
6, // 2: worker.ListSandboxesResponse.sandboxes:type_name -> worker.GetSandboxResponse
- 55, // 3: worker.ExecCommandRequest.envs:type_name -> worker.ExecCommandRequest.EnvsEntry
+ 57, // 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
- 56, // 7: worker.ExecSessionCreateRequest.envs:type_name -> worker.ExecSessionCreateRequest.EnvsEntry
+ 58, // 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
@@ -3405,36 +3529,38 @@ var file_proto_worker_worker_proto_depIdxs = []int32{
30, // 28: worker.SandboxWorker.BuildTemplate:input_type -> worker.BuildTemplateRequest
39, // 29: worker.SandboxWorker.GetSandboxStats:input_type -> worker.GetSandboxStatsRequest
45, // 30: worker.SandboxWorker.SetSandboxLimits:input_type -> worker.SetSandboxLimitsRequest
- 47, // 31: worker.SandboxWorker.PrepareMigrationIncoming:input_type -> worker.PrepareMigrationIncomingRequest
- 49, // 32: worker.SandboxWorker.LiveMigrate:input_type -> worker.LiveMigrateRequest
- 51, // 33: worker.SandboxWorker.CompleteMigrationIncoming:input_type -> worker.CompleteMigrationIncomingRequest
- 2, // 34: worker.SandboxWorker.CreateSandbox:output_type -> worker.CreateSandboxResponse
- 4, // 35: worker.SandboxWorker.DestroySandbox:output_type -> worker.DestroySandboxResponse
- 6, // 36: worker.SandboxWorker.GetSandbox:output_type -> worker.GetSandboxResponse
- 8, // 37: worker.SandboxWorker.ListSandboxes:output_type -> worker.ListSandboxesResponse
- 10, // 38: worker.SandboxWorker.ExecCommand:output_type -> worker.ExecCommandResponse
- 11, // 39: worker.SandboxWorker.ExecCommandStream:output_type -> worker.ExecOutputChunk
- 13, // 40: worker.SandboxWorker.ReadFile:output_type -> worker.ReadFileResponse
- 15, // 41: worker.SandboxWorker.WriteFile:output_type -> worker.WriteFileResponse
- 18, // 42: worker.SandboxWorker.ListDir:output_type -> worker.ListDirResponse
- 20, // 43: worker.SandboxWorker.CreatePTY:output_type -> worker.CreatePTYResponse
- 23, // 44: worker.SandboxWorker.PTYStream:output_type -> worker.PTYOutput
- 33, // 45: worker.SandboxWorker.ExecSessionCreate:output_type -> worker.ExecSessionCreateResponse
- 35, // 46: worker.SandboxWorker.ExecSessionList:output_type -> worker.ExecSessionListResponse
- 38, // 47: worker.SandboxWorker.ExecSessionKill:output_type -> worker.ExecSessionKillResponse
- 25, // 48: worker.SandboxWorker.HibernateSandbox:output_type -> worker.HibernateSandboxResponse
- 27, // 49: worker.SandboxWorker.WakeSandbox:output_type -> worker.WakeSandboxResponse
- 29, // 50: worker.SandboxWorker.SaveAsTemplate:output_type -> worker.SaveAsTemplateResponse
- 42, // 51: worker.SandboxWorker.CreateCheckpoint:output_type -> worker.CreateCheckpointResponse
- 44, // 52: worker.SandboxWorker.RestoreCheckpoint:output_type -> worker.RestoreCheckpointResponse
- 31, // 53: worker.SandboxWorker.BuildTemplate:output_type -> worker.BuildTemplateResponse
- 40, // 54: worker.SandboxWorker.GetSandboxStats:output_type -> worker.GetSandboxStatsResponse
- 46, // 55: worker.SandboxWorker.SetSandboxLimits:output_type -> worker.SetSandboxLimitsResponse
- 48, // 56: worker.SandboxWorker.PrepareMigrationIncoming:output_type -> worker.PrepareMigrationIncomingResponse
- 50, // 57: worker.SandboxWorker.LiveMigrate:output_type -> worker.LiveMigrateResponse
- 52, // 58: worker.SandboxWorker.CompleteMigrationIncoming:output_type -> worker.CompleteMigrationIncomingResponse
- 34, // [34:59] is the sub-list for method output_type
- 9, // [9:34] is the sub-list for method input_type
+ 47, // 31: worker.SandboxWorker.PreCopyDrives:input_type -> worker.PreCopyDrivesRequest
+ 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
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
@@ -3455,7 +3581,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: 56,
+ NumMessages: 58,
NumExtensions: 0,
NumServices: 1,
},
diff --git a/proto/worker/worker.proto b/proto/worker/worker.proto
index 4eda2233..c777b467 100644
--- a/proto/worker/worker.proto
+++ b/proto/worker/worker.proto
@@ -39,6 +39,7 @@ service SandboxWorker {
rpc SetSandboxLimits(SetSandboxLimitsRequest) returns (SetSandboxLimitsResponse);
// Live migration between workers
+ rpc PreCopyDrives(PreCopyDrivesRequest) returns (PreCopyDrivesResponse);
rpc PrepareMigrationIncoming(PrepareMigrationIncomingRequest) returns (PrepareMigrationIncomingResponse);
rpc LiveMigrate(LiveMigrateRequest) returns (LiveMigrateResponse);
rpc CompleteMigrationIncoming(CompleteMigrationIncomingRequest) returns (CompleteMigrationIncomingResponse);
@@ -312,6 +313,15 @@ message SetSandboxLimitsRequest {
message SetSandboxLimitsResponse {}
// Live migration messages
+message PreCopyDrivesRequest {
+ string sandbox_id = 1;
+}
+
+message PreCopyDrivesResponse {
+ string rootfs_key = 1; // S3 key for rootfs qcow2
+ string workspace_key = 2; // S3 key for workspace qcow2
+}
+
message PrepareMigrationIncomingRequest {
string sandbox_id = 1;
string rootfs_path = 2; // local path to rootfs on target (pre-copied)
@@ -320,6 +330,8 @@ message PrepareMigrationIncomingRequest {
int32 memory_mb = 5;
int32 guest_port = 6;
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
}
message PrepareMigrationIncomingResponse {
diff --git a/proto/worker/worker_grpc.pb.go b/proto/worker/worker_grpc.pb.go
index 8df2045a..a75724a9 100644
--- a/proto/worker/worker_grpc.pb.go
+++ b/proto/worker/worker_grpc.pb.go
@@ -41,6 +41,7 @@ const (
SandboxWorker_BuildTemplate_FullMethodName = "/worker.SandboxWorker/BuildTemplate"
SandboxWorker_GetSandboxStats_FullMethodName = "/worker.SandboxWorker/GetSandboxStats"
SandboxWorker_SetSandboxLimits_FullMethodName = "/worker.SandboxWorker/SetSandboxLimits"
+ SandboxWorker_PreCopyDrives_FullMethodName = "/worker.SandboxWorker/PreCopyDrives"
SandboxWorker_PrepareMigrationIncoming_FullMethodName = "/worker.SandboxWorker/PrepareMigrationIncoming"
SandboxWorker_LiveMigrate_FullMethodName = "/worker.SandboxWorker/LiveMigrate"
SandboxWorker_CompleteMigrationIncoming_FullMethodName = "/worker.SandboxWorker/CompleteMigrationIncoming"
@@ -73,6 +74,7 @@ type SandboxWorkerClient interface {
GetSandboxStats(ctx context.Context, in *GetSandboxStatsRequest, opts ...grpc.CallOption) (*GetSandboxStatsResponse, error)
SetSandboxLimits(ctx context.Context, in *SetSandboxLimitsRequest, opts ...grpc.CallOption) (*SetSandboxLimitsResponse, error)
// Live migration between workers
+ PreCopyDrives(ctx context.Context, in *PreCopyDrivesRequest, opts ...grpc.CallOption) (*PreCopyDrivesResponse, error)
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)
@@ -318,6 +320,16 @@ func (c *sandboxWorkerClient) SetSandboxLimits(ctx context.Context, in *SetSandb
return out, nil
}
+func (c *sandboxWorkerClient) PreCopyDrives(ctx context.Context, in *PreCopyDrivesRequest, opts ...grpc.CallOption) (*PreCopyDrivesResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(PreCopyDrivesResponse)
+ err := c.cc.Invoke(ctx, SandboxWorker_PreCopyDrives_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
func (c *sandboxWorkerClient) PrepareMigrationIncoming(ctx context.Context, in *PrepareMigrationIncomingRequest, opts ...grpc.CallOption) (*PrepareMigrationIncomingResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(PrepareMigrationIncomingResponse)
@@ -375,6 +387,7 @@ type SandboxWorkerServer interface {
GetSandboxStats(context.Context, *GetSandboxStatsRequest) (*GetSandboxStatsResponse, error)
SetSandboxLimits(context.Context, *SetSandboxLimitsRequest) (*SetSandboxLimitsResponse, error)
// Live migration between workers
+ PreCopyDrives(context.Context, *PreCopyDrivesRequest) (*PreCopyDrivesResponse, error)
PrepareMigrationIncoming(context.Context, *PrepareMigrationIncomingRequest) (*PrepareMigrationIncomingResponse, error)
LiveMigrate(context.Context, *LiveMigrateRequest) (*LiveMigrateResponse, error)
CompleteMigrationIncoming(context.Context, *CompleteMigrationIncomingRequest) (*CompleteMigrationIncomingResponse, error)
@@ -454,6 +467,9 @@ func (UnimplementedSandboxWorkerServer) GetSandboxStats(context.Context, *GetSan
func (UnimplementedSandboxWorkerServer) SetSandboxLimits(context.Context, *SetSandboxLimitsRequest) (*SetSandboxLimitsResponse, error) {
return nil, status.Error(codes.Unimplemented, "method SetSandboxLimits not implemented")
}
+func (UnimplementedSandboxWorkerServer) PreCopyDrives(context.Context, *PreCopyDrivesRequest) (*PreCopyDrivesResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method PreCopyDrives not implemented")
+}
func (UnimplementedSandboxWorkerServer) PrepareMigrationIncoming(context.Context, *PrepareMigrationIncomingRequest) (*PrepareMigrationIncomingResponse, error) {
return nil, status.Error(codes.Unimplemented, "method PrepareMigrationIncoming not implemented")
}
@@ -862,6 +878,24 @@ func _SandboxWorker_SetSandboxLimits_Handler(srv interface{}, ctx context.Contex
return interceptor(ctx, in, info, handler)
}
+func _SandboxWorker_PreCopyDrives_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(PreCopyDrivesRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(SandboxWorkerServer).PreCopyDrives(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: SandboxWorker_PreCopyDrives_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(SandboxWorkerServer).PreCopyDrives(ctx, req.(*PreCopyDrivesRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
func _SandboxWorker_PrepareMigrationIncoming_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(PrepareMigrationIncomingRequest)
if err := dec(in); err != nil {
@@ -1003,6 +1037,10 @@ var SandboxWorker_ServiceDesc = grpc.ServiceDesc{
MethodName: "SetSandboxLimits",
Handler: _SandboxWorker_SetSandboxLimits_Handler,
},
+ {
+ MethodName: "PreCopyDrives",
+ Handler: _SandboxWorker_PreCopyDrives_Handler,
+ },
{
MethodName: "PrepareMigrationIncoming",
Handler: _SandboxWorker_PrepareMigrationIncoming_Handler,