Skip to content

An open-source, faster Devin alternative

TypeScript

golden shot

Brian Reardona9532a7555af
diff --git a/cmd/worker/main.go b/cmd/worker/main.go
index 48c02bc7..033dc5aa 100644
--- a/cmd/worker/main.go
+++ b/cmd/worker/main.go
@@ -52,6 +52,13 @@ func main() {
defer fcMgr.Close()
log.Println("opensandbox-worker: Firecracker VM manager initialized")
+ // Prepare golden snapshot for fast default VM creation (~500ms vs ~2s cold boot)
+ go func() {
+ if err := fcMgr.PrepareGoldenSnapshot(); err != nil {
+ log.Printf("opensandbox-worker: golden snapshot preparation failed: %v (cold boot fallback active)", err)
+ }
+ }()
+
// The Firecracker manager implements sandbox.Manager
var mgr sandbox.Manager = fcMgr
diff --git a/internal/api/commands.go b/internal/api/commands.go
index 6bba01e8..0099ebab 100644
--- a/internal/api/commands.go
+++ b/internal/api/commands.go
@@ -77,6 +77,24 @@ func (s *Server) runCommand(c echo.Context) error {
}
func (s *Server) runCommandRemote(c echo.Context, sandboxID string) error {
+ // Wait for sandbox if it's being created asynchronously
+ if v, ok := s.pendingCreates.Load(sandboxID); ok {
+ pending := v.(*pendingCreate)
+ select {
+ case <-pending.ready:
+ if pending.err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": "sandbox creation failed: " + pending.err.Error(),
+ })
+ }
+ s.pendingCreates.Delete(sandboxID)
+ case <-c.Request().Context().Done():
+ return c.JSON(http.StatusGatewayTimeout, map[string]string{
+ "error": "timed out waiting for sandbox creation",
+ })
+ }
+ }
+
if s.store == nil {
return c.JSON(http.StatusServiceUnavailable, map[string]string{
"error": "database not configured",
diff --git a/internal/api/router.go b/internal/api/router.go
index 4d6f5951..2b4611b1 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -7,6 +7,7 @@ import (
"os"
"path/filepath"
"strings"
+ "sync"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
@@ -43,6 +44,13 @@ type Server struct {
sandboxDomain string // base domain for sandbox subdomains
ecrConfig *ecr.Config // nil if ECR not configured
cfClient *cloudflare.Client // nil if Cloudflare not configured
+ pendingCreates sync.Map // map[sandboxID]*pendingCreate — async sandbox creation tracking
+}
+
+// pendingCreate tracks an async sandbox creation.
+type pendingCreate struct {
+ ready chan struct{} // closed when creation completes
+ err error // set before closing ready
}
// ServerOpts holds optional dependencies for the API server.
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index ffbec1a7..88c6d831 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -820,41 +820,45 @@ func (s *Server) createCheckpoint(c echo.Context) error {
return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to create checkpoint: " + err.Error()})
}
- // Dispatch CreateCheckpoint gRPC to worker (server mode) or call manager directly (combined mode)
+ // Dispatch checkpoint creation in background — return immediately with status "processing".
+ // The heavy work (SyncFS + pause + memory snapshot + drive copy + resume + S3 upload)
+ // runs async. Clients poll listCheckpoints for status=ready.
if s.workerRegistry != nil {
grpcClient, err := s.workerRegistry.GetWorkerClient(session.WorkerID)
if err != nil {
return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "worker not available: " + err.Error()})
}
- grpcCtx, cancel := context.WithTimeout(ctx, 2*time.Minute)
- defer cancel()
-
- grpcResp, err := grpcClient.CreateCheckpoint(grpcCtx, &pb.CreateCheckpointRequest{
- SandboxId: sandboxID,
- CheckpointId: checkpointID.String(),
- })
- if err != nil {
- return c.JSON(http.StatusInternalServerError, map[string]string{"error": "create checkpoint failed: " + err.Error()})
- }
+ go func() {
+ grpcCtx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
+ defer cancel()
- // Mark checkpoint ready on the server side — the gRPC call completes after
- // the reflink copy (checkpoint is locally usable), S3 upload is async on the worker.
- _ = s.store.SetCheckpointReady(ctx, checkpointID, grpcResp.RootfsS3Key, grpcResp.WorkspaceS3Key, 0)
- cp.Status = "ready"
- cp.RootfsS3Key = &grpcResp.RootfsS3Key
- cp.WorkspaceS3Key = &grpcResp.WorkspaceS3Key
+ grpcResp, err := grpcClient.CreateCheckpoint(grpcCtx, &pb.CreateCheckpointRequest{
+ SandboxId: sandboxID,
+ CheckpointId: checkpointID.String(),
+ })
+ if err != nil {
+ log.Printf("api: async checkpoint %s failed: %v", checkpointID, err)
+ _ = s.store.SetCheckpointFailed(context.Background(), checkpointID, err.Error())
+ return
+ }
+ _ = s.store.SetCheckpointReady(context.Background(), checkpointID, grpcResp.RootfsS3Key, grpcResp.WorkspaceS3Key, 0)
+ log.Printf("api: checkpoint %s ready", checkpointID)
+ }()
} else if s.manager != nil {
- rootfsKey, workspaceKey, err := s.manager.CreateCheckpoint(ctx, sandboxID, checkpointID.String(), s.checkpointStore, func() {
- // Async callback when S3 upload completes (no-op here; we mark ready below)
- })
- if err != nil {
- return c.JSON(http.StatusInternalServerError, map[string]string{"error": "create checkpoint failed: " + err.Error()})
- }
- _ = s.store.SetCheckpointReady(ctx, checkpointID, rootfsKey, workspaceKey, 0)
- cp.Status = "ready"
- cp.RootfsS3Key = &rootfsKey
- cp.WorkspaceS3Key = &workspaceKey
+ go func() {
+ bgCtx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
+ defer cancel()
+
+ rootfsKey, workspaceKey, err := s.manager.CreateCheckpoint(bgCtx, sandboxID, checkpointID.String(), s.checkpointStore, func() {})
+ if err != nil {
+ log.Printf("api: async checkpoint %s failed: %v", checkpointID, err)
+ _ = s.store.SetCheckpointFailed(context.Background(), checkpointID, err.Error())
+ return
+ }
+ _ = s.store.SetCheckpointReady(context.Background(), checkpointID, rootfsKey, workspaceKey, 0)
+ log.Printf("api: checkpoint %s ready", checkpointID)
+ }()
} else {
return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)
}
@@ -936,35 +940,50 @@ func (s *Server) restoreCheckpoint(c echo.Context) error {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "checkpoint is not ready (status: " + cp.Status + ")"})
}
- // Dispatch RestoreCheckpoint gRPC to worker or call manager directly
+ // Dispatch restore in background — return immediately.
+ // Commands will block until restore completes.
+ pending := &pendingCreate{ready: make(chan struct{})}
+ s.pendingCreates.Store(sandboxID, pending)
+
if s.workerRegistry != nil {
grpcClient, err := s.workerRegistry.GetWorkerClient(session.WorkerID)
if err != nil {
+ s.pendingCreates.Delete(sandboxID)
return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "worker not available: " + err.Error()})
}
- grpcCtx, cancel := context.WithTimeout(ctx, 2*time.Minute)
- defer cancel()
+ go func() {
+ grpcCtx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
+ defer cancel()
- _, err = grpcClient.RestoreCheckpoint(grpcCtx, &pb.RestoreCheckpointRequest{
- SandboxId: sandboxID,
- CheckpointId: checkpointID.String(),
- })
- if err != nil {
- return c.JSON(http.StatusInternalServerError, map[string]string{"error": "restore checkpoint failed: " + err.Error()})
- }
+ _, restoreErr := grpcClient.RestoreCheckpoint(grpcCtx, &pb.RestoreCheckpointRequest{
+ SandboxId: sandboxID,
+ CheckpointId: checkpointID.String(),
+ })
+ if restoreErr != nil {
+ log.Printf("api: async restore %s/%s failed: %v", sandboxID, checkpointID, restoreErr)
+ }
+ pending.err = restoreErr
+ close(pending.ready)
+ }()
} else if s.manager != nil {
- if err := s.manager.RestoreFromCheckpoint(ctx, sandboxID, checkpointID.String()); err != nil {
- return c.JSON(http.StatusInternalServerError, map[string]string{"error": "restore checkpoint failed: " + err.Error()})
- }
+ go func() {
+ restoreErr := s.manager.RestoreFromCheckpoint(context.Background(), sandboxID, checkpointID.String())
+ if restoreErr != nil {
+ log.Printf("api: async restore %s/%s failed: %v", sandboxID, checkpointID, restoreErr)
+ }
+ pending.err = restoreErr
+ close(pending.ready)
+ }()
} else {
+ s.pendingCreates.Delete(sandboxID)
return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)
}
return c.JSON(http.StatusOK, map[string]string{
"sandboxId": sandboxID,
"checkpointId": checkpointID.String(),
- "status": "restored",
+ "status": "restoring",
})
}
@@ -1022,103 +1041,126 @@ func (s *Server) createFromCheckpoint(c echo.Context) error {
timeout = 300
}
- // Create new sandbox using checkpoint drives (same flow as creating from template)
- if s.workerRegistry != nil {
- // Server mode: pick a worker and dispatch via gRPC
- region := s.region
- if region == "" {
- region = "iad"
- }
+ // Unified async fork: return immediately, boot VM in background.
+ // First command from SDK will block until VM is ready.
- worker, grpcClient, err := s.workerRegistry.GetLeastLoadedWorker(region)
- if err != nil {
- return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "no workers available: " + err.Error()})
- }
+ // Pre-generate sandbox ID
+ sandboxID := "sb-" + uuid.New().String()[:8]
- grpcCtx, cancel := context.WithTimeout(ctx, 120*time.Second)
- defer cancel()
+ // Determine execution target
+ region := s.region
+ if region == "" {
+ region = "iad"
+ }
+ var workerID string
+ var grpcClient pb.SandboxWorkerClient
- grpcResp, err := grpcClient.CreateSandbox(grpcCtx, &pb.CreateSandboxRequest{
- Template: originalCfg.Template,
- Timeout: int32(timeout),
- Envs: originalCfg.Envs,
- MemoryMb: int32(originalCfg.MemoryMB),
- CpuCount: int32(originalCfg.CpuCount),
- NetworkEnabled: originalCfg.NetworkEnabled,
- Port: int32(originalCfg.Port),
- TemplateRootfsKey: *cp.RootfsS3Key,
- TemplateWorkspaceKey: *cp.WorkspaceS3Key,
- })
+ if s.workerRegistry != nil {
+ // Server mode: pick a worker
+ worker, client, err := s.workerRegistry.GetLeastLoadedWorker(region)
if err != nil {
- return c.JSON(http.StatusInternalServerError, map[string]string{"error": "create from checkpoint failed: " + err.Error()})
- }
-
- // Issue JWT
- var token string
- if s.jwtIssuer != nil {
- t, err := s.jwtIssuer.IssueSandboxToken(orgID, grpcResp.SandboxId, worker.ID, 24*time.Hour)
- if err == nil {
- token = t
- }
- }
-
- // Record session
- template := originalCfg.Template
- if template == "" {
- template = "default"
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "no workers available: " + err.Error()})
}
- cfgJSON, _ := json.Marshal(originalCfg)
- metadataJSON, _ := json.Marshal(originalCfg.Metadata)
- _, _ = s.store.CreateSandboxSession(ctx, grpcResp.SandboxId, orgID, nil, template, region, worker.ID, cfgJSON, metadataJSON)
-
- return c.JSON(http.StatusCreated, map[string]interface{}{
- "sandboxID": grpcResp.SandboxId,
- "connectURL": worker.HTTPAddr,
- "token": token,
- "status": grpcResp.Status,
- "region": region,
- "workerID": worker.ID,
- "fromCheckpointId": checkpointID.String(),
- })
- }
-
- // Combined mode: create locally using checkpoint drives
- if s.manager == nil {
+ workerID = worker.ID
+ grpcClient = client
+ } else if s.manager != nil {
+ // Combined mode: local execution
+ workerID = s.workerID
+ } else {
return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)
}
- cfg := originalCfg
- cfg.Timeout = timeout
- cfg.TemplateRootfsKey = *cp.RootfsS3Key
- cfg.TemplateWorkspaceKey = *cp.WorkspaceS3Key
-
- sb, err := s.manager.Create(ctx, cfg)
- if err != nil {
- return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
- }
+ // Register pending create — commands will wait until ready
+ pending := &pendingCreate{ready: make(chan struct{})}
+ s.pendingCreates.Store(sandboxID, pending)
+ // Also register with sandbox router if available (combined mode)
if s.router != nil {
- s.router.Register(sb.ID, time.Duration(timeout)*time.Second)
+ s.router.RegisterCreating(sandboxID, time.Duration(timeout)*time.Second)
}
+ // Issue JWT immediately
+ var token string
if s.jwtIssuer != nil {
- token, err := s.jwtIssuer.IssueSandboxToken(orgID, sb.ID, s.workerID, 24*time.Hour)
+ t, err := s.jwtIssuer.IssueSandboxToken(orgID, sandboxID, workerID, 24*time.Hour)
if err == nil {
- sb.Token = token
+ token = t
}
}
+ // Record session immediately
if s.store != nil {
template := originalCfg.Template
if template == "" {
template = "default"
}
- cfgJSON, _ := json.Marshal(cfg)
- metadataJSON, _ := json.Marshal(cfg.Metadata)
- _, _ = s.store.CreateSandboxSession(ctx, sb.ID, orgID, nil, template, s.region, s.workerID, cfgJSON, metadataJSON)
+ cfgJSON, _ := json.Marshal(originalCfg)
+ metadataJSON, _ := json.Marshal(originalCfg.Metadata)
+ _, _ = s.store.CreateSandboxSession(ctx, sandboxID, orgID, nil, template, region, workerID, cfgJSON, metadataJSON)
}
- return c.JSON(http.StatusCreated, sb)
+ // Boot VM in background
+ go func() {
+ createCtx, cancel := context.WithTimeout(context.Background(), 120*time.Second)
+ defer cancel()
+
+ var createErr error
+
+ if grpcClient != nil {
+ // Server mode: dispatch to worker via gRPC
+ _, createErr = grpcClient.CreateSandbox(createCtx, &pb.CreateSandboxRequest{
+ Template: originalCfg.Template,
+ Timeout: int32(timeout),
+ Envs: originalCfg.Envs,
+ MemoryMb: int32(originalCfg.MemoryMB),
+ CpuCount: int32(originalCfg.CpuCount),
+ NetworkEnabled: originalCfg.NetworkEnabled,
+ Port: int32(originalCfg.Port),
+ TemplateRootfsKey: *cp.RootfsS3Key,
+ TemplateWorkspaceKey: *cp.WorkspaceS3Key,
+ CheckpointId: checkpointID.String(),
+ SandboxId: sandboxID,
+ })
+ } else {
+ // Combined mode: create locally
+ cfg := originalCfg
+ cfg.Timeout = timeout
+ cfg.TemplateRootfsKey = *cp.RootfsS3Key
+ cfg.TemplateWorkspaceKey = *cp.WorkspaceS3Key
+ cfg.SandboxID = sandboxID
+
+ forkMgr, hasFork := s.manager.(interface {
+ ForkFromCheckpoint(ctx context.Context, checkpointID string, cfg types.SandboxConfig) (*types.Sandbox, error)
+ })
+ if hasFork {
+ _, createErr = forkMgr.ForkFromCheckpoint(createCtx, checkpointID.String(), cfg)
+ } else {
+ _, createErr = s.manager.Create(createCtx, cfg)
+ }
+ }
+
+ if createErr != nil {
+ log.Printf("api: async fork %s failed: %v", sandboxID, createErr)
+ }
+
+ // Signal completion
+ pending.err = createErr
+ close(pending.ready)
+
+ // Also signal router if available (combined mode)
+ if s.router != nil {
+ s.router.MarkCreated(sandboxID, createErr)
+ }
+ }()
+
+ return c.JSON(http.StatusCreated, map[string]interface{}{
+ "sandboxID": sandboxID,
+ "status": "creating",
+ "token": token,
+ "region": region,
+ "workerID": workerID,
+ "fromCheckpointId": checkpointID.String(),
+ })
}
// deleteCheckpoint deletes a checkpoint.
diff --git a/internal/db/store.go b/internal/db/store.go
index 858c5827..479c5af8 100644
--- a/internal/db/store.go
+++ b/internal/db/store.go
@@ -767,6 +767,14 @@ func (s *Store) SetCheckpointReady(ctx context.Context, checkpointID uuid.UUID,
return err
}
+// SetCheckpointFailed marks a checkpoint as failed.
+func (s *Store) SetCheckpointFailed(ctx context.Context, checkpointID uuid.UUID, reason string) error {
+ _, err := s.pool.Exec(ctx,
+ `UPDATE sandbox_checkpoints SET status = 'failed' WHERE id = $1`,
+ checkpointID)
+ return err
+}
+
// GetCheckpoint returns a checkpoint by ID.
func (s *Store) GetCheckpoint(ctx context.Context, checkpointID uuid.UUID) (*Checkpoint, error) {
cp := &Checkpoint{}
diff --git a/internal/firecracker/api.go b/internal/firecracker/api.go
index 80768666..f5637c9c 100644
--- a/internal/firecracker/api.go
+++ b/internal/firecracker/api.go
@@ -29,7 +29,8 @@ func NewFirecrackerClient(socketPath string) *FirecrackerClient {
}
return &FirecrackerClient{
socketPath: socketPath,
- httpClient: &http.Client{Transport: transport, Timeout: 30 * time.Second},
+ // No global timeout — per-request timeouts are set via context in doRequest/doRequestWithTimeout.
+ httpClient: &http.Client{Transport: transport},
}
}
@@ -65,6 +66,15 @@ func (c *FirecrackerClient) PutDrive(driveID, pathOnHost string, isRootDevice, i
return c.putWithID("/drives", driveID, body)
}
+// PatchDrive updates a drive's path_on_host. Works in Paused state after LoadSnapshot.
+func (c *FirecrackerClient) PatchDrive(driveID, pathOnHost string) error {
+ body := map[string]interface{}{
+ "drive_id": driveID,
+ "path_on_host": pathOnHost,
+ }
+ return c.patch("/drives/"+driveID, body)
+}
+
// PutNetworkInterface attaches a network interface.
func (c *FirecrackerClient) PutNetworkInterface(ifaceID, guestMAC, hostDevName string) error {
body := map[string]interface{}{
@@ -119,13 +129,14 @@ func (c *FirecrackerClient) ResumeVM() error {
// CreateSnapshot creates a full VM snapshot (memory + device state).
// The VM must be paused before calling this.
+// Uses a 5-minute timeout since memory dump can take a while on slower storage.
func (c *FirecrackerClient) CreateSnapshot(snapshotPath, memFilePath string) error {
body := map[string]string{
"snapshot_type": "Full",
"snapshot_path": snapshotPath,
"mem_file_path": memFilePath,
}
- return c.put("/snapshot/create", body)
+ return c.doRequestWithTimeout(http.MethodPut, "/snapshot/create", body, 5*time.Minute)
}
// LoadSnapshot restores a VM from a snapshot.
@@ -155,13 +166,16 @@ func (c *FirecrackerClient) patch(path string, body interface{}) error {
return c.doRequest(http.MethodPatch, path, body)
}
-func (c *FirecrackerClient) doRequest(method, path string, body interface{}) error {
+func (c *FirecrackerClient) doRequestWithTimeout(method, path string, body interface{}, timeout time.Duration) error {
jsonBody, err := json.Marshal(body)
if err != nil {
return fmt.Errorf("marshal request body: %w", err)
}
- req, err := http.NewRequest(method, "http://localhost"+path, bytes.NewReader(jsonBody))
+ ctx, cancel := context.WithTimeout(context.Background(), timeout)
+ defer cancel()
+
+ req, err := http.NewRequestWithContext(ctx, method, "http://localhost"+path, bytes.NewReader(jsonBody))
if err != nil {
return fmt.Errorf("create request: %w", err)
}
@@ -180,3 +194,7 @@ func (c *FirecrackerClient) doRequest(method, path string, body interface{}) err
return nil
}
+
+func (c *FirecrackerClient) doRequest(method, path string, body interface{}) error {
+ return c.doRequestWithTimeout(method, path, body, 30*time.Second)
+}
diff --git a/internal/firecracker/manager.go b/internal/firecracker/manager.go
index 67561835..9f25a5f0 100644
--- a/internal/firecracker/manager.go
+++ b/internal/firecracker/manager.go
@@ -49,6 +49,7 @@ type VMInstance struct {
guestMAC string // e.g., "AA:FC:00:00:2d:31"
guestCID uint32 // vsock CID
bootArgs string // kernel boot args
+ restoring chan struct{} // closed when an in-progress restore completes; nil when not restoring
}
// SandboxMeta is persisted to sandbox-meta.json in each sandbox directory.
@@ -74,6 +75,14 @@ type Config struct {
DefaultPort int // default guest port to expose (default: 80)
}
+// GoldenSnapshot holds the pre-booted default VM snapshot for fast creation.
+// Stored at {DataDir}/golden-snapshot/default/ with rootfs, workspace, mem, vmstate.
+type GoldenSnapshot struct {
+ Dir string // path to golden snapshot directory
+ Meta SnapshotMeta // metadata from the golden VM
+ Ready bool // true if golden snapshot is available
+}
+
// Manager implements sandbox.Manager using Firecracker microVMs.
type Manager struct {
cfg Config
@@ -83,6 +92,9 @@ type Manager struct {
vms map[string]*VMInstance
nextCID uint32 // next guest CID to assign (starts at 3, 0-2 are reserved)
uploadWg sync.WaitGroup // tracks in-flight async S3 uploads
+
+ goldenMu sync.RWMutex
+ golden *GoldenSnapshot // pre-booted default VM snapshot for fast creation
}
// NewManager creates a new Firecracker-backed sandbox manager.
@@ -146,25 +158,35 @@ func (m *Manager) allocateCID() uint32 {
// Create launches a new Firecracker microVM.
func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (*types.Sandbox, error) {
- id := "sb-" + uuid.New().String()[:8]
+ id := cfg.SandboxID
+ if id == "" {
+ id = "sb-" + uuid.New().String()[:8]
+ }
return m.createWithID(ctx, id, cfg)
}
// createWithID is the internal implementation of Create that accepts a specific sandbox ID.
// Used by Create (with a new UUID) and RestoreFromCheckpoint (with the existing ID).
func (m *Manager) createWithID(ctx context.Context, id string, cfg types.SandboxConfig) (*types.Sandbox, error) {
+ // Try golden snapshot for default template VMs (avoids cold boot, ~500ms vs ~2s)
+ template := cfg.Template
+ if template == "" || template == "base" {
+ template = "default"
+ }
+ if template == "default" && cfg.TemplateRootfsKey == "" {
+ if sb, err := m.createFromGoldenSnapshot(ctx, id, cfg); err == nil {
+ return sb, nil
+ } else if err != errNoGoldenSnapshot {
+ log.Printf("firecracker: golden snapshot create failed for %s: %v, falling back to cold boot", id, err)
+ }
+ }
+
sandboxDir := filepath.Join(m.cfg.DataDir, "sandboxes", id)
if err := os.MkdirAll(sandboxDir, 0755); err != nil {
return nil, fmt.Errorf("mkdir sandbox dir: %w", err)
}
- // Resolve template name (used for logging and cold-boot recovery)
- template := cfg.Template
- if template == "" || template == "base" {
- template = "default"
- }
-
rootfsPath := filepath.Join(sandboxDir, "rootfs.ext4")
workspacePath := filepath.Join(sandboxDir, "workspace.ext4")
@@ -615,7 +637,7 @@ func (m *Manager) HibernateAll(ctx context.Context, checkpointStore *storage.Che
// Exec runs a command in the VM via the agent.
func (m *Manager) Exec(ctx context.Context, sandboxID string, cfg types.ProcessConfig) (*types.ProcessResult, error) {
- vm, err := m.getVM(sandboxID)
+ vm, err := m.getReadyVM(ctx, sandboxID)
if err != nil {
return nil, err
}
@@ -653,7 +675,7 @@ func (m *Manager) Exec(ctx context.Context, sandboxID string, cfg types.ProcessC
// ReadFile reads a file from the VM.
func (m *Manager) ReadFile(ctx context.Context, sandboxID, path string) (string, error) {
- vm, err := m.getVM(sandboxID)
+ vm, err := m.getReadyVM(ctx, sandboxID)
if err != nil {
return "", err
}
@@ -666,7 +688,7 @@ func (m *Manager) ReadFile(ctx context.Context, sandboxID, path string) (string,
// WriteFile writes a file in the VM.
func (m *Manager) WriteFile(ctx context.Context, sandboxID, path, content string) error {
- vm, err := m.getVM(sandboxID)
+ vm, err := m.getReadyVM(ctx, sandboxID)
if err != nil {
return err
}
@@ -675,7 +697,7 @@ func (m *Manager) WriteFile(ctx context.Context, sandboxID, path, content string
// ListDir lists a directory in the VM.
func (m *Manager) ListDir(ctx context.Context, sandboxID, path string) ([]types.EntryInfo, error) {
- vm, err := m.getVM(sandboxID)
+ vm, err := m.getReadyVM(ctx, sandboxID)
if err != nil {
return nil, err
}
@@ -697,7 +719,7 @@ func (m *Manager) ListDir(ctx context.Context, sandboxID, path string) ([]types.
// MakeDir creates a directory in the VM.
func (m *Manager) MakeDir(ctx context.Context, sandboxID, path string) error {
- vm, err := m.getVM(sandboxID)
+ vm, err := m.getReadyVM(ctx, sandboxID)
if err != nil {
return err
}
@@ -706,7 +728,7 @@ func (m *Manager) MakeDir(ctx context.Context, sandboxID, path string) error {
// Remove removes a file/directory in the VM.
func (m *Manager) Remove(ctx context.Context, sandboxID, path string) error {
- vm, err := m.getVM(sandboxID)
+ vm, err := m.getReadyVM(ctx, sandboxID)
if err != nil {
return err
}
@@ -715,7 +737,7 @@ func (m *Manager) Remove(ctx context.Context, sandboxID, path string) error {
// Exists checks if a path exists in the VM.
func (m *Manager) Exists(ctx context.Context, sandboxID, path string) (bool, error) {
- vm, err := m.getVM(sandboxID)
+ vm, err := m.getReadyVM(ctx, sandboxID)
if err != nil {
return false, err
}
@@ -724,7 +746,7 @@ func (m *Manager) Exists(ctx context.Context, sandboxID, path string) (bool, err
// Stat returns file metadata from the VM.
func (m *Manager) Stat(ctx context.Context, sandboxID, path string) (*types.FileInfo, error) {
- vm, err := m.getVM(sandboxID)
+ vm, err := m.getReadyVM(ctx, sandboxID)
if err != nil {
return nil, err
}
@@ -744,7 +766,7 @@ func (m *Manager) Stat(ctx context.Context, sandboxID, path string) (*types.File
// Stats returns live resource usage from the VM.
func (m *Manager) Stats(ctx context.Context, sandboxID string) (*sandbox.SandboxStats, error) {
- vm, err := m.getVM(sandboxID)
+ vm, err := m.getReadyVM(ctx, sandboxID)
if err != nil {
return nil, err
}
@@ -843,6 +865,34 @@ func (m *Manager) getVM(id string) (*VMInstance, error) {
return vm, nil
}
+// getReadyVM returns a VM that is ready for agent operations.
+// If the VM is currently being restored, it waits for the restore to complete.
+func (m *Manager) getReadyVM(ctx context.Context, id string) (*VMInstance, error) {
+ vm, err := m.getVM(id)
+ if err != nil {
+ return nil, err
+ }
+
+ // Wait for in-progress restore to complete
+ if vm.restoring != nil {
+ select {
+ case <-vm.restoring:
+ // Restore finished — re-fetch VM (may have been replaced)
+ vm, err = m.getVM(id)
+ if err != nil {
+ return nil, err
+ }
+ case <-ctx.Done():
+ return nil, fmt.Errorf("sandbox %s: timed out waiting for restore", id)
+ }
+ }
+
+ if vm.agent == nil {
+ return nil, fmt.Errorf("sandbox %s: agent not available", id)
+ }
+ return vm, nil
+}
+
// vmToSandbox converts a VMInstance to a types.Sandbox.
func vmToSandbox(vm *VMInstance) *types.Sandbox {
return &types.Sandbox{
diff --git a/internal/firecracker/network.go b/internal/firecracker/network.go
index 5b417006..ea3b1ea1 100644
--- a/internal/firecracker/network.go
+++ b/internal/firecracker/network.go
@@ -64,7 +64,7 @@ func (a *SubnetAllocator) Allocate() (*NetworkConfig, error) {
hostIP := fmt.Sprintf("172.16.%d.%d", b2, b3+1)
guestIP := fmt.Sprintf("172.16.%d.%d", b2, b3+2)
- tapName := fmt.Sprintf("fc-tap%d", block)
+ tapName := fmt.Sprintf("fc-tap%07d", block)
return &NetworkConfig{
TAPName: tapName,
diff --git a/internal/firecracker/snapshot.go b/internal/firecracker/snapshot.go
index bd7e2acf..e3cb2ea8 100644
--- a/internal/firecracker/snapshot.go
+++ b/internal/firecracker/snapshot.go
@@ -1,7 +1,9 @@
package firecracker
import (
+ "bytes"
"context"
+ "encoding/binary"
"encoding/json"
"fmt"
"io"
@@ -12,10 +14,12 @@ import (
"strings"
"time"
+ "github.com/google/uuid"
"github.com/opensandbox/opensandbox/internal/sandbox"
"github.com/opensandbox/opensandbox/internal/sparse"
"github.com/opensandbox/opensandbox/internal/storage"
"github.com/opensandbox/opensandbox/pkg/types"
+ pb "github.com/opensandbox/opensandbox/proto/agent"
)
// SnapshotMeta holds metadata persisted alongside snapshot files.
@@ -864,9 +868,16 @@ func (m *Manager) CheckpointCachePath(checkpointID, filename string) string {
return ""
}
-// CreateCheckpoint snapshots a running sandbox's drives (rootfs + workspace) for later restore.
-// The VM is briefly paused (~10-50ms) during file copy then resumed. Archive upload is async.
+// CreateCheckpoint snapshots a running sandbox's state for later restore.
+// The VM is briefly paused during memory snapshot + drive reflink then resumed. Archive upload is async.
// Returns the pre-computed S3 keys immediately. onReady is called when the async upload finishes.
+//
+// SyncFS is intentionally skipped: the memory snapshot captures the guest kernel's entire page
+// cache, including all dirty (unflushed) data. On warm restore, the guest resumes with its full
+// page cache intact — no data is lost regardless of how much dirty data existed at snapshot time.
+// For cold boot fallback (no memory snapshot), unflushed data would be lost, equivalent to crash
+// recovery (ext4 journaling handles consistency). Skipping SyncFS eliminates the biggest latency
+// contributor: flushing 10GB+ of dirty data to disk could take 20-30s on EBS gp3.
func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID string, checkpointStore *storage.CheckpointStore, onReady func()) (rootfsKey, workspaceKey string, err error) {
vm, err := m.getVM(sandboxID)
if err != nil {
@@ -889,13 +900,12 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID
cachedRootfs := filepath.Join(cacheDir, "rootfs.ext4")
cachedWorkspace := filepath.Join(cacheDir, "workspace.ext4")
- // Step 1: SyncFS (agent stays alive)
+ // Step 1: Flush workspace data to disk (required for cold boot forks that don't use memory snapshot).
+ // SyncFS ensures the ext4 filesystem is consistent on disk before we copy it.
if vm.agent != nil {
- syncCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
- if syncErr := vm.agent.SyncFS(syncCtx); syncErr != nil {
- log.Printf("firecracker: CreateCheckpoint %s: SyncFS warning: %v", vm.ID, syncErr)
+ if syncErr := vm.agent.SyncFS(ctx); syncErr != nil {
+ log.Printf("firecracker: CreateCheckpoint %s: SyncFS failed: %v (unflushed data may be lost in cold boot forks)", vm.ID, syncErr)
}
- cancel()
}
// Step 2: Close gRPC connection (vsock must be inactive before pause)
@@ -914,6 +924,38 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID
}
log.Printf("firecracker: CreateCheckpoint %s/%s: VM paused (%dms)", vm.ID, checkpointID, time.Since(t0).Milliseconds())
+ // Step 3: Create memory snapshot (best-effort — enables warm restore, captures dirty page cache)
+ snapshotDir := filepath.Join(cacheDir, "snapshot")
+ if mkErr := os.MkdirAll(snapshotDir, 0755); mkErr != nil {
+ log.Printf("firecracker: CreateCheckpoint %s/%s: mkdir snapshot dir failed: %v (warm restore will be unavailable)", vm.ID, checkpointID, mkErr)
+ } else {
+ memFile := filepath.Join(snapshotDir, "mem")
+ vmstateFile := filepath.Join(snapshotDir, "vmstate")
+ if snapErr := vm.fcClient.CreateSnapshot(vmstateFile, memFile); snapErr != nil {
+ log.Printf("firecracker: CreateCheckpoint %s/%s: memory snapshot failed: %v (warm restore will be unavailable)", vm.ID, checkpointID, snapErr)
+ os.RemoveAll(snapshotDir)
+ } else {
+ // Write snapshot metadata (reuse SnapshotMeta from hibernate)
+ meta := &SnapshotMeta{
+ SandboxID: vm.ID,
+ Network: vm.network,
+ GuestCID: vm.guestCID,
+ GuestMAC: vm.guestMAC,
+ BootArgs: vm.bootArgs,
+ RootfsPath: filepath.Join(vm.sandboxDir, "rootfs.ext4"),
+ WorkspacePath: filepath.Join(vm.sandboxDir, "workspace.ext4"),
+ VsockPath: vm.vsockPath,
+ CpuCount: vm.CpuCount,
+ MemoryMB: vm.MemoryMB,
+ Template: vm.Template,
+ GuestPort: vm.GuestPort,
+ }
+ metaJSON, _ := json.Marshal(meta)
+ _ = os.WriteFile(filepath.Join(snapshotDir, "snapshot-meta.json"), metaJSON, 0644)
+ log.Printf("firecracker: CreateCheckpoint %s/%s: memory snapshot captured (%dms)", vm.ID, checkpointID, time.Since(t0).Milliseconds())
+ }
+ }
+
// Step 4: Copy drive files while VM is paused (drives are stable)
copyErr := copyFileReflink(srcRootfs, cachedRootfs)
if copyErr == nil {
@@ -952,6 +994,11 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID
m.uploadWg.Add(1)
go func() {
defer m.uploadWg.Done()
+ defer func() {
+ if r := recover(); r != nil {
+ log.Printf("firecracker: checkpoint %s: upload goroutine panic: %v", checkpointID, r)
+ }
+ }()
uploadCtx, cancel := context.WithTimeout(context.Background(), 15*time.Minute)
defer cancel()
@@ -978,19 +1025,24 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID
}
// RestoreFromCheckpoint reverts a running sandbox to a checkpoint.
-// The current VM is killed, drives are replaced with checkpoint copies, and a new VM is cold booted.
-// The sandbox ID stays the same.
+// Attempts warm restore (LoadSnapshot) if a memory snapshot exists in the checkpoint cache.
+// Falls back to cold boot if warm restore fails or no snapshot is available.
func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpointID string) error {
vm, err := m.getVM(sandboxID)
if err != nil {
return err
}
+ // Signal that this VM is restoring — Exec and other operations will wait on this channel
+ restoreCh := make(chan struct{})
+ vm.restoring = restoreCh
+ defer close(restoreCh)
+
cacheDir := m.checkpointCacheDir(checkpointID)
cachedRootfs := filepath.Join(cacheDir, "rootfs.ext4")
cachedWorkspace := filepath.Join(cacheDir, "workspace.ext4")
- // Verify checkpoint files exist locally
+ // Verify checkpoint drives exist locally
if _, err := os.Stat(cachedRootfs); err != nil {
return fmt.Errorf("checkpoint rootfs not found locally: %w", err)
}
@@ -998,11 +1050,54 @@ func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpoi
return fmt.Errorf("checkpoint workspace not found locally: %w", err)
}
- // Step 1: SyncFS (best effort — save current state in case needed)
+ // Check if warm restore is possible (memory snapshot exists in checkpoint cache)
+ snapshotDir := filepath.Join(cacheDir, "snapshot")
+ memFile := filepath.Join(snapshotDir, "mem")
+ vmstateFile := filepath.Join(snapshotDir, "vmstate")
+ metaPath := filepath.Join(snapshotDir, "snapshot-meta.json")
+ canWarmRestore := fileExists(memFile) && fileExists(vmstateFile) && fileExists(metaPath)
+
+ if canWarmRestore {
+ if err := m.warmRestoreFromCheckpoint(ctx, vm, sandboxID, checkpointID, cacheDir); err != nil {
+ log.Printf("firecracker: RestoreFromCheckpoint %s/%s: warm restore failed: %v, falling back to cold boot", sandboxID, checkpointID, err)
+ // Warm restore may have killed the VM — re-fetch to check
+ vm, _ = m.getVM(sandboxID)
+ } else {
+ return nil // Warm restore succeeded
+ }
+ }
+
+ // Cold boot fallback
+ return m.coldBootRestoreFromCheckpoint(ctx, vm, sandboxID, checkpointID, cachedRootfs, cachedWorkspace)
+}
+
+// warmRestoreFromCheckpoint restores a sandbox using Firecracker's snapshot load.
+// The VM resumes from the exact state when the checkpoint was created — all processes
+// are preserved, and restore completes in ~200-500ms instead of ~3.5s cold boot.
+func (m *Manager) warmRestoreFromCheckpoint(ctx context.Context, vm *VMInstance, sandboxID, checkpointID string, cacheDir string) error {
+ t0 := time.Now()
+
+ snapshotDir := filepath.Join(cacheDir, "snapshot")
+ memFile := filepath.Join(snapshotDir, "mem")
+ vmstateFile := filepath.Join(snapshotDir, "vmstate")
+ metaPath := filepath.Join(snapshotDir, "snapshot-meta.json")
+
+ // Read snapshot metadata
+ metaJSON, err := os.ReadFile(metaPath)
+ if err != nil {
+ return fmt.Errorf("read snapshot meta: %w", err)
+ }
+ var meta SnapshotMeta
+ if err := json.Unmarshal(metaJSON, &meta); err != nil {
+ return fmt.Errorf("parse snapshot meta: %w", err)
+ }
+
+ // Save VM state we need after kill
+ sandboxDir := vm.sandboxDir
+ endAt := vm.EndAt
+
+ // Step 1: Close agent on current VM
if vm.agent != nil {
- syncCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
- _ = vm.agent.SyncFS(syncCtx)
- cancel()
vm.agent.Close()
vm.agent = nil
}
@@ -1013,33 +1108,186 @@ func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpoi
_ = vm.cmd.Wait()
}
- // Step 2b: Clean up socket files so the new VM can bind
+ // Step 3: Clean up sockets
_ = os.Remove(vm.vsockPath)
if vm.apiSockPath != "" {
_ = os.Remove(vm.apiSockPath)
}
- // Step 3: Save VM config before removing from map
- template := vm.Template
- cpuCount := vm.CpuCount
- memoryMB := vm.MemoryMB
- guestPort := vm.GuestPort
+ // Step 4: Reflink copy checkpoint drives to sandbox dir (same absolute paths baked into vmstate)
+ rootfsPath := filepath.Join(sandboxDir, "rootfs.ext4")
+ workspacePath := filepath.Join(sandboxDir, "workspace.ext4")
+ if err := copyFileReflink(filepath.Join(cacheDir, "rootfs.ext4"), rootfsPath); err != nil {
+ return fmt.Errorf("copy checkpoint rootfs: %w", err)
+ }
+ if err := copyFileReflink(filepath.Join(cacheDir, "workspace.ext4"), workspacePath); err != nil {
+ return fmt.Errorf("copy checkpoint workspace: %w", err)
+ }
- // Step 4: Clean up network
+ // Step 5: Release old network and reclaim the same TAP name (baked into vmstate)
if vm.network != nil {
RemoveDNAT(vm.network)
DeleteTAP(vm.network.TAPName)
m.subnets.Release(vm.network.TAPName)
}
- // Step 5: Remove old VM from tracking
+ netCfg, err := m.subnets.AllocateSpecific(meta.Network.TAPName)
+ if err != nil {
+ return fmt.Errorf("reclaim TAP %s for warm restore: %w", meta.Network.TAPName, err)
+ }
+ if err := CreateTAP(netCfg); err != nil {
+ m.subnets.Release(netCfg.TAPName)
+ return fmt.Errorf("create TAP: %w", err)
+ }
+
+ hostPort, err := FindFreePort()
+ if err != nil {
+ DeleteTAP(netCfg.TAPName)
+ m.subnets.Release(netCfg.TAPName)
+ return fmt.Errorf("find free port: %w", err)
+ }
+ netCfg.HostPort = hostPort
+ netCfg.GuestPort = meta.GuestPort
+ if netCfg.GuestPort == 0 {
+ netCfg.GuestPort = m.cfg.DefaultPort
+ }
+
+ if err := AddDNAT(netCfg); err != nil {
+ DeleteTAP(netCfg.TAPName)
+ m.subnets.Release(netCfg.TAPName)
+ return fmt.Errorf("add DNAT: %w", err)
+ }
+
+ // Step 6: Start fresh Firecracker process (snapshot mode — no config needed)
+ apiSockPath := filepath.Join(sandboxDir, "firecracker.sock")
+ vsockPath := meta.VsockPath
+ _ = os.Remove(apiSockPath)
+ _ = os.Remove(vsockPath)
+
+ logPath := filepath.Join(sandboxDir, "firecracker.log")
+ logFile, err := os.Create(logPath)
+ if err != nil {
+ m.cleanupVM(netCfg, "")
+ return fmt.Errorf("create log file: %w", err)
+ }
+
+ cmd := exec.Command(m.cfg.FirecrackerBin, "--api-sock", apiSockPath)
+ cmd.Stdout = logFile
+ cmd.Stderr = logFile
+ if err := cmd.Start(); err != nil {
+ logFile.Close()
+ m.cleanupVM(netCfg, "")
+ return fmt.Errorf("start firecracker: %w", err)
+ }
+ logFile.Close()
+
+ fcClient := NewFirecrackerClient(apiSockPath)
+ if err := fcClient.WaitForSocket(5 * time.Second); err != nil {
+ cmd.Process.Kill()
+ cmd.Wait()
+ m.cleanupVM(netCfg, "")
+ return fmt.Errorf("wait for API socket: %w", err)
+ }
+
+ // Step 7: Load snapshot — VM resumes exactly where it was paused during checkpoint
+ if err := fcClient.LoadSnapshot(vmstateFile, memFile, true); err != nil {
+ cmd.Process.Kill()
+ cmd.Wait()
+ m.cleanupVM(netCfg, "")
+ return fmt.Errorf("load snapshot: %w", err)
+ }
+
+ log.Printf("firecracker: RestoreFromCheckpoint %s/%s: snapshot loaded (%dms)", sandboxID, checkpointID, time.Since(t0).Milliseconds())
+
+ // Step 8: Wait for agent (should be near-instant — agent was running when snapshot was taken)
+ agentClient, err := m.waitForAgent(context.Background(), vsockPath, 10*time.Second)
+ if err != nil {
+ cmd.Process.Kill()
+ cmd.Wait()
+ m.cleanupVM(netCfg, "")
+ return fmt.Errorf("agent not ready after warm restore: %w", err)
+ }
+
+ // Step 9: Register restored VM in tracking map
+ newVM := &VMInstance{
+ ID: sandboxID,
+ Template: meta.Template,
+ Status: types.SandboxStatusRunning,
+ StartedAt: time.Now(),
+ EndAt: endAt,
+ CpuCount: meta.CpuCount,
+ MemoryMB: meta.MemoryMB,
+ HostPort: hostPort,
+ GuestPort: netCfg.GuestPort,
+ pid: cmd.Process.Pid,
+ cmd: cmd,
+ network: netCfg,
+ vsockPath: vsockPath,
+ sandboxDir: sandboxDir,
+ apiSockPath: apiSockPath,
+ fcClient: fcClient,
+ guestMAC: meta.GuestMAC,
+ guestCID: meta.GuestCID,
+ bootArgs: meta.BootArgs,
+ agent: agentClient,
+ }
+
m.mu.Lock()
- delete(m.vms, sandboxID)
+ delete(m.vms, sandboxID) // remove old entry if still present
+ m.vms[sandboxID] = newVM
m.mu.Unlock()
- // Step 6: Cold boot a fresh VM using checkpoint drives
- // Pass checkpoint cache paths as template keys so createWithID copies them
- // instead of creating fresh drives from the base image.
+ log.Printf("firecracker: RestoreFromCheckpoint %s/%s: warm restore complete (%dms, port=%d, tap=%s)",
+ sandboxID, checkpointID, time.Since(t0).Milliseconds(), hostPort, netCfg.TAPName)
+
+ return nil
+}
+
+// coldBootRestoreFromCheckpoint is the fallback restore path.
+// Kills the VM, replaces drives, and cold boots a new VM from checkpoint drives.
+func (m *Manager) coldBootRestoreFromCheckpoint(ctx context.Context, vm *VMInstance, sandboxID, checkpointID, cachedRootfs, cachedWorkspace string) error {
+ if vm != nil {
+ // Close agent and kill process if not already done by failed warm restore
+ if vm.agent != nil {
+ vm.agent.Close()
+ vm.agent = nil
+ }
+ if vm.cmd != nil && vm.cmd.Process != nil {
+ _ = vm.cmd.Process.Kill()
+ _ = vm.cmd.Wait()
+ }
+
+ // Clean up sockets
+ _ = os.Remove(vm.vsockPath)
+ if vm.apiSockPath != "" {
+ _ = os.Remove(vm.apiSockPath)
+ }
+
+ // Clean up network
+ if vm.network != nil {
+ RemoveDNAT(vm.network)
+ DeleteTAP(vm.network.TAPName)
+ m.subnets.Release(vm.network.TAPName)
+ }
+ }
+
+ // NOTE: We do NOT delete the old VM from the tracking map here.
+ // The old VM entry (with restoring channel) must remain so that
+ // concurrent Exec calls can find it and wait on the restoring channel.
+ // createWithID below will overwrite the entry with the new VM.
+
+ // Cold boot a fresh VM using checkpoint drives
+ template := "default"
+ cpuCount := 0
+ memoryMB := 0
+ guestPort := 0
+ if vm != nil {
+ template = vm.Template
+ cpuCount = vm.CpuCount
+ memoryMB = vm.MemoryMB
+ guestPort = vm.GuestPort
+ }
+
cfg := types.SandboxConfig{
Template: template,
CpuCount: cpuCount,
@@ -1078,7 +1326,10 @@ func sparseCompressAndUpload(ctx context.Context, srcPath, s3Key string, store *
}
defer os.Remove(archivePath)
- info, _ := os.Stat(archivePath)
+ info, statErr := os.Stat(archivePath)
+ if statErr != nil {
+ return fmt.Errorf("stat sparse archive %s: %w", archivePath, statErr)
+ }
log.Printf("firecracker: sparse archive %s: %d non-zero blocks, %d KB compressed",
filepath.Base(srcPath), blocks, info.Size()/1024)
@@ -1101,3 +1352,866 @@ func compressAndUploadFile(ctx context.Context, srcPath, s3Key string, store *st
}
return nil
}
+
+// --- Warm Fork from Checkpoint ---
+
+// Firecracker CRC64: Jones polynomial (bit-reversed form) with init=0, no final XOR.
+// Polynomial 0x95AC9329AC4BC9B5 is the bit-reverse of 0xad93d23594c935a9.
+// Go's hash/crc64 package uses a different polynomial (ECMA or ISO), so we build
+// our own table. The lookup algorithm is standard LSB-first (reflected).
+var firecrackerCRC64Table = func() [256]uint64 {
+ const poly = 0x95AC9329AC4BC9B5
+ var table [256]uint64
+ for i := 0; i < 256; i++ {
+ crc := uint64(i)
+ for j := 0; j < 8; j++ {
+ if crc&1 == 1 {
+ crc = (crc >> 1) ^ poly
+ } else {
+ crc >>= 1
+ }
+ }
+ table[i] = crc
+ }
+ return table
+}()
+
+func firecrackerCRC64(data []byte) uint64 {
+ crc := uint64(0)
+ for _, v := range data {
+ crc = firecrackerCRC64Table[byte(crc)^v] ^ (crc >> 8)
+ }
+ return crc
+}
+
+// patchVMStateBinary performs binary find-and-replace on a Firecracker vmstate file.
+// It patches sandbox ID (fixing drive paths + vsock path), TAP name, and CID,
+// then recalculates the CRC64 checksum that Firecracker validates on load.
+//
+// The vmstate format: [serialized data][8-byte CRC64 Jones/Redis checksum]
+// TAP names must be the same length (use fixed-width fc-tap%07d format).
+// Returns an error if the old sandbox ID is not found (safety check).
+func patchVMStateBinary(vmstatePath, oldSandboxID, newSandboxID, oldTAP, newTAP string, oldCID, newCID uint32) error {
+ raw, err := os.ReadFile(vmstatePath)
+ if err != nil {
+ return fmt.Errorf("read vmstate: %w", err)
+ }
+
+ if len(raw) < 8 {
+ return fmt.Errorf("vmstate too small (%d bytes)", len(raw))
+ }
+
+ // Split into data and trailing CRC64 checksum.
+ // Firecracker uses Jones/Redis CRC64 (bit-reversed polynomial 0x95AC9329AC4BC9B5,
+ // reflected/LSB-first lookup, init=0, no final XOR).
+ data := raw[:len(raw)-8]
+ storedCRC := binary.LittleEndian.Uint64(raw[len(raw)-8:])
+
+ computedCRC := firecrackerCRC64(data)
+ if computedCRC != storedCRC {
+ return fmt.Errorf("vmstate CRC mismatch before patching: stored=%d computed=%d (unexpected format)", storedCRC, computedCRC)
+ }
+
+ // Patch sandbox ID — fixes drive paths (/data/sandboxes/{id}/rootfs.ext4, workspace.ext4)
+ // and vsock path (/data/sandboxes/{id}/vsock.sock)
+ oldID := []byte(oldSandboxID)
+ newID := []byte(newSandboxID)
+ if len(oldID) != len(newID) {
+ return fmt.Errorf("sandbox ID length mismatch: %q (%d) vs %q (%d)", oldSandboxID, len(oldID), newSandboxID, len(newID))
+ }
+ if !bytes.Contains(data, oldID) {
+ return fmt.Errorf("old sandbox ID %q not found in vmstate — cannot patch", oldSandboxID)
+ }
+ data = bytes.ReplaceAll(data, oldID, newID)
+
+ // Patch TAP name — must be same length (fixed-width format)
+ if oldTAP != "" && newTAP != "" && oldTAP != newTAP {
+ oldTAPBytes := []byte(oldTAP)
+ newTAPBytes := []byte(newTAP)
+ if len(oldTAPBytes) != len(newTAPBytes) {
+ return fmt.Errorf("TAP name length mismatch: %q (%d) vs %q (%d) — use fixed-width format", oldTAP, len(oldTAPBytes), newTAP, len(newTAPBytes))
+ }
+ data = bytes.ReplaceAll(data, oldTAPBytes, newTAPBytes)
+ }
+
+ // Patch CID — search for the old CID (uint32 LE) near the vsock.sock string.
+ // The CID appears in the vsock device state in the vmstate binary.
+ if oldCID != newCID {
+ oldCIDBytes := make([]byte, 4)
+ newCIDBytes := make([]byte, 4)
+ binary.LittleEndian.PutUint32(oldCIDBytes, oldCID)
+ binary.LittleEndian.PutUint32(newCIDBytes, newCID)
+
+ // Find vsock.sock marker and search within 1KB around it for the CID
+ marker := []byte("vsock.sock")
+ idx := bytes.Index(data, marker)
+ if idx >= 0 {
+ searchStart := idx - 512
+ if searchStart < 0 {
+ searchStart = 0
+ }
+ searchEnd := idx + 512
+ if searchEnd > len(data) {
+ searchEnd = len(data)
+ }
+ region := data[searchStart:searchEnd]
+ cidIdx := bytes.Index(region, oldCIDBytes)
+ if cidIdx >= 0 {
+ absIdx := searchStart + cidIdx
+ copy(data[absIdx:absIdx+4], newCIDBytes)
+ log.Printf("firecracker: patchVMState: patched CID %d→%d at offset %d", oldCID, newCID, absIdx)
+ } else {
+ log.Printf("firecracker: patchVMState: CID %d not found near vsock marker (best-effort, continuing)", oldCID)
+ }
+ } else {
+ log.Printf("firecracker: patchVMState: vsock.sock marker not found (best-effort, continuing)")
+ }
+ }
+
+ // Recompute CRC64 over patched data and append
+ newCRC := firecrackerCRC64(data)
+ crcBytes := make([]byte, 8)
+ binary.LittleEndian.PutUint64(crcBytes, newCRC)
+ patched := append(data, crcBytes...)
+
+ if err := os.WriteFile(vmstatePath, patched, 0644); err != nil {
+ return fmt.Errorf("write patched vmstate: %w", err)
+ }
+ log.Printf("firecracker: patchVMState: CRC64 updated (%d→%d)", storedCRC, newCRC)
+ return nil
+}
+
+// reconfigureGuestNetwork updates the guest's network configuration via agent Exec.
+// After warm fork/golden snapshot, the guest has the old network from the source snapshot.
+// This brings eth0 up (golden snapshot takes it down to drain virtio queues),
+// flushes the old config, and applies the new IPs and gateway.
+func reconfigureGuestNetwork(ctx context.Context, agent *AgentClient, guestIP, hostIP string, cidr int) error {
+ cmd := fmt.Sprintf("ip link set eth0 up && ip addr flush dev eth0 && ip addr add %s/%d dev eth0 && ip route add default via %s", guestIP, cidr, hostIP)
+ resp, err := agent.Exec(ctx, &pb.ExecRequest{
+ Command: "/bin/sh",
+ Args: []string{"-c", cmd},
+ TimeoutSeconds: 5,
+ })
+ if err != nil {
+ return fmt.Errorf("exec network reconfig: %w", err)
+ }
+ if resp.ExitCode != 0 {
+ return fmt.Errorf("network reconfig failed (exit %d): %s", resp.ExitCode, resp.Stderr)
+ }
+ return nil
+}
+
+// ForkFromCheckpoint creates a new sandbox from an existing checkpoint.
+// Tries warm fork first (LoadSnapshot with binary-patched vmstate, ~300ms),
+// falls back to cold boot (~1.8s) if warm fork fails or snapshot files are missing.
+// The sandbox ID can be pre-determined via cfg.SandboxID for async creation flows.
+func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, cfg types.SandboxConfig) (*types.Sandbox, error) {
+ cacheDir := m.checkpointCacheDir(checkpointID)
+
+ newID := cfg.SandboxID
+ if newID == "" {
+ newID = "sb-" + uuid.New().String()[:8]
+ }
+
+ // Try warm fork if snapshot files exist locally
+ snapshotDir := filepath.Join(cacheDir, "snapshot")
+ canWarm := fileExists(filepath.Join(snapshotDir, "mem")) &&
+ fileExists(filepath.Join(snapshotDir, "vmstate")) &&
+ fileExists(filepath.Join(snapshotDir, "snapshot-meta.json"))
+
+ if canWarm {
+ sb, err := m.warmForkFromCheckpoint(ctx, checkpointID, cfg, cacheDir)
+ if err == nil {
+ return sb, nil
+ }
+ log.Printf("firecracker: ForkFromCheckpoint %s: warm fork failed: %v, falling back to cold boot", checkpointID, err)
+ }
+
+ // Cold boot fallback: use checkpoint drives from local cache
+ rootfsPath := filepath.Join(cacheDir, "rootfs.ext4")
+ workspacePath := filepath.Join(cacheDir, "workspace.ext4")
+ if fileExists(rootfsPath) && fileExists(workspacePath) {
+ cfg.TemplateRootfsKey = "local://" + rootfsPath
+ cfg.TemplateWorkspaceKey = "local://" + workspacePath
+ log.Printf("firecracker: ForkFromCheckpoint %s: cold boot from local cached drives for %s", checkpointID, newID)
+ } else {
+ log.Printf("firecracker: ForkFromCheckpoint %s: no local drives, will download from S3 for %s", checkpointID, newID)
+ }
+
+ return m.createWithID(ctx, newID, cfg)
+}
+
+// warmForkFromCheckpoint creates a new sandbox by loading the checkpoint's memory snapshot
+// into a fresh Firecracker process. The vmstate is binary-patched to update the sandbox ID,
+// TAP name, and CID. Guest networking is reconfigured after resume via Exec RPC.
+func (m *Manager) warmForkFromCheckpoint(ctx context.Context, checkpointID string, cfg types.SandboxConfig, cacheDir string) (*types.Sandbox, error) {
+ t0 := time.Now()
+
+ // Step 1: Generate new sandbox ID and create sandbox dir
+ newID := cfg.SandboxID
+ if newID == "" {
+ newID = "sb-" + uuid.New().String()[:8]
+ }
+ sandboxDir := filepath.Join(m.cfg.DataDir, "sandboxes", newID)
+ if err := os.MkdirAll(sandboxDir, 0755); err != nil {
+ return nil, fmt.Errorf("mkdir sandbox dir: %w", err)
+ }
+
+ // Step 2: Read source snapshot metadata
+ snapshotDir := filepath.Join(cacheDir, "snapshot")
+ metaJSON, err := os.ReadFile(filepath.Join(snapshotDir, "snapshot-meta.json"))
+ if err != nil {
+ os.RemoveAll(sandboxDir)
+ return nil, fmt.Errorf("read snapshot meta: %w", err)
+ }
+ var meta SnapshotMeta
+ if err := json.Unmarshal(metaJSON, &meta); err != nil {
+ os.RemoveAll(sandboxDir)
+ return nil, fmt.Errorf("parse snapshot meta: %w", err)
+ }
+
+ oldSandboxID := meta.SandboxID
+ log.Printf("firecracker: warmFork %s→%s from checkpoint %s", oldSandboxID, newID, checkpointID)
+
+ // Step 3: Copy checkpoint drives to new sandbox dir (reflink)
+ rootfsPath := filepath.Join(sandboxDir, "rootfs.ext4")
+ workspacePath := filepath.Join(sandboxDir, "workspace.ext4")
+ if err := copyFileReflink(filepath.Join(cacheDir, "rootfs.ext4"), rootfsPath); err != nil {
+ os.RemoveAll(sandboxDir)
+ return nil, fmt.Errorf("copy checkpoint rootfs: %w", err)
+ }
+ if err := copyFileReflink(filepath.Join(cacheDir, "workspace.ext4"), workspacePath); err != nil {
+ os.RemoveAll(sandboxDir)
+ return nil, fmt.Errorf("copy checkpoint workspace: %w", err)
+ }
+
+ // Step 4: Copy snapshot files (mem + vmstate) to new sandbox dir
+ newSnapshotDir := filepath.Join(sandboxDir, "snapshot")
+ if err := os.MkdirAll(newSnapshotDir, 0755); err != nil {
+ os.RemoveAll(sandboxDir)
+ return nil, fmt.Errorf("mkdir snapshot dir: %w", err)
+ }
+ memFile := filepath.Join(newSnapshotDir, "mem")
+ vmstateFile := filepath.Join(newSnapshotDir, "vmstate")
+ if err := copyFileReflink(filepath.Join(snapshotDir, "mem"), memFile); err != nil {
+ os.RemoveAll(sandboxDir)
+ return nil, fmt.Errorf("copy mem: %w", err)
+ }
+ if err := copyFileReflink(filepath.Join(snapshotDir, "vmstate"), vmstateFile); err != nil {
+ os.RemoveAll(sandboxDir)
+ return nil, fmt.Errorf("copy vmstate: %w", err)
+ }
+
+ log.Printf("firecracker: warmFork %s: files copied (%dms)", newID, time.Since(t0).Milliseconds())
+
+ // Step 5: Allocate new network (TAP, subnet, DNAT)
+ netCfg, err := m.subnets.Allocate()
+ if err != nil {
+ os.RemoveAll(sandboxDir)
+ return nil, fmt.Errorf("allocate subnet: %w", err)
+ }
+ if err := CreateTAP(netCfg); err != nil {
+ m.subnets.Release(netCfg.TAPName)
+ os.RemoveAll(sandboxDir)
+ return nil, fmt.Errorf("create TAP: %w", err)
+ }
+
+ hostPort, err := FindFreePort()
+ if err != nil {
+ DeleteTAP(netCfg.TAPName)
+ m.subnets.Release(netCfg.TAPName)
+ os.RemoveAll(sandboxDir)
+ return nil, fmt.Errorf("find free port: %w", err)
+ }
+ netCfg.HostPort = hostPort
+ netCfg.GuestPort = meta.GuestPort
+ if netCfg.GuestPort == 0 {
+ netCfg.GuestPort = m.cfg.DefaultPort
+ }
+
+ if err := AddDNAT(netCfg); err != nil {
+ DeleteTAP(netCfg.TAPName)
+ m.subnets.Release(netCfg.TAPName)
+ os.RemoveAll(sandboxDir)
+ return nil, fmt.Errorf("add DNAT: %w", err)
+ }
+
+ // Step 6: Binary-patch vmstate (sandbox ID, TAP, CID)
+ newCID := m.allocateCID()
+ oldTAP := ""
+ if meta.Network != nil {
+ oldTAP = meta.Network.TAPName
+ }
+ if err := patchVMStateBinary(vmstateFile, oldSandboxID, newID, oldTAP, netCfg.TAPName, meta.GuestCID, newCID); err != nil {
+ m.cleanupVM(netCfg, sandboxDir)
+ return nil, fmt.Errorf("patch vmstate: %w", err)
+ }
+ log.Printf("firecracker: warmFork %s: vmstate patched (%dms)", newID, time.Since(t0).Milliseconds())
+
+ // Step 7: Start fresh Firecracker process
+ vsockPath := filepath.Join(sandboxDir, "vsock.sock")
+ apiSockPath := filepath.Join(sandboxDir, "firecracker.sock")
+ _ = os.Remove(apiSockPath)
+ _ = os.Remove(vsockPath)
+
+ logPath := filepath.Join(sandboxDir, "firecracker.log")
+ logFile, err := os.Create(logPath)
+ if err != nil {
+ m.cleanupVM(netCfg, sandboxDir)
+ return nil, fmt.Errorf("create log file: %w", err)
+ }
+
+ cmd := exec.Command(m.cfg.FirecrackerBin, "--api-sock", apiSockPath)
+ cmd.Stdout = logFile
+ cmd.Stderr = logFile
+ if err := cmd.Start(); err != nil {
+ logFile.Close()
+ m.cleanupVM(netCfg, sandboxDir)
+ return nil, fmt.Errorf("start firecracker: %w", err)
+ }
+ logFile.Close()
+
+ fcClient := NewFirecrackerClient(apiSockPath)
+ if err := fcClient.WaitForSocket(5 * time.Second); err != nil {
+ cmd.Process.Kill()
+ cmd.Wait()
+ m.cleanupVM(netCfg, sandboxDir)
+ return nil, fmt.Errorf("wait for API socket: %w", err)
+ }
+
+ // Step 8: Load snapshot — VM resumes from checkpoint state
+ if err := fcClient.LoadSnapshot(vmstateFile, memFile, true); err != nil {
+ cmd.Process.Kill()
+ cmd.Wait()
+ m.cleanupVM(netCfg, sandboxDir)
+ return nil, fmt.Errorf("load snapshot: %w", err)
+ }
+ log.Printf("firecracker: warmFork %s: snapshot loaded (%dms)", newID, time.Since(t0).Milliseconds())
+
+ // Step 9: Wait for agent (should be near-instant — agent was running when snapshot was taken)
+ agentClient, err := m.waitForAgent(context.Background(), vsockPath, 10*time.Second)
+ if err != nil {
+ cmd.Process.Kill()
+ cmd.Wait()
+ m.cleanupVM(netCfg, sandboxDir)
+ return nil, fmt.Errorf("agent not ready after warm fork: %w", err)
+ }
+
+ // Step 10: Reconfigure guest network (guest has old IPs from checkpoint)
+ if err := reconfigureGuestNetwork(ctx, agentClient, netCfg.GuestIP, netCfg.HostIP, netCfg.CIDR); err != nil {
+ log.Printf("firecracker: warmFork %s: network reconfig failed: %v (VM still running, network may not work)", newID, err)
+ // Don't fail — the VM is running and accessible via vsock, just external network may be broken
+ }
+
+ // Step 11: Write sandbox-meta.json for crash recovery
+ sbMeta := SandboxMeta{
+ SandboxID: newID,
+ Template: meta.Template,
+ CpuCount: meta.CpuCount,
+ MemoryMB: meta.MemoryMB,
+ GuestPort: netCfg.GuestPort,
+ }
+ sbMetaJSON, _ := json.Marshal(sbMeta)
+ _ = os.WriteFile(filepath.Join(sandboxDir, "sandbox-meta.json"), sbMetaJSON, 0644)
+
+ // Step 12: Register VM
+ timeout := cfg.Timeout
+ if timeout <= 0 {
+ timeout = 300
+ }
+
+ now := time.Now()
+ vm := &VMInstance{
+ ID: newID,
+ Template: meta.Template,
+ Status: types.SandboxStatusRunning,
+ StartedAt: now,
+ EndAt: now.Add(time.Duration(timeout) * time.Second),
+ CpuCount: meta.CpuCount,
+ MemoryMB: meta.MemoryMB,
+ HostPort: hostPort,
+ GuestPort: netCfg.GuestPort,
+ pid: cmd.Process.Pid,
+ cmd: cmd,
+ network: netCfg,
+ vsockPath: vsockPath,
+ sandboxDir: sandboxDir,
+ apiSockPath: apiSockPath,
+ fcClient: fcClient,
+ guestMAC: meta.GuestMAC,
+ guestCID: newCID,
+ bootArgs: meta.BootArgs,
+ agent: agentClient,
+ }
+
+ m.mu.Lock()
+ m.vms[newID] = vm
+ m.mu.Unlock()
+
+ log.Printf("firecracker: warmFork %s from checkpoint %s: complete (%dms, port=%d, tap=%s)",
+ newID, checkpointID, time.Since(t0).Milliseconds(), hostPort, netCfg.TAPName)
+
+ return vmToSandbox(vm), nil
+}
+
+// --- Golden Snapshot ---
+
+// errNoGoldenSnapshot is returned when no golden snapshot is available.
+var errNoGoldenSnapshot = fmt.Errorf("no golden snapshot available")
+
+// PrepareGoldenSnapshot boots a default VM, creates a memory snapshot, and stores it
+// for fast VM creation. All subsequent Sandbox.create() calls for the default template
+// will use LoadSnapshot (~500ms) instead of cold boot (~2s).
+func (m *Manager) PrepareGoldenSnapshot() error {
+ t0 := time.Now()
+ goldenDir := filepath.Join(m.cfg.DataDir, "golden-snapshot", "default")
+
+ // Clean up any existing golden snapshot
+ os.RemoveAll(goldenDir)
+ if err := os.MkdirAll(goldenDir, 0755); err != nil {
+ return fmt.Errorf("mkdir golden dir: %w", err)
+ }
+
+ // Step 1: Boot a temporary VM with default config
+ // Use same-length ID as real sandboxes (sb-XXXXXXXX = 11 chars) for vmstate binary patching
+ tempID := "sb-" + uuid.New().String()[:8]
+ tempDir := filepath.Join(m.cfg.DataDir, "sandboxes", tempID)
+ if err := os.MkdirAll(tempDir, 0755); err != nil {
+ return fmt.Errorf("mkdir temp sandbox dir: %w", err)
+ }
+
+ // Prepare drives
+ rootfsPath := filepath.Join(tempDir, "rootfs.ext4")
+ workspacePath := filepath.Join(tempDir, "workspace.ext4")
+
+ baseImage, err := ResolveBaseImage(m.cfg.ImagesDir, "default")
+ if err != nil {
+ os.RemoveAll(tempDir)
+ return fmt.Errorf("resolve base image: %w", err)
+ }
+ if err := PrepareRootfs(baseImage, rootfsPath); err != nil {
+ os.RemoveAll(tempDir)
+ return fmt.Errorf("prepare rootfs: %w", err)
+ }
+ if err := CreateWorkspace(workspacePath, m.cfg.DefaultDiskMB); err != nil {
+ os.RemoveAll(tempDir)
+ return fmt.Errorf("create workspace: %w", err)
+ }
+
+ // Allocate network
+ netCfg, err := m.subnets.Allocate()
+ if err != nil {
+ os.RemoveAll(tempDir)
+ return fmt.Errorf("allocate subnet: %w", err)
+ }
+ if err := CreateTAP(netCfg); err != nil {
+ m.subnets.Release(netCfg.TAPName)
+ os.RemoveAll(tempDir)
+ return fmt.Errorf("create TAP: %w", err)
+ }
+
+ cpus := m.cfg.DefaultCPUs
+ memMB := m.cfg.DefaultMemoryMB
+ guestCID := m.allocateCID()
+ vsockPath := filepath.Join(tempDir, "vsock.sock")
+ guestMAC := generateMAC(tempID)
+
+ bootArgs := fmt.Sprintf(
+ "keep_bootcon console=ttyS0 reboot=k panic=1 pci=off "+
+ "ip=%s::%s:%s::eth0:off "+
+ "init=/sbin/init "+
+ "osb.gateway=%s",
+ netCfg.GuestIP, netCfg.HostIP, netCfg.Mask, netCfg.HostIP,
+ )
+
+ // Start Firecracker
+ apiSockPath := filepath.Join(tempDir, "firecracker.sock")
+ logPath := filepath.Join(tempDir, "firecracker.log")
+ logFile, err := os.Create(logPath)
+ if err != nil {
+ m.cleanupVM(netCfg, tempDir)
+ return fmt.Errorf("create log file: %w", err)
+ }
+
+ cmd := exec.Command(m.cfg.FirecrackerBin, "--api-sock", apiSockPath)
+ cmd.Stdout = logFile
+ cmd.Stderr = logFile
+ if err := cmd.Start(); err != nil {
+ logFile.Close()
+ m.cleanupVM(netCfg, tempDir)
+ return fmt.Errorf("start firecracker: %w", err)
+ }
+ logFile.Close()
+
+ // Configure VM
+ fcClient := NewFirecrackerClient(apiSockPath)
+ if err := fcClient.WaitForSocket(5 * time.Second); err != nil {
+ cmd.Process.Kill()
+ cmd.Wait()
+ m.cleanupVM(netCfg, tempDir)
+ return fmt.Errorf("wait for API socket: %w", err)
+ }
+ if err := fcClient.PutMachineConfig(cpus, memMB); err != nil {
+ cmd.Process.Kill()
+ cmd.Wait()
+ m.cleanupVM(netCfg, tempDir)
+ return fmt.Errorf("put machine config: %w", err)
+ }
+ if err := fcClient.PutBootSource(m.cfg.KernelPath, bootArgs); err != nil {
+ cmd.Process.Kill()
+ cmd.Wait()
+ m.cleanupVM(netCfg, tempDir)
+ return fmt.Errorf("put boot source: %w", err)
+ }
+ if err := fcClient.PutDrive("rootfs", rootfsPath, true, false); err != nil {
+ cmd.Process.Kill()
+ cmd.Wait()
+ m.cleanupVM(netCfg, tempDir)
+ return fmt.Errorf("put rootfs drive: %w", err)
+ }
+ if err := fcClient.PutDrive("workspace", workspacePath, false, false); err != nil {
+ cmd.Process.Kill()
+ cmd.Wait()
+ m.cleanupVM(netCfg, tempDir)
+ return fmt.Errorf("put workspace drive: %w", err)
+ }
+ if err := fcClient.PutNetworkInterface("eth0", guestMAC, netCfg.TAPName); err != nil {
+ cmd.Process.Kill()
+ cmd.Wait()
+ m.cleanupVM(netCfg, tempDir)
+ return fmt.Errorf("put network interface: %w", err)
+ }
+ if err := fcClient.PutVsock(guestCID, vsockPath); err != nil {
+ cmd.Process.Kill()
+ cmd.Wait()
+ m.cleanupVM(netCfg, tempDir)
+ return fmt.Errorf("put vsock: %w", err)
+ }
+ if err := fcClient.StartInstance(); err != nil {
+ cmd.Process.Kill()
+ cmd.Wait()
+ m.cleanupVM(netCfg, tempDir)
+ return fmt.Errorf("start instance: %w", err)
+ }
+
+ log.Printf("firecracker: golden snapshot: VM booted (%dms)", time.Since(t0).Milliseconds())
+
+ // Step 2: Wait for agent
+ agent, err := m.waitForAgent(context.Background(), vsockPath, 30*time.Second)
+ if err != nil {
+ cmd.Process.Kill()
+ cmd.Wait()
+ m.cleanupVM(netCfg, tempDir)
+ return fmt.Errorf("agent not ready: %w", err)
+ }
+
+ log.Printf("firecracker: golden snapshot: agent ready (%dms)", time.Since(t0).Milliseconds())
+
+ // Step 3: Flush filesystem, quiesce network, close agent, pause VM, snapshot
+ _ = agent.SyncFS(context.Background())
+
+ // Bring eth0 down to drain virtio-net queues cleanly. Without this,
+ // snapshot restore with a different TAP backend causes virtqueue corruption
+ // ("output.0:id 0 is not a head!") and a soft lockup in the guest kernel.
+ _, _ = agent.Exec(context.Background(), &pb.ExecRequest{
+ Command: "/bin/sh",
+ Args: []string{"-c", "ip link set eth0 down"},
+ TimeoutSeconds: 5,
+ })
+
+ agent.Close()
+
+ if err := fcClient.PauseVM(); err != nil {
+ cmd.Process.Kill()
+ cmd.Wait()
+ m.cleanupVM(netCfg, tempDir)
+ return fmt.Errorf("pause VM: %w", err)
+ }
+
+ snapshotDir := filepath.Join(goldenDir, "snapshot")
+ if err := os.MkdirAll(snapshotDir, 0755); err != nil {
+ cmd.Process.Kill()
+ cmd.Wait()
+ m.cleanupVM(netCfg, tempDir)
+ return fmt.Errorf("mkdir snapshot dir: %w", err)
+ }
+
+ memFile := filepath.Join(snapshotDir, "mem")
+ vmstateFile := filepath.Join(snapshotDir, "vmstate")
+ if err := fcClient.CreateSnapshot(vmstateFile, memFile); err != nil {
+ cmd.Process.Kill()
+ cmd.Wait()
+ m.cleanupVM(netCfg, tempDir)
+ return fmt.Errorf("create snapshot: %w", err)
+ }
+
+ log.Printf("firecracker: golden snapshot: memory snapshot captured (%dms)", time.Since(t0).Milliseconds())
+
+ // Step 4: Copy drives to golden dir (reflink for speed)
+ if err := copyFileReflink(rootfsPath, filepath.Join(goldenDir, "rootfs.ext4")); err != nil {
+ cmd.Process.Kill()
+ cmd.Wait()
+ m.cleanupVM(netCfg, tempDir)
+ os.RemoveAll(goldenDir)
+ return fmt.Errorf("copy rootfs: %w", err)
+ }
+ if err := copyFileReflink(workspacePath, filepath.Join(goldenDir, "workspace.ext4")); err != nil {
+ cmd.Process.Kill()
+ cmd.Wait()
+ m.cleanupVM(netCfg, tempDir)
+ os.RemoveAll(goldenDir)
+ return fmt.Errorf("copy workspace: %w", err)
+ }
+
+ // Step 5: Write metadata
+ meta := SnapshotMeta{
+ SandboxID: tempID,
+ Network: netCfg,
+ GuestCID: guestCID,
+ GuestMAC: guestMAC,
+ BootArgs: bootArgs,
+ CpuCount: cpus,
+ MemoryMB: memMB,
+ Template: "default",
+ GuestPort: m.cfg.DefaultPort,
+ }
+ metaJSON, _ := json.Marshal(meta)
+ _ = os.WriteFile(filepath.Join(snapshotDir, "snapshot-meta.json"), metaJSON, 0644)
+
+ // Step 6: Kill the temporary VM + clean up
+ cmd.Process.Kill()
+ cmd.Wait()
+ DeleteTAP(netCfg.TAPName)
+ m.subnets.Release(netCfg.TAPName)
+ RemoveDNAT(netCfg)
+ os.RemoveAll(tempDir)
+
+ // Step 7: Register golden snapshot
+ gs := &GoldenSnapshot{
+ Dir: goldenDir,
+ Meta: meta,
+ Ready: true,
+ }
+ m.goldenMu.Lock()
+ m.golden = gs
+ m.goldenMu.Unlock()
+
+ log.Printf("firecracker: golden snapshot ready at %s (%dms)", goldenDir, time.Since(t0).Milliseconds())
+ return nil
+}
+
+// createFromGoldenSnapshot creates a new sandbox using the pre-booted golden snapshot.
+// Returns errNoGoldenSnapshot if no golden snapshot is available.
+func (m *Manager) createFromGoldenSnapshot(ctx context.Context, id string, cfg types.SandboxConfig) (*types.Sandbox, error) {
+ m.goldenMu.RLock()
+ gs := m.golden
+ m.goldenMu.RUnlock()
+
+ if gs == nil || !gs.Ready {
+ return nil, errNoGoldenSnapshot
+ }
+
+ t0 := time.Now()
+ meta := gs.Meta
+ goldenDir := gs.Dir
+
+ // Verify golden snapshot files still exist
+ if !fileExists(filepath.Join(goldenDir, "snapshot", "mem")) ||
+ !fileExists(filepath.Join(goldenDir, "snapshot", "vmstate")) {
+ return nil, errNoGoldenSnapshot
+ }
+
+ sandboxDir := filepath.Join(m.cfg.DataDir, "sandboxes", id)
+ if err := os.MkdirAll(sandboxDir, 0755); err != nil {
+ return nil, fmt.Errorf("mkdir sandbox dir: %w", err)
+ }
+
+ // Step 1: Copy drives from golden snapshot (reflink = instant CoW)
+ rootfsPath := filepath.Join(sandboxDir, "rootfs.ext4")
+ workspacePath := filepath.Join(sandboxDir, "workspace.ext4")
+ if err := copyFileReflink(filepath.Join(goldenDir, "rootfs.ext4"), rootfsPath); err != nil {
+ os.RemoveAll(sandboxDir)
+ return nil, fmt.Errorf("copy golden rootfs: %w", err)
+ }
+ if err := copyFileReflink(filepath.Join(goldenDir, "workspace.ext4"), workspacePath); err != nil {
+ os.RemoveAll(sandboxDir)
+ return nil, fmt.Errorf("copy golden workspace: %w", err)
+ }
+
+ // Step 2: Copy snapshot files (mem + vmstate)
+ snapshotDir := filepath.Join(sandboxDir, "snapshot")
+ if err := os.MkdirAll(snapshotDir, 0755); err != nil {
+ os.RemoveAll(sandboxDir)
+ return nil, fmt.Errorf("mkdir snapshot dir: %w", err)
+ }
+ memFile := filepath.Join(snapshotDir, "mem")
+ vmstateFile := filepath.Join(snapshotDir, "vmstate")
+ if err := copyFileReflink(filepath.Join(goldenDir, "snapshot", "mem"), memFile); err != nil {
+ os.RemoveAll(sandboxDir)
+ return nil, fmt.Errorf("copy golden mem: %w", err)
+ }
+ if err := copyFileReflink(filepath.Join(goldenDir, "snapshot", "vmstate"), vmstateFile); err != nil {
+ os.RemoveAll(sandboxDir)
+ return nil, fmt.Errorf("copy golden vmstate: %w", err)
+ }
+
+ log.Printf("firecracker: goldenCreate %s: files copied (%dms)", id, time.Since(t0).Milliseconds())
+
+ // Step 3: Allocate new network
+ netCfg, err := m.subnets.Allocate()
+ if err != nil {
+ os.RemoveAll(sandboxDir)
+ return nil, fmt.Errorf("allocate subnet: %w", err)
+ }
+ if err := CreateTAP(netCfg); err != nil {
+ m.subnets.Release(netCfg.TAPName)
+ os.RemoveAll(sandboxDir)
+ return nil, fmt.Errorf("create TAP: %w", err)
+ }
+
+ hostPort, err := FindFreePort()
+ if err != nil {
+ DeleteTAP(netCfg.TAPName)
+ m.subnets.Release(netCfg.TAPName)
+ os.RemoveAll(sandboxDir)
+ return nil, fmt.Errorf("find free port: %w", err)
+ }
+ guestPort := cfg.Port
+ if guestPort == 0 {
+ guestPort = m.cfg.DefaultPort
+ }
+ netCfg.HostPort = hostPort
+ netCfg.GuestPort = guestPort
+
+ if err := AddDNAT(netCfg); err != nil {
+ DeleteTAP(netCfg.TAPName)
+ m.subnets.Release(netCfg.TAPName)
+ os.RemoveAll(sandboxDir)
+ return nil, fmt.Errorf("add DNAT: %w", err)
+ }
+
+ // Step 4: Binary-patch vmstate
+ newCID := m.allocateCID()
+ oldTAP := ""
+ if meta.Network != nil {
+ oldTAP = meta.Network.TAPName
+ }
+ if err := patchVMStateBinary(vmstateFile, meta.SandboxID, id, oldTAP, netCfg.TAPName, meta.GuestCID, newCID); err != nil {
+ m.cleanupVM(netCfg, sandboxDir)
+ return nil, fmt.Errorf("patch vmstate: %w", err)
+ }
+ log.Printf("firecracker: goldenCreate %s: vmstate patched (%dms)", id, time.Since(t0).Milliseconds())
+
+ // Step 5: Start fresh Firecracker process
+ vsockPath := filepath.Join(sandboxDir, "vsock.sock")
+ apiSockPath := filepath.Join(sandboxDir, "firecracker.sock")
+ _ = os.Remove(apiSockPath)
+ _ = os.Remove(vsockPath)
+
+ logPath := filepath.Join(sandboxDir, "firecracker.log")
+ logFileH, err := os.Create(logPath)
+ if err != nil {
+ m.cleanupVM(netCfg, sandboxDir)
+ return nil, fmt.Errorf("create log file: %w", err)
+ }
+
+ cmd := exec.Command(m.cfg.FirecrackerBin, "--api-sock", apiSockPath)
+ cmd.Stdout = logFileH
+ cmd.Stderr = logFileH
+ if err := cmd.Start(); err != nil {
+ logFileH.Close()
+ m.cleanupVM(netCfg, sandboxDir)
+ return nil, fmt.Errorf("start firecracker: %w", err)
+ }
+ logFileH.Close()
+
+ fcClient := NewFirecrackerClient(apiSockPath)
+ if err := fcClient.WaitForSocket(5 * time.Second); err != nil {
+ cmd.Process.Kill()
+ cmd.Wait()
+ m.cleanupVM(netCfg, sandboxDir)
+ return nil, fmt.Errorf("wait for API socket: %w", err)
+ }
+
+ // Step 6: Load snapshot
+ if err := fcClient.LoadSnapshot(vmstateFile, memFile, true); err != nil {
+ cmd.Process.Kill()
+ cmd.Wait()
+ m.cleanupVM(netCfg, sandboxDir)
+ return nil, fmt.Errorf("load snapshot: %w", err)
+ }
+ log.Printf("firecracker: goldenCreate %s: snapshot loaded (%dms)", id, time.Since(t0).Milliseconds())
+
+ // Step 7: Wait for agent
+ agentClient, err := m.waitForAgent(context.Background(), vsockPath, 10*time.Second)
+ if err != nil {
+ cmd.Process.Kill()
+ cmd.Wait()
+ m.cleanupVM(netCfg, sandboxDir)
+ return nil, fmt.Errorf("agent not ready after golden create: %w", err)
+ }
+
+ // Step 8: Reconfigure guest network
+ if err := reconfigureGuestNetwork(ctx, agentClient, netCfg.GuestIP, netCfg.HostIP, netCfg.CIDR); err != nil {
+ log.Printf("firecracker: goldenCreate %s: network reconfig failed: %v (VM still running)", id, err)
+ }
+
+ // Step 9: Write sandbox-meta.json
+ cpus := cfg.CpuCount
+ if cpus <= 0 {
+ cpus = m.cfg.DefaultCPUs
+ }
+ memMB := cfg.MemoryMB
+ if memMB <= 0 {
+ memMB = m.cfg.DefaultMemoryMB
+ }
+
+ sbMeta := SandboxMeta{
+ SandboxID: id,
+ Template: "default",
+ CpuCount: cpus,
+ MemoryMB: memMB,
+ GuestPort: guestPort,
+ }
+ sbMetaJSON, _ := json.Marshal(sbMeta)
+ _ = os.WriteFile(filepath.Join(sandboxDir, "sandbox-meta.json"), sbMetaJSON, 0644)
+
+ // Step 10: Register VM
+ timeout := time.Duration(cfg.Timeout) * time.Second
+ if timeout <= 0 {
+ timeout = 300 * time.Second
+ }
+
+ now := time.Now()
+ vm := &VMInstance{
+ ID: id,
+ Template: "default",
+ Status: types.SandboxStatusRunning,
+ StartedAt: now,
+ EndAt: now.Add(timeout),
+ CpuCount: cpus,
+ MemoryMB: memMB,
+ HostPort: hostPort,
+ GuestPort: guestPort,
+ pid: cmd.Process.Pid,
+ cmd: cmd,
+ network: netCfg,
+ vsockPath: vsockPath,
+ sandboxDir: sandboxDir,
+ apiSockPath: apiSockPath,
+ fcClient: fcClient,
+ guestMAC: generateMAC(id),
+ guestCID: newCID,
+ bootArgs: meta.BootArgs,
+ agent: agentClient,
+ }
+
+ m.mu.Lock()
+ m.vms[id] = vm
+ m.mu.Unlock()
+
+ log.Printf("firecracker: goldenCreate %s: complete (%dms, port=%d, tap=%s)",
+ id, time.Since(t0).Milliseconds(), hostPort, netCfg.TAPName)
+
+ return vmToSandbox(vm), nil
+}
diff --git a/internal/sandbox/hibernate.go b/internal/sandbox/hibernate.go
index ae1352a0..b6fbfdc1 100644
--- a/internal/sandbox/hibernate.go
+++ b/internal/sandbox/hibernate.go
@@ -372,6 +372,11 @@ func (m *PodmanManager) RestoreFromCheckpoint(_ context.Context, _, _ string) er
return fmt.Errorf("checkpoints are only supported on Firecracker backend")
}
+// ForkFromCheckpoint is not supported on the Podman backend (Firecracker only).
+func (m *PodmanManager) ForkFromCheckpoint(_ context.Context, _ string, _ types.SandboxConfig) (*types.Sandbox, error) {
+ return nil, fmt.Errorf("checkpoints are only supported on Firecracker backend")
+}
+
// CheckpointCachePath always returns "" on the Podman backend (Firecracker only).
func (m *PodmanManager) CheckpointCachePath(_, _ string) string {
return ""
diff --git a/internal/sandbox/interface.go b/internal/sandbox/interface.go
index e871b5d5..85477977 100644
--- a/internal/sandbox/interface.go
+++ b/internal/sandbox/interface.go
@@ -68,5 +68,6 @@ type Manager interface {
// Checkpointing
CreateCheckpoint(ctx context.Context, sandboxID, checkpointID string, checkpointStore *storage.CheckpointStore, onReady func()) (rootfsKey, workspaceKey string, err error)
RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpointID string) error
+ ForkFromCheckpoint(ctx context.Context, checkpointID string, cfg types.SandboxConfig) (*types.Sandbox, error)
CheckpointCachePath(checkpointID, filename string) string
}
diff --git a/internal/sandbox/router.go b/internal/sandbox/router.go
index 9f349cfd..3bd3051c 100644
--- a/internal/sandbox/router.go
+++ b/internal/sandbox/router.go
@@ -18,6 +18,7 @@ const (
StateRunning SandboxState = iota
StateHibernated
StateWaking
+ StateCreating // async creation in progress — commands wait until ready
)
func (s SandboxState) String() string {
@@ -28,6 +29,8 @@ func (s SandboxState) String() string {
return "hibernated"
case StateWaking:
return "waking"
+ case StateCreating:
+ return "creating"
default:
return "unknown"
}
@@ -132,6 +135,53 @@ func (r *SandboxRouter) Register(sandboxID string, timeout time.Duration) {
r.sandboxes[sandboxID] = entry
}
+// RegisterCreating registers a sandbox that is being created asynchronously.
+// Commands routed to this sandbox will block until MarkCreated is called.
+func (r *SandboxRouter) RegisterCreating(sandboxID string, timeout time.Duration) {
+ if timeout <= 0 {
+ timeout = r.defaultTimeout
+ }
+
+ r.mu.Lock()
+ defer r.mu.Unlock()
+
+ entry := &sandboxEntry{
+ state: StateCreating,
+ timeout: timeout,
+ wakeCh: make(chan struct{}), // reuse wakeCh as the "ready" signal
+ }
+ r.sandboxes[sandboxID] = entry
+}
+
+// MarkCreated transitions a sandbox from StateCreating to StateRunning.
+// This unblocks any commands waiting on the sandbox.
+func (r *SandboxRouter) MarkCreated(sandboxID string, err error) {
+ r.mu.RLock()
+ entry, ok := r.sandboxes[sandboxID]
+ r.mu.RUnlock()
+ if !ok {
+ return
+ }
+
+ entry.mu.Lock()
+ defer entry.mu.Unlock()
+
+ if entry.state != StateCreating {
+ return
+ }
+
+ if err != nil {
+ entry.wakeErr = err
+ entry.state = StateHibernated // mark as failed
+ } else {
+ entry.state = StateRunning
+ entry.timer = time.AfterFunc(entry.timeout, func() {
+ r.onTimeout(sandboxID)
+ })
+ }
+ close(entry.wakeCh)
+}
+
// Unregister removes a sandbox from the router (called on kill/destroy).
func (r *SandboxRouter) Unregister(sandboxID string) {
r.mu.Lock()
@@ -330,6 +380,24 @@ func (r *SandboxRouter) ensureRunning(ctx context.Context, sandboxID string) err
return ctx.Err()
}
+ case StateCreating:
+ // Sandbox is being created asynchronously — wait for it
+ readyCh := entry.wakeCh
+ entry.mu.Unlock()
+
+ select {
+ case <-readyCh:
+ entry.mu.Lock()
+ err := entry.wakeErr
+ entry.mu.Unlock()
+ if err != nil {
+ return fmt.Errorf("sandbox %s creation failed: %w", sandboxID, err)
+ }
+ return nil
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+
default:
entry.mu.Unlock()
return fmt.Errorf("sandbox %s in unexpected state: %v", sandboxID, entry.state)
diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.go
index 84b1303c..73355055 100644
--- a/internal/worker/grpc_server.go
+++ b/internal/worker/grpc_server.go
@@ -86,6 +86,35 @@ func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxReq
NetworkEnabled: req.NetworkEnabled,
ImageRef: req.ImageRef,
Port: int(req.Port),
+ SandboxID: req.SandboxId, // use server-assigned ID if provided
+ }
+
+ // Warm fork: if checkpoint_id is set, try snapshot-based fork first.
+ // ForkFromCheckpoint handles warm fork with cold boot fallback internally.
+ if req.CheckpointId != "" {
+ // Ensure checkpoint drives are cached locally (download from S3 if needed)
+ if req.TemplateRootfsKey != "" && req.TemplateWorkspaceKey != "" {
+ if _, _, err := s.resolveTemplateDrives(ctx, req.TemplateRootfsKey, req.TemplateWorkspaceKey); err != nil {
+ log.Printf("grpc: warm fork %s: resolve drives failed: %v, continuing with ForkFromCheckpoint", req.CheckpointId, err)
+ }
+ }
+
+ sb, err := s.manager.ForkFromCheckpoint(ctx, req.CheckpointId, cfg)
+ if err == nil {
+ // Register with sandbox router for rolling timeout tracking
+ if s.router != nil {
+ timeout := cfg.Timeout
+ if timeout <= 0 {
+ timeout = 300
+ }
+ s.router.Register(sb.ID, time.Duration(timeout)*time.Second)
+ }
+ return &pb.CreateSandboxResponse{
+ SandboxId: sb.ID,
+ Status: string(sb.Status),
+ }, nil
+ }
+ log.Printf("grpc: ForkFromCheckpoint %s failed: %v, falling back to standard Create", req.CheckpointId, err)
}
// Handle sandbox snapshot template: resolve S3 keys to local paths.
diff --git a/pkg/types/sandbox.go b/pkg/types/sandbox.go
index c85163e0..9f3ad16a 100644
--- a/pkg/types/sandbox.go
+++ b/pkg/types/sandbox.go
@@ -46,6 +46,9 @@ type SandboxConfig struct {
// When set, the sandbox boots from these drives instead of the standard base image.
TemplateRootfsKey string `json:"templateRootfsKey,omitempty"`
TemplateWorkspaceKey string `json:"templateWorkspaceKey,omitempty"`
+ // SandboxID allows pre-determining the sandbox ID for async creation.
+ // If empty, a new ID is generated automatically.
+ SandboxID string `json:"-"`
}
// SandboxListResponse is the response for listing sandboxes.
diff --git a/proto/worker/worker.pb.go b/proto/worker/worker.pb.go
index e980a357..49743318 100644
--- a/proto/worker/worker.pb.go
+++ b/proto/worker/worker.pb.go
@@ -80,8 +80,12 @@ type CreateSandboxRequest struct {
// Sandbox snapshot template: if non-empty, boot from these S3 keys instead of base image.
TemplateRootfsKey string `protobuf:"bytes,9,opt,name=template_rootfs_key,json=templateRootfsKey,proto3" json:"template_rootfs_key,omitempty"`
TemplateWorkspaceKey string `protobuf:"bytes,10,opt,name=template_workspace_key,json=templateWorkspaceKey,proto3" json:"template_workspace_key,omitempty"`
- unknownFields protoimpl.UnknownFields
- sizeCache protoimpl.SizeCache
+ // If set, attempt warm fork from local checkpoint snapshot (LoadSnapshot instead of cold boot).
+ CheckpointId string `protobuf:"bytes,11,opt,name=checkpoint_id,json=checkpointId,proto3" json:"checkpoint_id,omitempty"`
+ // Server-assigned sandbox ID. If non-empty, worker uses this instead of generating one.
+ SandboxId string `protobuf:"bytes,12,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
}
func (x *CreateSandboxRequest) Reset() {
@@ -184,6 +188,20 @@ func (x *CreateSandboxRequest) GetTemplateWorkspaceKey() string {
return ""
}
+func (x *CreateSandboxRequest) GetCheckpointId() string {
+ if x != nil {
+ return x.CheckpointId
+ }
+ return ""
+}
+
+func (x *CreateSandboxRequest) GetSandboxId() string {
+ if x != nil {
+ return x.SandboxId
+ }
+ return ""
+}
+
type CreateSandboxResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`
@@ -2146,7 +2164,7 @@ var File_proto_worker_worker_proto protoreflect.FileDescriptor
const file_proto_worker_worker_proto_rawDesc = "" +
"\n" +
- "\x19proto/worker/worker.proto\x12\x06worker\"\xbb\x03\n" +
+ "\x19proto/worker/worker.proto\x12\x06worker\"\xff\x03\n" +
"\x14CreateSandboxRequest\x12\x1a\n" +
"\btemplate\x18\x01 \x01(\tR\btemplate\x12\x18\n" +
"\atimeout\x18\x02 \x01(\x05R\atimeout\x12:\n" +
@@ -2158,7 +2176,10 @@ const file_proto_worker_worker_proto_rawDesc = "" +
"\x04port\x18\b \x01(\x05R\x04port\x12.\n" +
"\x13template_rootfs_key\x18\t \x01(\tR\x11templateRootfsKey\x124\n" +
"\x16template_workspace_key\x18\n" +
- " \x01(\tR\x14templateWorkspaceKey\x1a7\n" +
+ " \x01(\tR\x14templateWorkspaceKey\x12#\n" +
+ "\rcheckpoint_id\x18\v \x01(\tR\fcheckpointId\x12\x1d\n" +
+ "\n" +
+ "sandbox_id\x18\f \x01(\tR\tsandboxId\x1a7\n" +
"\tEnvsEntry\x12\x10\n" +
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
"\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"N\n" +
diff --git a/proto/worker/worker.proto b/proto/worker/worker.proto
index a1eb63ca..0679ee9b 100644
--- a/proto/worker/worker.proto
+++ b/proto/worker/worker.proto
@@ -45,6 +45,10 @@ message CreateSandboxRequest {
// Sandbox snapshot template: if non-empty, boot from these S3 keys instead of base image.
string template_rootfs_key = 9;
string template_workspace_key = 10;
+ // If set, attempt warm fork from local checkpoint snapshot (LoadSnapshot instead of cold boot).
+ string checkpoint_id = 11;
+ // Server-assigned sandbox ID. If non-empty, worker uses this instead of generating one.
+ string sandbox_id = 12;
}
message CreateSandboxResponse {
diff --git a/sdks/typescript/examples/bench-checkpoints.ts b/sdks/typescript/examples/bench-checkpoints.ts
index a25188bc..72dfb4d6 100644
--- a/sdks/typescript/examples/bench-checkpoints.ts
+++ b/sdks/typescript/examples/bench-checkpoints.ts
@@ -18,8 +18,6 @@ import { Sandbox } from "../src/index";
function bold(msg: string) { console.log(`\x1b[1m${msg}\x1b[0m`); }
function dim(msg: string) { console.log(`\x1b[2m ${msg}\x1b[0m`); }
-function cyan(msg: string) { console.log(`\x1b[36m${msg}\x1b[0m`); }
-function green(msg: string) { console.log(`\x1b[32m${msg}\x1b[0m`); }
function red(msg: string) { console.log(`\x1b[31m${msg}\x1b[0m`); }
async function sleep(ms: number) {
@@ -93,6 +91,7 @@ async function main() {
console.log();
const timings: Timing[] = [];
+ const createSbTiming: Timing = { label: "Create sandbox", samples: [] };
const createTiming: Timing = { label: "Create checkpoint", samples: [] };
const listTiming: Timing = { label: "List checkpoints", samples: [] };
const restoreTiming: Timing = { label: "Restore (in-place)", samples: [] };
@@ -100,24 +99,50 @@ async function main() {
const deleteTiming: Timing = { label: "Delete checkpoint", samples: [] };
const firstCmdTiming: Timing = { label: "First cmd after restore", samples: [] };
- timings.push(createTiming, listTiming, restoreTiming, firstCmdTiming, forkTiming, deleteTiming);
+ timings.push(createSbTiming, createTiming, listTiming, restoreTiming, firstCmdTiming, forkTiming, deleteTiming);
const sandboxes: Sandbox[] = [];
try {
- // ── Setup ──────────────────────────────────────────────────────
- bold("━━━ Setup ━━━\n");
+ // ── Benchmark: Create sandbox ─────────────────────────────────
+ bold("━━━ Create sandbox ━━━\n");
- const { result: sandbox, ms: createSbMs } = await timed(() =>
- Sandbox.create({ template: "base", timeout: 300 }),
- );
- sandboxes.push(sandbox);
- dim(`Sandbox created: ${sandbox.sandboxId} (${formatMs(createSbMs)})`);
+ let sandbox!: Sandbox;
+ for (let i = 0; i < ITERATIONS; i++) {
+ const { result: sb, ms } = await timed(() =>
+ Sandbox.create({ template: "base", timeout: 300 }),
+ );
+ createSbTiming.samples.push(ms);
+ sandboxes.push(sb);
+ dim(`#${i + 1}: ${formatMs(ms)} (sandbox=${sb.sandboxId})`);
+ if (i === 0) sandbox = sb;
+ // Kill extra sandboxes — we only need the first for remaining benchmarks
+ if (i > 0) sb.kill().catch(() => {});
+ }
+ console.log();
- // Write some state so the workspace isn't empty
- await sandbox.commands.run("dd if=/dev/urandom of=/workspace/payload.bin bs=1M count=10 2>/dev/null");
+ // ── Setup ──────────────────────────────────────────────────────
+ bold("━━━ Setup ━━━\n");
+ dim(`Using sandbox ${sandbox.sandboxId} for checkpoint benchmarks`);
+
+ // Write payload data to workspace
+ const payloadMB = parseInt(process.env.BENCH_PAYLOAD_MB || "10240", 10);
+ const payloadGB = payloadMB / 1024;
+ dim(`Writing ${payloadMB >= 1024 ? payloadGB + " GB" : payloadMB + " MB"} payload...`);
+ const { ms: writeMs } = await timed(async () => {
+ if (payloadMB >= 1024) {
+ // Write in 1GB chunks for large payloads
+ const chunks = Math.ceil(payloadMB / 1024);
+ for (let i = 0; i < chunks; i++) {
+ await sandbox.commands.run(`dd if=/dev/urandom of=/workspace/payload-${i}.bin bs=1M count=1024 2>/dev/null`, { timeout: 300 });
+ dim(` chunk ${i + 1}/${chunks} written`);
+ }
+ } else {
+ await sandbox.commands.run(`dd if=/dev/urandom of=/workspace/payload.bin bs=1M count=${payloadMB} 2>/dev/null`, { timeout: 120 });
+ }
+ });
await sandbox.commands.run("echo bench-state > /workspace/marker.txt");
- dim("Wrote 10 MB payload + marker file");
+ dim(`Wrote ${payloadMB >= 1024 ? payloadGB + " GB" : payloadMB + " MB"} payload + marker file (${formatMs(writeMs)})`);
console.log();
// ── Benchmark: Create checkpoint ───────────────────────────────