Skip to content

An open-source, faster Devin alternative

TypeScript

remove old code

Brian Reardon18473541bc45
diff --git a/cmd/worker/main.go b/cmd/worker/main.go
index 7bc9cef7..8a652978 100644
--- a/cmd/worker/main.go
+++ b/cmd/worker/main.go
@@ -32,7 +32,7 @@ func main() {
log.Fatalf("failed to load config: %v", err)
}
- log.Printf("opensandbox-worker: starting (id=%s, region=%s, backend=%s)...", cfg.WorkerID, cfg.Region, cfg.VMBackend)
+ log.Printf("opensandbox-worker: starting (id=%s, region=%s, backend=qemu)...", cfg.WorkerID, cfg.Region)
ctx := context.Background()
diff --git a/internal/config/config.go b/internal/config/config.go
index 0e9e04f7..108be1e9 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -66,19 +66,13 @@ type Config struct {
DefaultSandboxCPUs int // default vCPUs per sandbox, default 1
DefaultSandboxDiskMB int // default disk quota per sandbox (MB), 0 = no quota
- // VM backend selection (worker mode)
- VMBackend string // "firecracker" or "qemu" (default: "qemu")
-
- // Firecracker microVM configuration (worker mode)
- FirecrackerBin string // Path to firecracker binary (default: "firecracker")
- KernelPath string // Path to vmlinux kernel (default: $DataDir/firecracker/vmlinux-arm64)
- ImagesDir string // Path to base rootfs images (default: $DataDir/firecracker/images/)
-
- // QEMU configuration (worker mode, when VMBackend="qemu")
- QEMUBin string // Path to qemu-system-x86_64 binary (default: "qemu-system-x86_64")
+ // QEMU VM configuration (worker mode)
+ KernelPath string // Path to vmlinux kernel
+ ImagesDir string // Path to base rootfs images
+ QEMUBin string // Path to qemu-system binary (default: "qemu-system-x86_64")
// AWS EC2 compute pool (server mode only — for auto-scaling worker machines)
- EC2AMI string // Custom AMI with Firecracker pre-installed
+ EC2AMI string // Custom AMI for worker instances
EC2InstanceType string // e.g. "c7gd.metal", "r6gd.metal", "r7gd.metal"
EC2SubnetID string // VPC subnet for worker instances
EC2SecurityGroupID string // Security group (allow 8080, 9090, 9091)
@@ -154,8 +148,6 @@ func Load() (*Config, error) {
DefaultSandboxCPUs: envOrDefaultInt("OPENSANDBOX_DEFAULT_SANDBOX_CPUS", 1),
DefaultSandboxDiskMB: envOrDefaultInt("OPENSANDBOX_DEFAULT_SANDBOX_DISK_MB", 0),
- VMBackend: envOrDefault("OPENSANDBOX_VM_BACKEND", "qemu"),
- FirecrackerBin: envOrDefault("OPENSANDBOX_FIRECRACKER_BIN", "firecracker"),
KernelPath: os.Getenv("OPENSANDBOX_KERNEL_PATH"), // default derived from DataDir
ImagesDir: os.Getenv("OPENSANDBOX_IMAGES_DIR"), // default derived from DataDir
QEMUBin: envOrDefault("OPENSANDBOX_QEMU_BIN", "qemu-system-x86_64"),
diff --git a/internal/firecracker/agent_client.go b/internal/firecracker/agent_client.go
deleted file mode 100644
index 7d4c2364..00000000
--- a/internal/firecracker/agent_client.go
+++ /dev/null
@@ -1,278 +0,0 @@
-package firecracker
-
-import (
- "bufio"
- "context"
- "fmt"
- "net"
- "strings"
- "time"
-
- pb "github.com/opensandbox/opensandbox/proto/agent"
- "google.golang.org/grpc"
- "google.golang.org/grpc/backoff"
- "google.golang.org/grpc/credentials/insecure"
-)
-
-// AgentClient is the host-side gRPC client that connects to the
-// osb-agent running inside a Firecracker VM via vsock.
-type AgentClient struct {
- conn *grpc.ClientConn
- client pb.SandboxAgentClient
-}
-
-// NewAgentClient connects to the agent via the Firecracker vsock UDS.
-// In --no-api mode, Firecracker creates a single UDS file (vsock.sock).
-// To reach a guest port, the host connects to the UDS and sends
-// "CONNECT <port>\n". Firecracker responds with "OK <buf_size>\n"
-// and the connection is then relayed to the guest.
-func NewAgentClient(vsockPath string) (*AgentClient, error) {
- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
- defer cancel()
-
- conn, err := grpc.DialContext(ctx,
- // Use passthrough scheme — the custom dialer handles the actual connection
- "passthrough:///vsock",
- grpc.WithTransportCredentials(insecure.NewCredentials()),
- grpc.WithBlock(),
- grpc.WithConnectParams(grpc.ConnectParams{
- Backoff: backoff.Config{
- BaseDelay: 10 * time.Millisecond,
- Multiplier: 1.6,
- Jitter: 0.2,
- MaxDelay: 1 * time.Second,
- },
- }),
- grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) {
- return dialVsock(ctx, vsockPath, 1024)
- }),
- grpc.WithDefaultCallOptions(
- grpc.MaxCallRecvMsgSize(64*1024*1024),
- grpc.MaxCallSendMsgSize(64*1024*1024),
- ),
- )
- if err != nil {
- return nil, fmt.Errorf("connect to agent at %s: %w", vsockPath, err)
- }
-
- return &AgentClient{
- conn: conn,
- client: pb.NewSandboxAgentClient(conn),
- }, nil
-}
-
-// dialVsock connects to a guest port via Firecracker's vsock UDS protocol.
-// Protocol: connect to the UDS, send "CONNECT <port>\n", read "OK ...\n".
-func dialVsock(ctx context.Context, vsockPath string, port int) (net.Conn, error) {
- deadline, ok := ctx.Deadline()
- if !ok {
- deadline = time.Now().Add(5 * time.Second)
- }
-
- d := net.Dialer{Deadline: deadline}
- conn, err := d.DialContext(ctx, "unix", vsockPath)
- if err != nil {
- return nil, fmt.Errorf("dial vsock UDS %s: %w", vsockPath, err)
- }
-
- // Send CONNECT command
- _ = conn.SetDeadline(deadline)
- if _, err := fmt.Fprintf(conn, "CONNECT %d\n", port); err != nil {
- conn.Close()
- return nil, fmt.Errorf("send CONNECT %d: %w", port, err)
- }
-
- // Read response line (e.g., "OK 1073741824\n")
- reader := bufio.NewReader(conn)
- line, err := reader.ReadString('\n')
- if err != nil {
- conn.Close()
- return nil, fmt.Errorf("read vsock response: %w", err)
- }
- line = strings.TrimSpace(line)
- if !strings.HasPrefix(line, "OK") {
- conn.Close()
- return nil, fmt.Errorf("vsock CONNECT failed: %s", line)
- }
-
- // Clear deadline — gRPC manages its own timeouts
- _ = conn.SetDeadline(time.Time{})
-
- // Wrap to handle the buffered reader (there may be buffered data from the OK line)
- return &vsockConn{Conn: conn, reader: reader}, nil
-}
-
-// vsockConn wraps a net.Conn with a bufio.Reader to handle buffered reads
-// from the CONNECT handshake.
-type vsockConn struct {
- net.Conn
- reader *bufio.Reader
-}
-
-func (c *vsockConn) Read(p []byte) (int, error) {
- return c.reader.Read(p)
-}
-
-// Close closes the gRPC connection.
-func (c *AgentClient) Close() error {
- if c == nil || c.conn == nil {
- return nil
- }
- return c.conn.Close()
-}
-
-// SetEnvs sends sandbox-level environment variables to the in-VM agent.
-func (c *AgentClient) SetEnvs(ctx context.Context, envs map[string]string) error {
- _, err := c.client.SetEnvs(ctx, &pb.SetEnvsRequest{Envs: envs})
- return err
-}
-
-// Ping verifies the agent is responsive.
-func (c *AgentClient) Ping(ctx context.Context) (*pb.PingResponse, error) {
- return c.client.Ping(ctx, &pb.PingRequest{})
-}
-
-// Exec runs a command in the VM.
-func (c *AgentClient) Exec(ctx context.Context, req *pb.ExecRequest) (*pb.ExecResponse, error) {
- return c.client.Exec(ctx, req)
-}
-
-// ReadFile reads a file from the VM.
-func (c *AgentClient) ReadFile(ctx context.Context, path string) ([]byte, error) {
- resp, err := c.client.ReadFile(ctx, &pb.ReadFileRequest{Path: path})
- if err != nil {
- return nil, err
- }
- return resp.Content, nil
-}
-
-// WriteFile writes a file in the VM.
-func (c *AgentClient) WriteFile(ctx context.Context, path string, content []byte) error {
- _, err := c.client.WriteFile(ctx, &pb.WriteFileRequest{Path: path, Content: content})
- return err
-}
-
-// ListDir lists a directory in the VM.
-func (c *AgentClient) ListDir(ctx context.Context, path string) ([]*pb.DirEntry, error) {
- resp, err := c.client.ListDir(ctx, &pb.ListDirRequest{Path: path})
- if err != nil {
- return nil, err
- }
- return resp.Entries, nil
-}
-
-// MakeDir creates a directory in the VM.
-func (c *AgentClient) MakeDir(ctx context.Context, path string) error {
- _, err := c.client.MakeDir(ctx, &pb.MakeDirRequest{Path: path})
- return err
-}
-
-// Remove removes a file/directory in the VM.
-func (c *AgentClient) Remove(ctx context.Context, path string) error {
- _, err := c.client.Remove(ctx, &pb.RemoveRequest{Path: path})
- return err
-}
-
-// Exists checks if a path exists in the VM.
-func (c *AgentClient) Exists(ctx context.Context, path string) (bool, error) {
- resp, err := c.client.Exists(ctx, &pb.ExistsRequest{Path: path})
- if err != nil {
- return false, err
- }
- return resp.Exists, nil
-}
-
-// Stat returns file metadata from the VM.
-func (c *AgentClient) Stat(ctx context.Context, path string) (*pb.StatResponse, error) {
- return c.client.Stat(ctx, &pb.StatRequest{Path: path})
-}
-
-// Stats returns resource usage from the VM.
-func (c *AgentClient) Stats(ctx context.Context) (*pb.StatsResponse, error) {
- return c.client.Stats(ctx, &pb.StatsRequest{})
-}
-
-// Shutdown gracefully stops the agent.
-func (c *AgentClient) Shutdown(ctx context.Context) error {
- _, err := c.client.Shutdown(ctx, &pb.ShutdownRequest{})
- return err
-}
-
-// SyncFS flushes all filesystem buffers inside the VM without exiting the agent.
-func (c *AgentClient) SyncFS(ctx context.Context) error {
- _, err := c.client.SyncFS(ctx, &pb.SyncFSRequest{})
- return err
-}
-
-// PTYCreate creates a new PTY session in the VM.
-func (c *AgentClient) PTYCreate(ctx context.Context, cols, rows int32, shell string) (sessionID string, dataPort uint32, err error) {
- resp, err := c.client.PTYCreate(ctx, &pb.PTYCreateRequest{
- Cols: cols,
- Rows: rows,
- Shell: shell,
- })
- if err != nil {
- return "", 0, err
- }
- return resp.SessionId, resp.DataPort, nil
-}
-
-// PTYResize resizes a PTY session.
-func (c *AgentClient) PTYResize(ctx context.Context, sessionID string, cols, rows int32) error {
- _, err := c.client.PTYResize(ctx, &pb.PTYResizeRequest{
- SessionId: sessionID,
- Cols: cols,
- Rows: rows,
- })
- return err
-}
-
-// PTYKill terminates a PTY session.
-func (c *AgentClient) PTYKill(ctx context.Context, sessionID string) error {
- _, err := c.client.PTYKill(ctx, &pb.PTYKillRequest{SessionId: sessionID})
- return err
-}
-
-// ExecSessionCreate creates a new exec session in the VM.
-func (c *AgentClient) ExecSessionCreate(ctx context.Context, req *pb.ExecSessionCreateRequest) (string, error) {
- resp, err := c.client.ExecSessionCreate(ctx, req)
- if err != nil {
- return "", err
- }
- return resp.SessionId, nil
-}
-
-// ExecSessionAttach connects to an exec session's bidi stream.
-func (c *AgentClient) ExecSessionAttach(ctx context.Context) (pb.SandboxAgent_ExecSessionAttachClient, error) {
- return c.client.ExecSessionAttach(ctx)
-}
-
-// ExecSessionList lists all exec sessions in the VM.
-func (c *AgentClient) ExecSessionList(ctx context.Context) ([]*pb.ExecSessionInfo, error) {
- resp, err := c.client.ExecSessionList(ctx, &pb.ExecSessionListRequest{})
- if err != nil {
- return nil, err
- }
- return resp.Sessions, nil
-}
-
-// ExecSessionKill kills an exec session in the VM.
-func (c *AgentClient) ExecSessionKill(ctx context.Context, sessionID string, signal int32) error {
- _, err := c.client.ExecSessionKill(ctx, &pb.ExecSessionKillRequest{
- SessionId: sessionID,
- Signal: signal,
- })
- return err
-}
-
-// ConnectPTYData connects to the PTY data stream on the given vsock port.
-// Returns a raw TCP-like connection for bidirectional PTY I/O.
-func (c *AgentClient) ConnectPTYData(vsockPath string, dataPort uint32) (net.Conn, error) {
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
- defer cancel()
- conn, err := dialVsock(ctx, vsockPath, int(dataPort))
- if err != nil {
- return nil, fmt.Errorf("connect to PTY data port %d: %w", dataPort, err)
- }
- return conn, nil
-}
diff --git a/internal/firecracker/api.go b/internal/firecracker/api.go
deleted file mode 100644
index 8b18c6aa..00000000
--- a/internal/firecracker/api.go
+++ /dev/null
@@ -1,200 +0,0 @@
-package firecracker
-
-import (
- "bytes"
- "context"
- "encoding/json"
- "fmt"
- "io"
- "net"
- "net/http"
- "os"
- "time"
-)
-
-// FirecrackerClient is a minimal HTTP client for the Firecracker API socket.
-type FirecrackerClient struct {
- socketPath string
- httpClient *http.Client
-}
-
-// NewFirecrackerClient creates a client that talks to a Firecracker instance
-// via its Unix domain API socket.
-func NewFirecrackerClient(socketPath string) *FirecrackerClient {
- transport := &http.Transport{
- DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
- d := net.Dialer{}
- return d.DialContext(ctx, "unix", socketPath)
- },
- }
- return &FirecrackerClient{
- socketPath: socketPath,
- // No global timeout — per-request timeouts are set via context in doRequest/doRequestWithTimeout.
- httpClient: &http.Client{Transport: transport},
- }
-}
-
-// WaitForSocket polls until the API socket file exists on disk.
-func (c *FirecrackerClient) WaitForSocket(timeout time.Duration) error {
- deadline := time.Now().Add(timeout)
- for time.Now().Before(deadline) {
- if _, err := os.Stat(c.socketPath); err == nil {
- return nil
- }
- time.Sleep(50 * time.Millisecond)
- }
- return fmt.Errorf("firecracker API socket %s not ready after %v", c.socketPath, timeout)
-}
-
-// PutBootSource configures the kernel boot source.
-func (c *FirecrackerClient) PutBootSource(kernelPath, bootArgs string) error {
- body := map[string]string{
- "kernel_image_path": kernelPath,
- "boot_args": bootArgs,
- }
- return c.put("/boot-source", body)
-}
-
-// PutDrive attaches a block device (drive) to the VM.
-func (c *FirecrackerClient) PutDrive(driveID, pathOnHost string, isRootDevice, isReadOnly bool) error {
- body := map[string]interface{}{
- "drive_id": driveID,
- "path_on_host": pathOnHost,
- "is_root_device": isRootDevice,
- "is_read_only": isReadOnly,
- }
- 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{}{
- "iface_id": ifaceID,
- "guest_mac": guestMAC,
- "host_dev_name": hostDevName,
- }
- return c.putWithID("/network-interfaces", ifaceID, body)
-}
-
-// PutVsock configures the vsock device.
-func (c *FirecrackerClient) PutVsock(guestCID uint32, udsPath string) error {
- body := map[string]interface{}{
- "guest_cid": guestCID,
- "uds_path": udsPath,
- }
- return c.put("/vsock", body)
-}
-
-// PutMachineConfig sets vCPU count and memory size.
-func (c *FirecrackerClient) PutMachineConfig(vcpuCount, memSizeMib int) error {
- body := map[string]interface{}{
- "vcpu_count": vcpuCount,
- "mem_size_mib": memSizeMib,
- }
- return c.put("/machine-config", body)
-}
-
-// StartInstance boots the configured VM.
-func (c *FirecrackerClient) StartInstance() error {
- body := map[string]string{
- "action_type": "InstanceStart",
- }
- return c.put("/actions", body)
-}
-
-// PauseVM pauses a running VM.
-func (c *FirecrackerClient) PauseVM() error {
- body := map[string]string{
- "state": "Paused",
- }
- return c.patch("/vm", body)
-}
-
-// ResumeVM resumes a paused VM.
-func (c *FirecrackerClient) ResumeVM() error {
- body := map[string]string{
- "state": "Resumed",
- }
- return c.patch("/vm", body)
-}
-
-// 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.doRequestWithTimeout(http.MethodPut, "/snapshot/create", body, 5*time.Minute)
-}
-
-// LoadSnapshot restores a VM from a snapshot.
-// If resumeVM is true, the VM starts running immediately after load.
-func (c *FirecrackerClient) LoadSnapshot(snapshotPath, memFilePath string, resumeVM bool) error {
- body := map[string]interface{}{
- "snapshot_path": snapshotPath,
- "mem_backend": map[string]string{
- "backend_path": memFilePath,
- "backend_type": "File",
- },
- "enable_diff_snapshots": false,
- "resume_vm": resumeVM,
- }
- return c.put("/snapshot/load", body)
-}
-
-func (c *FirecrackerClient) put(path string, body interface{}) error {
- return c.doRequest(http.MethodPut, path, body)
-}
-
-func (c *FirecrackerClient) putWithID(basePath, id string, body interface{}) error {
- return c.doRequest(http.MethodPut, basePath+"/"+id, body)
-}
-
-func (c *FirecrackerClient) patch(path string, body interface{}) error {
- return c.doRequest(http.MethodPatch, path, body)
-}
-
-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)
- }
-
- 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)
- }
- req.Header.Set("Content-Type", "application/json")
-
- resp, err := c.httpClient.Do(req)
- if err != nil {
- return fmt.Errorf("firecracker API %s %s: %w", method, path, err)
- }
- defer resp.Body.Close()
-
- if resp.StatusCode >= 300 {
- respBody, _ := io.ReadAll(resp.Body)
- return fmt.Errorf("firecracker API %s %s returned %d: %s", method, path, resp.StatusCode, string(respBody))
- }
-
- 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
deleted file mode 100644
index 6503135d..00000000
--- a/internal/firecracker/manager.go
+++ /dev/null
@@ -1,1195 +0,0 @@
-// Package firecracker implements sandbox.Manager using Firecracker microVMs.
-// Each sandbox is a lightweight VM with its own kernel, rootfs, and workspace,
-// communicating with the host via gRPC over vsock.
-package firecracker
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "log"
- "os"
- "os/exec"
- "path/filepath"
- "strings"
- "sync"
- "time"
-
- "github.com/google/uuid"
- "github.com/opensandbox/opensandbox/internal/sandbox"
- "github.com/opensandbox/opensandbox/internal/storage"
- "github.com/opensandbox/opensandbox/pkg/types"
- pb "github.com/opensandbox/opensandbox/proto/agent"
-)
-
-// Compile-time check that Manager implements sandbox.Manager.
-var _ sandbox.Manager = (*Manager)(nil)
-
-// VMInstance holds the state of a running Firecracker microVM.
-type VMInstance struct {
- ID string
- Template string
- Status types.SandboxStatus
- StartedAt time.Time
- EndAt time.Time
- CpuCount int
- MemoryMB int
- HostPort int
- GuestPort int
-
- // VM internals
- pid int // Firecracker VMM process PID
- cmd *exec.Cmd // Firecracker process
- network *NetworkConfig
- vsockPath string // path to vsock UDS on host
- sandboxDir string // /data/sandboxes/{id}/
- agent *AgentClient // gRPC client to in-VM agent
- apiSockPath string // path to Firecracker API socket
- fcClient *FirecrackerClient // API client for this VM's Firecracker process
- 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
- sealedTokens map[string]string // sealed token → real value (for re-registering proxy on wake)
-}
-
-// SandboxMeta is persisted to sandbox-meta.json in each sandbox directory.
-// It records VM config so that on hard kill recovery, a sandbox can be
-// cold-booted from template + existing workspace without needing DB access.
-type SandboxMeta struct {
- SandboxID string `json:"sandboxId"`
- Template string `json:"template"`
- CpuCount int `json:"cpuCount"`
- MemoryMB int `json:"memoryMB"`
- GuestPort int `json:"guestPort"`
-}
-
-// SecretsProxyIntegration provides the interface for the secrets proxy to integrate
-// with VM lifecycle. The firecracker package uses this interface to avoid importing
-// the secretsproxy package directly.
-type SecretsProxyIntegration interface {
- // CreateSealedEnvs generates sealed tokens for env vars, registers a proxy session,
- // and returns the full env map (sealed tokens + proxy config vars) to inject into the VM.
- // secretAllowedHosts maps env var name → allowed hosts for that secret (nil = all allowed hosts).
- CreateSealedEnvs(sandboxID, guestIP, gatewayIP string, envVars map[string]string, allowlist []string, secretAllowedHosts map[string][]string) map[string]string
- // UnregisterSession removes the proxy session for the given guest IP.
- UnregisterSession(guestIP string)
- // GetSessionTokens returns the sealed token → real value map for persisting during hibernate.
- GetSessionTokens(guestIP string) map[string]string
- // GetSessionAllowlist returns the egress allowlist for persisting during hibernate.
- GetSessionAllowlist(guestIP string) []string
- // GetSessionTokenHosts returns the per-token host restrictions for persisting during hibernate.
- GetSessionTokenHosts(guestIP string) map[string][]string
- // ReregisterSession re-creates a proxy session from a persisted token map (used on wake).
- ReregisterSession(sandboxID, guestIP string, tokens map[string]string, allowlist []string, tokenHosts map[string][]string)
- // CACertPEM returns the CA certificate PEM for injection into the VM trust store.
- CACertPEM() []byte
-}
-
-// Config holds configuration for the Firecracker Manager.
-type Config struct {
- DataDir string // base data directory (e.g., /data)
- KernelPath string // path to vmlinux (e.g., /data/firecracker/vmlinux-arm64)
- ImagesDir string // path to base rootfs images (e.g., /data/firecracker/images/)
- FirecrackerBin string // path to firecracker binary (default: "firecracker")
- DefaultMemoryMB int // default RAM per VM (default: 512)
- DefaultCPUs int // default vCPUs per VM (default: 1)
- DefaultDiskMB int // default workspace size in MB (default: 20480 = 20GB)
- 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
- subnets *SubnetAllocator
-
- mu sync.RWMutex
- 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
- templateGoldens map[string]*GoldenSnapshot // per-checkpoint golden snapshots for templates/images
-
- secretsProxy SecretsProxyIntegration // nil if secrets proxy is not configured
-}
-
-// NewManager creates a new Firecracker-backed sandbox manager.
-func NewManager(cfg Config) (*Manager, error) {
- if cfg.DataDir == "" {
- return nil, fmt.Errorf("DataDir is required")
- }
- if cfg.KernelPath == "" {
- cfg.KernelPath = filepath.Join(cfg.DataDir, "firecracker", "vmlinux-arm64")
- }
- if cfg.ImagesDir == "" {
- cfg.ImagesDir = filepath.Join(cfg.DataDir, "firecracker", "images")
- }
- if cfg.FirecrackerBin == "" {
- cfg.FirecrackerBin = "firecracker"
- }
- if cfg.DefaultMemoryMB == 0 {
- cfg.DefaultMemoryMB = 512
- }
- if cfg.DefaultCPUs == 0 {
- cfg.DefaultCPUs = 1
- }
- if cfg.DefaultDiskMB == 0 {
- cfg.DefaultDiskMB = 20480 // 20GB
- }
- if cfg.DefaultPort == 0 {
- cfg.DefaultPort = 80
- }
-
- // Verify kernel exists
- if _, err := os.Stat(cfg.KernelPath); err != nil {
- return nil, fmt.Errorf("kernel not found at %s: %w", cfg.KernelPath, err)
- }
-
- // Verify firecracker binary
- if _, err := exec.LookPath(cfg.FirecrackerBin); err != nil {
- return nil, fmt.Errorf("firecracker binary not found: %w", err)
- }
-
- // Enable IP forwarding for VM networking
- if err := EnableForwarding(); err != nil {
- log.Printf("firecracker: warning: could not enable IP forwarding: %v", err)
- }
-
- return &Manager{
- cfg: cfg,
- subnets: NewSubnetAllocator(),
- vms: make(map[string]*VMInstance),
- nextCID: 3, // CIDs 0-2 are reserved (hypervisor=0, local=1, host=2)
- templateGoldens: make(map[string]*GoldenSnapshot),
- }, nil
-}
-
-// SetSecretsProxy configures the secrets proxy integration for token substitution.
-// Must be called before any sandboxes are created.
-func (m *Manager) SetSecretsProxy(sp SecretsProxyIntegration) {
- m.secretsProxy = sp
-}
-
-// allocateCID returns a unique guest CID for a new VM.
-func (m *Manager) allocateCID() uint32 {
- m.mu.Lock()
- defer m.mu.Unlock()
- cid := m.nextCID
- m.nextCID++
- return cid
-}
-
-// Create launches a new Firecracker microVM.
-func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (*types.Sandbox, error) {
- 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)
- }
- }
- // Per-template golden snapshot: if creating from a checkpoint (image/snapshot),
- // try the golden snapshot path keyed by checkpoint ID.
- if cfg.CheckpointID != "" && cfg.TemplateRootfsKey != "" {
- if sb, err := m.createFromGoldenSnapshot(ctx, id, cfg); err == nil {
- return sb, nil
- } else if err != errNoGoldenSnapshot {
- log.Printf("firecracker: template golden snapshot create failed for %s (cp=%s): %v, falling back to cold boot", id, cfg.CheckpointID, 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)
- }
-
- rootfsPath := filepath.Join(sandboxDir, "rootfs.ext4")
- workspacePath := filepath.Join(sandboxDir, "workspace.ext4")
-
- if cfg.TemplateRootfsKey != "" {
- // Sandbox snapshot template: gRPC handler extracted template drives to local paths
- // encoded as "local://<absolute-path>" in TemplateRootfsKey / TemplateWorkspaceKey.
- srcRootfs := strings.TrimPrefix(cfg.TemplateRootfsKey, "local://")
- srcWorkspace := strings.TrimPrefix(cfg.TemplateWorkspaceKey, "local://")
- log.Printf("firecracker: create %s from snapshot template (rootfs=%s, workspace=%s)", id, srcRootfs, srcWorkspace)
- if err := copyFileReflink(srcRootfs, rootfsPath); err != nil {
- os.RemoveAll(sandboxDir)
- return nil, fmt.Errorf("copy template rootfs: %w", err)
- }
- if err := copyFileReflink(srcWorkspace, workspacePath); err != nil {
- os.RemoveAll(sandboxDir)
- return nil, fmt.Errorf("copy template workspace: %w", err)
- }
- } else {
- // Standard base image + fresh workspace
- baseImage, err := ResolveBaseImage(m.cfg.ImagesDir, template)
- if err != nil {
- os.RemoveAll(sandboxDir)
- return nil, fmt.Errorf("resolve base image: %w", err)
- }
- if err := PrepareRootfs(baseImage, rootfsPath); err != nil {
- os.RemoveAll(sandboxDir)
- return nil, fmt.Errorf("prepare rootfs: %w", err)
- }
-
- diskMB := m.cfg.DefaultDiskMB
- if err := CreateWorkspace(workspacePath, diskMB); err != nil {
- os.RemoveAll(sandboxDir)
- return nil, fmt.Errorf("create workspace: %w", err)
- }
- }
-
- // Allocate network
- netCfg, err := m.subnets.Allocate()
- if err != nil {
- os.RemoveAll(sandboxDir)
- return nil, fmt.Errorf("allocate subnet: %w", err)
- }
-
- // Create TAP device
- if err := CreateTAP(netCfg); err != nil {
- m.subnets.Release(netCfg.TAPName)
- os.RemoveAll(sandboxDir)
- return nil, fmt.Errorf("create TAP: %w", err)
- }
-
- // Find free host port for port forwarding
- guestPort := cfg.Port
- if guestPort == 0 {
- guestPort = m.cfg.DefaultPort
- }
- 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 = guestPort
-
- // Add DNAT rule
- 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)
- }
-
- // Configure vCPU and memory
- cpus := cfg.CpuCount
- if cpus <= 0 {
- cpus = m.cfg.DefaultCPUs
- }
- memMB := cfg.MemoryMB
- if memMB <= 0 {
- memMB = m.cfg.DefaultMemoryMB
- }
-
- // Vsock UDS path and unique CID
- vsockPath := filepath.Join(sandboxDir, "vsock.sock")
- guestCID := m.allocateCID()
-
- // Build kernel boot args
- // The init script in the rootfs reads these to configure networking
- 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,
- )
-
- // Generate a deterministic MAC from the sandbox ID
- guestMAC := generateMAC(id)
-
- // Start Firecracker with API socket (enables snapshot support)
- apiSockPath := filepath.Join(sandboxDir, "firecracker.sock")
- os.Remove(apiSockPath) // clean stale socket
-
- 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()
-
- // Configure VM via API socket
- 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)
- }
-
- if err := fcClient.PutMachineConfig(cpus, memMB); err != nil {
- cmd.Process.Kill()
- cmd.Wait()
- m.cleanupVM(netCfg, sandboxDir)
- return nil, 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, sandboxDir)
- return nil, 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, sandboxDir)
- return nil, 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, sandboxDir)
- return nil, 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, sandboxDir)
- return nil, fmt.Errorf("put network interface: %w", err)
- }
- if err := fcClient.PutVsock(guestCID, vsockPath); err != nil {
- cmd.Process.Kill()
- cmd.Wait()
- m.cleanupVM(netCfg, sandboxDir)
- return nil, fmt.Errorf("put vsock: %w", err)
- }
- if err := fcClient.StartInstance(); err != nil {
- cmd.Process.Kill()
- cmd.Wait()
- m.cleanupVM(netCfg, sandboxDir)
- return nil, fmt.Errorf("start instance: %w", err)
- }
-
- now := time.Now()
- timeout := time.Duration(cfg.Timeout) * time.Second
- if timeout <= 0 {
- timeout = 300 * time.Second
- }
-
- vm := &VMInstance{
- ID: id,
- Template: template,
- 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: guestMAC,
- guestCID: guestCID,
- bootArgs: bootArgs,
- }
-
- // Wait for agent to become available (use background context so gRPC deadline doesn't kill us)
- agentClient, err := m.waitForAgent(context.Background(), vsockPath, 30*time.Second)
- if err != nil {
- log.Printf("firecracker: agent not ready for %s, killing VM: %v", id, err)
- cmd.Process.Kill()
- cmd.Wait()
- m.cleanupVM(netCfg, sandboxDir)
- return nil, fmt.Errorf("agent not ready: %w", err)
- }
- vm.agent = agentClient
-
- // Secrets proxy integration: seal env vars and set up proxy redirect.
- // Sealed tokens replace real values inside the VM — the MITM proxy swaps
- // them back to real values on outbound HTTPS requests.
- envsToInject := cfg.Envs
- if m.secretsProxy != nil && len(cfg.Envs) > 0 {
- sealedEnvs := m.secretsProxy.CreateSealedEnvs(id, netCfg.GuestIP, netCfg.HostIP, cfg.Envs, cfg.EgressAllowlist, cfg.SecretAllowedHosts)
- if sealedEnvs != nil {
- envsToInject = sealedEnvs
- // Redirect VM HTTPS traffic through the proxy
- if err := AddProxyRedirect(netCfg); err != nil {
- log.Printf("firecracker: warning: proxy redirect failed for %s: %v", id, err)
- }
- // Inject CA cert into VM trust store
- m.injectCACert(context.Background(), agentClient, id)
- }
- }
-
- // Send sandbox-level env vars into the VM agent (survives snapshots)
- if len(envsToInject) > 0 {
- envCtx, envCancel := context.WithTimeout(context.Background(), 5*time.Second)
- if err := agentClient.SetEnvs(envCtx, envsToInject); err != nil {
- envCancel()
- log.Printf("firecracker: warning: SetEnvs failed for %s: %v", id, err)
- }
- envCancel()
- }
-
- // Register VM
- m.mu.Lock()
- m.vms[id] = vm
- m.mu.Unlock()
-
- // Write sandbox-meta.json for local NVMe recovery after hard kill
- sbMeta := SandboxMeta{
- SandboxID: id,
- Template: template,
- CpuCount: cpus,
- MemoryMB: memMB,
- GuestPort: guestPort,
- }
- if metaJSON, err := json.Marshal(sbMeta); err == nil {
- _ = os.WriteFile(filepath.Join(sandboxDir, "sandbox-meta.json"), metaJSON, 0644)
- }
-
- log.Printf("firecracker: created VM %s (template=%s, cpu=%d, mem=%dMB, port=%d→%d, tap=%s, mac=%s)",
- id, template, cpus, memMB, hostPort, guestPort, netCfg.TAPName, guestMAC)
-
- return &types.Sandbox{
- ID: id,
- Template: template,
- Status: types.SandboxStatusRunning,
- StartedAt: now,
- EndAt: now.Add(timeout),
- CpuCount: cpus,
- MemoryMB: memMB,
- HostPort: hostPort,
- }, nil
-}
-
-// waitForAgent polls the agent via gRPC until it responds or times out.
-func (m *Manager) waitForAgent(ctx context.Context, vsockPath string, timeout time.Duration) (*AgentClient, error) {
- t0 := time.Now()
- deadline := t0.Add(timeout)
- var lastErr error
- attempts := 0
-
- // Log initial vsock file state for diagnostics
- if _, err := os.Stat(vsockPath); err != nil {
- log.Printf("firecracker: waitForAgent: vsock.sock does not exist yet at %s", vsockPath)
- } else {
- log.Printf("firecracker: waitForAgent: vsock.sock exists at %s", vsockPath)
- }
-
- for time.Now().Before(deadline) {
- attempts++
- tAttempt := time.Now()
- client, err := NewAgentClient(vsockPath)
- if err != nil {
- lastErr = err
- if attempts <= 3 || attempts%10 == 0 {
- log.Printf("firecracker: waitForAgent: attempt %d dial failed (%dms): %v",
- attempts, time.Since(tAttempt).Milliseconds(), err)
- }
- time.Sleep(50 * time.Millisecond)
- continue
- }
-
- pingCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
- _, err = client.Ping(pingCtx)
- cancel()
- if err != nil {
- client.Close()
- lastErr = err
- if attempts <= 3 || attempts%10 == 0 {
- log.Printf("firecracker: waitForAgent: attempt %d ping failed (%dms): %v",
- attempts, time.Since(tAttempt).Milliseconds(), err)
- }
- time.Sleep(50 * time.Millisecond)
- continue
- }
-
- log.Printf("firecracker: waitForAgent: connected on attempt %d (%dms total)",
- attempts, time.Since(t0).Milliseconds())
- return client, nil
- }
-
- return nil, fmt.Errorf("agent not ready after %v (%d attempts): %v", timeout, attempts, lastErr)
-}
-
-// Get returns sandbox info by ID.
-func (m *Manager) Get(ctx context.Context, id string) (*types.Sandbox, error) {
- m.mu.RLock()
- vm, ok := m.vms[id]
- m.mu.RUnlock()
- if !ok {
- return nil, fmt.Errorf("sandbox %s not found", id)
- }
-
- return vmToSandbox(vm), nil
-}
-
-// Kill stops a VM and cleans up all resources.
-func (m *Manager) Kill(ctx context.Context, id string) error {
- m.mu.Lock()
- vm, ok := m.vms[id]
- if ok {
- delete(m.vms, id)
- }
- m.mu.Unlock()
- if !ok {
- return fmt.Errorf("sandbox %s not found", id)
- }
-
- return m.destroyVM(vm)
-}
-
-// destroyVM stops a VM and cleans up all resources.
-func (m *Manager) destroyVM(vm *VMInstance) error {
- // Try graceful shutdown via agent
- if vm.agent != nil {
- shutCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
- _ = vm.agent.Shutdown(shutCtx)
- cancel()
- vm.agent.Close()
- }
-
- // Kill Firecracker process
- if vm.cmd != nil && vm.cmd.Process != nil {
- vm.cmd.Process.Kill()
- vm.cmd.Wait()
- }
-
- // Clean up secrets proxy session
- if m.secretsProxy != nil && vm.network != nil {
- m.secretsProxy.UnregisterSession(vm.network.GuestIP)
- }
-
- // Clean up network
- if vm.network != nil {
- RemoveProxyRedirect(vm.network)
- RemoveDNAT(vm.network)
- DeleteTAP(vm.network.TAPName)
- m.subnets.Release(vm.network.TAPName)
- }
-
- // Clean up API socket
- if vm.apiSockPath != "" {
- os.Remove(vm.apiSockPath)
- }
-
- // Remove sandbox directory
- if vm.sandboxDir != "" {
- os.RemoveAll(vm.sandboxDir)
- }
-
- log.Printf("firecracker: destroyed VM %s", vm.ID)
- return nil
-}
-
-// injectCACert writes the secrets proxy CA certificate into the VM and updates
-// the trust store so HTTPS requests through the proxy are trusted.
-func (m *Manager) injectCACert(ctx context.Context, agent *AgentClient, sandboxID string) {
- if m.secretsProxy == nil {
- return
- }
- certPEM := m.secretsProxy.CACertPEM()
- if len(certPEM) == 0 {
- return
- }
-
- writeCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
- defer cancel()
-
- certPath := "/usr/local/share/ca-certificates/opensandbox-proxy.crt"
- if err := agent.WriteFile(writeCtx, certPath, certPEM); err != nil {
- log.Printf("firecracker: warning: write CA cert failed for %s: %v", sandboxID, err)
- return
- }
-
- // Update the system trust store
- updateCtx, updateCancel := context.WithTimeout(ctx, 10*time.Second)
- defer updateCancel()
- _, err := agent.Exec(updateCtx, &pb.ExecRequest{
- Command: "/bin/sh",
- Args: []string{"-c", "update-ca-certificates 2>/dev/null || true"},
- TimeoutSeconds: 10,
- })
- if err != nil {
- log.Printf("firecracker: warning: update-ca-certificates failed for %s: %v", sandboxID, err)
- }
-}
-
-// cleanupVM cleans up resources on failed creation.
-func (m *Manager) cleanupVM(netCfg *NetworkConfig, sandboxDir string) {
- if netCfg != nil {
- RemoveProxyRedirect(netCfg)
- RemoveDNAT(netCfg)
- DeleteTAP(netCfg.TAPName)
- m.subnets.Release(netCfg.TAPName)
- }
- if sandboxDir != "" {
- os.RemoveAll(sandboxDir)
- }
-}
-
-// List returns all running VMs.
-func (m *Manager) List(ctx context.Context) ([]types.Sandbox, error) {
- m.mu.RLock()
- defer m.mu.RUnlock()
-
- result := make([]types.Sandbox, 0, len(m.vms))
- for _, vm := range m.vms {
- result = append(result, *vmToSandbox(vm))
- }
- return result, nil
-}
-
-// Count returns the number of running VMs.
-func (m *Manager) Count(ctx context.Context) (int, error) {
- m.mu.RLock()
- defer m.mu.RUnlock()
- return len(m.vms), nil
-}
-
-// Close stops all VMs and cleans up.
-func (m *Manager) Close() {
- m.mu.Lock()
- vms := make([]*VMInstance, 0, len(m.vms))
- for _, vm := range m.vms {
- vms = append(vms, vm)
- }
- m.vms = make(map[string]*VMInstance)
- m.mu.Unlock()
-
- for _, vm := range vms {
- m.destroyVM(vm)
- }
- log.Printf("firecracker: manager closed, %d VMs destroyed", len(vms))
-}
-
-// WaitUploads blocks until all in-flight async S3 uploads complete,
-// or the timeout expires.
-func (m *Manager) WaitUploads(timeout time.Duration) {
- done := make(chan struct{})
- go func() {
- m.uploadWg.Wait()
- close(done)
- }()
- select {
- case <-done:
- log.Println("firecracker: all S3 uploads complete")
- case <-time.After(timeout):
- log.Printf("firecracker: timed out waiting for S3 uploads after %s", timeout)
- }
-}
-
-// HibernateAllResult holds the result of a single VM hibernation during HibernateAll.
-type HibernateAllResult struct {
- SandboxID string
- HibernationKey string
- Err error
-}
-
-// HibernateAll hibernates all running VMs concurrently.
-// The local snapshot (syncfs + pause + dump) is fast (~200ms per VM) and runs in parallel.
-// S3 uploads happen asynchronously and are tracked by uploadWg.
-func (m *Manager) HibernateAll(ctx context.Context, checkpointStore *storage.CheckpointStore) []HibernateAllResult {
- m.mu.RLock()
- ids := make([]string, 0, len(m.vms))
- for id := range m.vms {
- ids = append(ids, id)
- }
- m.mu.RUnlock()
-
- if len(ids) == 0 {
- return nil
- }
-
- var results []HibernateAllResult
- var resultsMu sync.Mutex
- var wg sync.WaitGroup
-
- for _, id := range ids {
- wg.Add(1)
- go func(sandboxID string) {
- defer wg.Done()
- result, err := m.Hibernate(ctx, sandboxID, checkpointStore)
-
- resultsMu.Lock()
- defer resultsMu.Unlock()
- if err != nil {
- log.Printf("firecracker: HibernateAll: %s failed: %v", sandboxID, err)
- results = append(results, HibernateAllResult{SandboxID: sandboxID, Err: err})
- } else {
- results = append(results, HibernateAllResult{SandboxID: sandboxID, HibernationKey: result.HibernationKey})
- }
- }(id)
- }
-
- wg.Wait()
- return results
-}
-
-// 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.getReadyVM(ctx, sandboxID)
- if err != nil {
- return nil, err
- }
-
- timeout := int32(cfg.Timeout)
- if timeout <= 0 {
- timeout = 60
- }
-
- // If no explicit args, wrap in shell for pipe/redirect/&&/|| support
- command := cfg.Command
- args := cfg.Args
- if len(args) == 0 {
- args = []string{"-c", command}
- command = "/bin/sh"
- }
-
- resp, err := vm.agent.Exec(ctx, &pb.ExecRequest{
- Command: command,
- Args: args,
- Envs: cfg.Env,
- Cwd: cfg.Cwd,
- TimeoutSeconds: timeout,
- })
- if err != nil {
- return nil, fmt.Errorf("exec in %s: %w", sandboxID, err)
- }
-
- return &types.ProcessResult{
- ExitCode: int(resp.ExitCode),
- Stdout: resp.Stdout,
- Stderr: resp.Stderr,
- }, nil
-}
-
-// ReadFile reads a file from the VM.
-func (m *Manager) ReadFile(ctx context.Context, sandboxID, path string) (string, error) {
- vm, err := m.getReadyVM(ctx, sandboxID)
- if err != nil {
- return "", err
- }
- data, err := vm.agent.ReadFile(ctx, path)
- if err != nil {
- return "", err
- }
- return string(data), nil
-}
-
-// WriteFile writes a file in the VM.
-func (m *Manager) WriteFile(ctx context.Context, sandboxID, path, content string) error {
- vm, err := m.getReadyVM(ctx, sandboxID)
- if err != nil {
- return err
- }
- return vm.agent.WriteFile(ctx, path, []byte(content))
-}
-
-// ListDir lists a directory in the VM.
-func (m *Manager) ListDir(ctx context.Context, sandboxID, path string) ([]types.EntryInfo, error) {
- vm, err := m.getReadyVM(ctx, sandboxID)
- if err != nil {
- return nil, err
- }
- entries, err := vm.agent.ListDir(ctx, path)
- if err != nil {
- return nil, err
- }
- result := make([]types.EntryInfo, len(entries))
- for i, e := range entries {
- result[i] = types.EntryInfo{
- Name: e.Name,
- IsDir: e.IsDir,
- Size: e.Size,
- Path: e.Path,
- }
- }
- return result, nil
-}
-
-// MakeDir creates a directory in the VM.
-func (m *Manager) MakeDir(ctx context.Context, sandboxID, path string) error {
- vm, err := m.getReadyVM(ctx, sandboxID)
- if err != nil {
- return err
- }
- return vm.agent.MakeDir(ctx, path)
-}
-
-// Remove removes a file/directory in the VM.
-func (m *Manager) Remove(ctx context.Context, sandboxID, path string) error {
- vm, err := m.getReadyVM(ctx, sandboxID)
- if err != nil {
- return err
- }
- return vm.agent.Remove(ctx, path)
-}
-
-// Exists checks if a path exists in the VM.
-func (m *Manager) Exists(ctx context.Context, sandboxID, path string) (bool, error) {
- vm, err := m.getReadyVM(ctx, sandboxID)
- if err != nil {
- return false, err
- }
- return vm.agent.Exists(ctx, path)
-}
-
-// Stat returns file metadata from the VM.
-func (m *Manager) Stat(ctx context.Context, sandboxID, path string) (*types.FileInfo, error) {
- vm, err := m.getReadyVM(ctx, sandboxID)
- if err != nil {
- return nil, err
- }
- resp, err := vm.agent.Stat(ctx, path)
- if err != nil {
- return nil, err
- }
- return &types.FileInfo{
- Name: resp.Name,
- IsDir: resp.IsDir,
- Size: resp.Size,
- Mode: resp.Mode,
- ModTime: resp.ModTime,
- Path: resp.Path,
- }, nil
-}
-
-// SetResourceLimits adjusts sandbox cgroup limits at runtime.
-// Not yet implemented for the Firecracker backend.
-func (m *Manager) SetResourceLimits(ctx context.Context, sandboxID string, maxPids int32, maxMemoryBytes, cpuMaxUsec, cpuPeriodUsec int64) error {
- return fmt.Errorf("SetResourceLimits not implemented for Firecracker backend")
-}
-
-// Stats returns live resource usage from the VM.
-func (m *Manager) Stats(ctx context.Context, sandboxID string) (*sandbox.SandboxStats, error) {
- vm, err := m.getReadyVM(ctx, sandboxID)
- if err != nil {
- return nil, err
- }
- resp, err := vm.agent.Stats(ctx)
- if err != nil {
- return nil, err
- }
- return &sandbox.SandboxStats{
- CPUPercent: resp.CpuPercent,
- MemUsage: resp.MemUsage,
- MemLimit: resp.MemLimit,
- NetInput: resp.NetInput,
- NetOutput: resp.NetOutput,
- PIDs: int(resp.Pids),
- }, nil
-}
-
-// HostPort returns the mapped host port for a sandbox.
-func (m *Manager) HostPort(ctx context.Context, sandboxID string) (int, error) {
- vm, err := m.getVM(sandboxID)
- if err != nil {
- return 0, err
- }
- return vm.HostPort, nil
-}
-
-// ContainerAddr returns the VM's guest IP and the requested port as "ip:port".
-// Used by the proxy to route preview URL traffic to a specific port inside the VM.
-func (m *Manager) ContainerAddr(ctx context.Context, sandboxID string, port int) (string, error) {
- vm, err := m.getVM(sandboxID)
- if err != nil {
- return "", err
- }
- if vm.network == nil {
- return "", fmt.Errorf("sandbox %s has no network config", sandboxID)
- }
- return fmt.Sprintf("%s:%d", vm.network.GuestIP, port), nil
-}
-
-// DataDir returns the base data directory.
-func (m *Manager) DataDir() string {
- return m.cfg.DataDir
-}
-
-// ContainerName returns a human-readable name for the sandbox (for logging).
-func (m *Manager) ContainerName(id string) string {
- return "fc-" + id
-}
-
-// Hibernate snapshots a VM and uploads to S3.
-// On success the Firecracker process is killed, network is torn down, and the
-// VM is removed from the in-memory tracking map so it no longer counts toward
-// worker capacity. The sandbox can later be restored via Wake().
-func (m *Manager) Hibernate(ctx context.Context, sandboxID string, checkpointStore *storage.CheckpointStore) (*sandbox.HibernateResult, error) {
- vm, err := m.getVM(sandboxID)
- if err != nil {
- return nil, err
- }
- result, err := m.doHibernate(ctx, vm, checkpointStore)
- if err != nil {
- return nil, err
- }
-
- // Remove the VM from tracking — the Firecracker process is dead and
- // resources (TAP, memory, CPU) are released. This frees the capacity
- // slot so the worker can accept new sandboxes.
- m.mu.Lock()
- delete(m.vms, sandboxID)
- m.mu.Unlock()
-
- return result, nil
-}
-
-// Wake restores a VM from a snapshot.
-func (m *Manager) Wake(ctx context.Context, sandboxID string, checkpointKey string, checkpointStore *storage.CheckpointStore, timeout int) (*types.Sandbox, error) {
- return m.doWake(ctx, sandboxID, checkpointKey, checkpointStore, timeout)
-}
-
-// getVM retrieves a VM by ID (read-locked).
-func (m *Manager) getVM(id string) (*VMInstance, error) {
- m.mu.RLock()
- vm, ok := m.vms[id]
- m.mu.RUnlock()
- if !ok {
- return nil, fmt.Errorf("sandbox %s not found", id)
- }
- 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{
- ID: vm.ID,
- Template: vm.Template,
- Status: vm.Status,
- StartedAt: vm.StartedAt,
- EndAt: vm.EndAt,
- CpuCount: vm.CpuCount,
- MemoryMB: vm.MemoryMB,
- HostPort: vm.HostPort,
- }
-}
-
-// generateMAC creates a deterministic MAC address from a sandbox ID.
-// Format: AA:FC:00:00:XX:XX where XX:XX are derived from the ID.
-func generateMAC(id string) string {
- var b4, b5 byte
- if len(id) > 3 {
- b4 = id[3]
- }
- if len(id) > 0 {
- b5 = id[len(id)-1]
- }
- return fmt.Sprintf("AA:FC:00:00:%02x:%02x", b4, b5)
-}
-
-// GetVsockPath returns the vsock UDS path for a sandbox (used by PTY manager).
-func (m *Manager) GetVsockPath(sandboxID string) (string, error) {
- vm, err := m.getVM(sandboxID)
- if err != nil {
- return "", err
- }
- return vm.vsockPath, nil
-}
-
-// GetAgent returns the agent client for a sandbox (used by PTY manager).
-func (m *Manager) GetAgent(sandboxID string) (*AgentClient, error) {
- vm, err := m.getVM(sandboxID)
- if err != nil {
- return nil, err
- }
- return vm.agent, nil
-}
-
-// GetWorkspacePath returns the host path to a sandbox's workspace.ext4 drive.
-func (m *Manager) GetWorkspacePath(sandboxID string) (string, error) {
- vm, err := m.getVM(sandboxID)
- if err != nil {
- return "", err
- }
- return filepath.Join(vm.sandboxDir, "workspace.ext4"), nil
-}
-
-// SyncFS flushes filesystem buffers inside the VM via the agent.
-func (m *Manager) SyncFS(ctx context.Context, sandboxID string) error {
- vm, err := m.getVM(sandboxID)
- if err != nil {
- return err
- }
- if vm.agent == nil {
- return fmt.Errorf("no agent connection for %s", sandboxID)
- }
- return vm.agent.SyncFS(ctx)
-}
-
-// CleanupOrphanedProcesses kills any Firecracker processes and TAP devices
-// left over from a previous worker run. Must be called before RecoverLocalSandboxes
-// so TAP devices are free for re-allocation.
-func (m *Manager) CleanupOrphanedProcesses() {
- // Kill all firecracker processes not tracked by this manager
- out, err := exec.Command("pgrep", "-f", "firecracker").Output()
- if err == nil && len(out) > 0 {
- count := 0
- for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {
- if line == "" {
- continue
- }
- _ = exec.Command("kill", "-9", line).Run()
- count++
- }
- if count > 0 {
- log.Printf("firecracker: killed %d orphaned firecracker process(es)", count)
- }
- }
-
- // Clean up orphaned TAP devices (fc-tap0, fc-tap1, ...)
- out, err = exec.Command("ip", "-o", "link", "show").Output()
- if err == nil {
- for _, line := range strings.Split(string(out), "\n") {
- fields := strings.Fields(line)
- if len(fields) < 2 {
- continue
- }
- // format: "3: fc-tap0: <flags> ..."
- tapName := strings.TrimSuffix(fields[1], ":")
- if strings.HasPrefix(tapName, "fc-") {
- _ = exec.Command("ip", "link", "del", tapName).Run()
- log.Printf("firecracker: cleaned up orphaned TAP %s", tapName)
- }
- }
- }
-}
-
-// LocalRecovery describes a sandbox found on disk that can be recovered.
-type LocalRecovery struct {
- SandboxID string
- HasSnapshot bool // true = full snapshot (mem+vmstate), false = workspace only
- Meta SandboxMeta // from sandbox-meta.json or snapshot-meta.json
-}
-
-// RecoverLocalSandboxes scans the sandboxes directory for sandbox data left
-// on NVMe from a previous run. Returns recoverable sandboxes.
-func (m *Manager) RecoverLocalSandboxes() []LocalRecovery {
- sandboxesDir := filepath.Join(m.cfg.DataDir, "sandboxes")
- entries, err := os.ReadDir(sandboxesDir)
- if err != nil {
- log.Printf("firecracker: no sandboxes dir to scan: %v", err)
- return nil
- }
-
- var recoveries []LocalRecovery
- for _, entry := range entries {
- if !entry.IsDir() || !strings.HasPrefix(entry.Name(), "sb-") {
- continue
- }
- sandboxID := entry.Name()
- sandboxDir := filepath.Join(sandboxesDir, sandboxID)
-
- // Check for full snapshot (graceful shutdown completed)
- snapshotMetaPath := filepath.Join(sandboxDir, "snapshot", "snapshot-meta.json")
- if fileExists(filepath.Join(sandboxDir, "snapshot", "mem")) &&
- fileExists(filepath.Join(sandboxDir, "snapshot", "vmstate")) &&
- fileExists(snapshotMetaPath) {
- var snapMeta SnapshotMeta
- if data, err := os.ReadFile(snapshotMetaPath); err == nil {
- if json.Unmarshal(data, &snapMeta) == nil {
- recoveries = append(recoveries, LocalRecovery{
- SandboxID: sandboxID,
- HasSnapshot: true,
- Meta: SandboxMeta{
- SandboxID: sandboxID,
- Template: snapMeta.Template,
- CpuCount: snapMeta.CpuCount,
- MemoryMB: snapMeta.MemoryMB,
- GuestPort: snapMeta.GuestPort,
- },
- })
- continue
- }
- }
- }
-
- // Check for workspace-only (hard kill, no snapshot)
- if fileExists(filepath.Join(sandboxDir, "workspace.ext4")) {
- sbMetaPath := filepath.Join(sandboxDir, "sandbox-meta.json")
- var meta SandboxMeta
- if data, err := os.ReadFile(sbMetaPath); err == nil {
- if json.Unmarshal(data, &meta) == nil {
- recoveries = append(recoveries, LocalRecovery{
- SandboxID: sandboxID,
- HasSnapshot: false,
- Meta: meta,
- })
- continue
- }
- }
- // No readable meta — skip (can't determine template)
- log.Printf("firecracker: skipping %s: workspace exists but no sandbox-meta.json", sandboxID)
- }
- }
- return recoveries
-}
diff --git a/internal/firecracker/network.go b/internal/firecracker/network.go
deleted file mode 100644
index 78d277f8..00000000
--- a/internal/firecracker/network.go
+++ /dev/null
@@ -1,314 +0,0 @@
-package firecracker
-
-import (
- "fmt"
- "net"
- "os/exec"
- "strings"
- "sync"
-)
-
-// NetworkConfig holds the networking state for a single VM.
-type NetworkConfig struct {
- TAPName string // e.g., "tap0"
- HostIP string // e.g., "172.16.0.1"
- GuestIP string // e.g., "172.16.0.2"
- Mask string // e.g., "255.255.255.252"
- CIDR int // /30
-
- // Port forwarding
- HostPort int // host port mapped to guest
- GuestPort int // guest port (typically 80)
- DNATRuleAdded bool
-
- // Secrets proxy redirect
- ProxyRedirectAdded bool
-}
-
-// SubnetAllocator manages /30 subnet allocation from a 172.16.0.0/16 pool.
-// Each VM gets a /30: host IP (.1) and guest IP (.2), with .0 as network and .3 as broadcast.
-type SubnetAllocator struct {
- mu sync.Mutex
- next uint32 // next /30 block index (0, 1, 2, ...)
- used map[uint32]bool
-}
-
-// NewSubnetAllocator creates a new subnet allocator.
-func NewSubnetAllocator() *SubnetAllocator {
- return &SubnetAllocator{
- used: make(map[uint32]bool),
- }
-}
-
-// Allocate returns a new /30 subnet for a VM.
-// Returns tapName, hostIP, guestIP, mask.
-func (a *SubnetAllocator) Allocate() (*NetworkConfig, error) {
- a.mu.Lock()
- defer a.mu.Unlock()
-
- // Find next free /30 block
- block := a.next
- for a.used[block] {
- block++
- if block > 16383 { // 172.16.0.0/16 has 16384 /30 blocks
- return nil, fmt.Errorf("subnet pool exhausted")
- }
- }
- a.used[block] = true
- a.next = block + 1
-
- // Calculate IPs: 172.16.{high}.{low*4}
- // Each /30 block is 4 IPs: base+0 (network), base+1 (host), base+2 (guest), base+3 (broadcast)
- base := block * 4
- b2 := byte(base >> 8) // second octet offset
- b3 := byte(base & 0xFF) // third octet base
-
- // base+0 is network address, base+1 is host, base+2 is guest, base+3 is broadcast
- 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%07d", block)
-
- return &NetworkConfig{
- TAPName: tapName,
- HostIP: hostIP,
- GuestIP: guestIP,
- Mask: "255.255.255.252",
- CIDR: 30,
- }, nil
-}
-
-// AllocateSpecific reserves a specific TAP name/subnet block.
-// Used during snapshot restore where the TAP name is baked into the vmstate.
-func (a *SubnetAllocator) AllocateSpecific(tapName string) (*NetworkConfig, error) {
- a.mu.Lock()
- defer a.mu.Unlock()
-
- var block uint32
- if _, err := fmt.Sscanf(tapName, "fc-tap%d", &block); err != nil {
- return nil, fmt.Errorf("parse tap name %q: %w", tapName, err)
- }
- if a.used[block] {
- return nil, fmt.Errorf("tap %s already in use", tapName)
- }
- a.used[block] = true
-
- // Calculate IPs using same math as Allocate()
- base := block * 4
- b2 := byte(base >> 8)
- b3 := byte(base & 0xFF)
-
- return &NetworkConfig{
- TAPName: tapName,
- HostIP: fmt.Sprintf("172.16.%d.%d", b2, b3+1),
- GuestIP: fmt.Sprintf("172.16.%d.%d", b2, b3+2),
- Mask: "255.255.255.252",
- CIDR: 30,
- }, nil
-}
-
-// Release returns a /30 block to the pool.
-func (a *SubnetAllocator) Release(tapName string) {
- a.mu.Lock()
- defer a.mu.Unlock()
-
- // Extract block number from tap name
- var block uint32
- if _, err := fmt.Sscanf(tapName, "fc-tap%d", &block); err != nil {
- return
- }
- delete(a.used, block)
-}
-
-// CreateTAP creates a TAP device and configures it with the host IP.
-func CreateTAP(cfg *NetworkConfig) error {
- // Create TAP device
- if err := run("ip", "tuntap", "add", "dev", cfg.TAPName, "mode", "tap"); err != nil {
- return fmt.Errorf("create tap %s: %w", cfg.TAPName, err)
- }
-
- // Assign host IP
- addr := fmt.Sprintf("%s/%d", cfg.HostIP, cfg.CIDR)
- if err := run("ip", "addr", "add", addr, "dev", cfg.TAPName); err != nil {
- DeleteTAP(cfg.TAPName)
- return fmt.Errorf("assign ip to %s: %w", cfg.TAPName, err)
- }
-
- // Bring up
- if err := run("ip", "link", "set", cfg.TAPName, "up"); err != nil {
- DeleteTAP(cfg.TAPName)
- return fmt.Errorf("bring up %s: %w", cfg.TAPName, err)
- }
-
- return nil
-}
-
-// DeleteTAP removes a TAP device.
-func DeleteTAP(tapName string) {
- _ = run("ip", "link", "del", tapName)
-}
-
-// AddDNAT adds an iptables DNAT rule: hostPort → guestIP:guestPort.
-func AddDNAT(cfg *NetworkConfig) error {
- if cfg.HostPort == 0 || cfg.GuestPort == 0 {
- return nil
- }
- err := run("iptables", "-t", "nat", "-A", "PREROUTING",
- "-p", "tcp", "--dport", fmt.Sprintf("%d", cfg.HostPort),
- "-j", "DNAT", "--to-destination",
- fmt.Sprintf("%s:%d", cfg.GuestIP, cfg.GuestPort))
- if err != nil {
- return fmt.Errorf("add DNAT: %w", err)
- }
-
- // Also add for locally-generated traffic (connections from the host itself)
- err = run("iptables", "-t", "nat", "-A", "OUTPUT",
- "-p", "tcp", "--dport", fmt.Sprintf("%d", cfg.HostPort),
- "-j", "DNAT", "--to-destination",
- fmt.Sprintf("%s:%d", cfg.GuestIP, cfg.GuestPort))
- if err != nil {
- // Non-fatal — PREROUTING is the important one
- return nil
- }
-
- cfg.DNATRuleAdded = true
- return nil
-}
-
-// RemoveDNAT removes the iptables DNAT rules.
-func RemoveDNAT(cfg *NetworkConfig) {
- if !cfg.DNATRuleAdded {
- return
- }
- _ = run("iptables", "-t", "nat", "-D", "PREROUTING",
- "-p", "tcp", "--dport", fmt.Sprintf("%d", cfg.HostPort),
- "-j", "DNAT", "--to-destination",
- fmt.Sprintf("%s:%d", cfg.GuestIP, cfg.GuestPort))
- _ = run("iptables", "-t", "nat", "-D", "OUTPUT",
- "-p", "tcp", "--dport", fmt.Sprintf("%d", cfg.HostPort),
- "-j", "DNAT", "--to-destination",
- fmt.Sprintf("%s:%d", cfg.GuestIP, cfg.GuestPort))
-}
-
-// AddProxyRedirect adds an iptables rule to redirect HTTPS traffic from the VM
-// through the secrets proxy on the host. Traffic from guestIP:443 is redirected
-// to hostIP:3128 where the MITM proxy substitutes sealed tokens.
-func AddProxyRedirect(cfg *NetworkConfig) error {
- err := run("iptables", "-t", "nat", "-A", "PREROUTING",
- "-s", cfg.GuestIP,
- "-p", "tcp", "--dport", "443",
- "-j", "DNAT", "--to-destination",
- fmt.Sprintf("%s:3128", cfg.HostIP))
- if err != nil {
- return fmt.Errorf("add proxy redirect: %w", err)
- }
- cfg.ProxyRedirectAdded = true
- return nil
-}
-
-// RemoveProxyRedirect removes the iptables proxy redirect rule.
-func RemoveProxyRedirect(cfg *NetworkConfig) {
- if !cfg.ProxyRedirectAdded {
- return
- }
- _ = run("iptables", "-t", "nat", "-D", "PREROUTING",
- "-s", cfg.GuestIP,
- "-p", "tcp", "--dport", "443",
- "-j", "DNAT", "--to-destination",
- fmt.Sprintf("%s:3128", cfg.HostIP))
-}
-
-// EnableForwarding enables IPv4 forwarding and masquerading for the VM subnet.
-// Call once at startup.
-func EnableForwarding() error {
- // Enable IP forwarding
- if err := run("sysctl", "-w", "net.ipv4.ip_forward=1"); err != nil {
- return fmt.Errorf("enable ip_forward: %w", err)
- }
-
- // Allow routing packets with 127.0.0.0/8 source through non-loopback interfaces.
- // Required for DNAT from localhost:PORT → guest VM IP to work.
- if err := run("sysctl", "-w", "net.ipv4.conf.all.route_localnet=1"); err != nil {
- return fmt.Errorf("enable route_localnet: %w", err)
- }
-
- // Add masquerade rule for VM subnet (idempotent — check if exists first)
- out, _ := exec.Command("iptables", "-t", "nat", "-S", "POSTROUTING").CombinedOutput()
- outRules := string(out)
- if !strings.Contains(outRules, "172.16.0.0/16") {
- // Detect the default outgoing interface
- outIface := detectDefaultInterface()
- if outIface != "" {
- _ = run("iptables", "-t", "nat", "-A", "POSTROUTING",
- "-s", "172.16.0.0/16", "-o", outIface,
- "-j", "MASQUERADE")
- } else {
- // Fallback: masquerade on all interfaces except TAPs
- _ = run("iptables", "-t", "nat", "-A", "POSTROUTING",
- "-s", "172.16.0.0/16", "!", "-o", "fc-tap+",
- "-j", "MASQUERADE")
- }
- }
-
- // Masquerade for DNAT'd traffic from the host to VMs (e.g. localhost:PORT → guest:80).
- // Without this, packets arrive at the guest with src=127.0.0.1, and replies go nowhere.
- // This rewrites src to the host's TAP IP so the guest replies back through the TAP.
- if !strings.Contains(outRules, "172.16.0.0/16 -j MASQUERADE") {
- _ = run("iptables", "-t", "nat", "-A", "POSTROUTING",
- "-d", "172.16.0.0/16",
- "-j", "MASQUERADE")
- }
-
- // Allow FORWARD for VM traffic — many distros (and Docker) default FORWARD to DROP.
- // Without these rules, packets from VMs are silently dropped even with masquerade.
- fwdOut, _ := exec.Command("iptables", "-S", "FORWARD").CombinedOutput()
- fwdRules := string(fwdOut)
- if !strings.Contains(fwdRules, "172.16.0.0/16 -j ACCEPT") {
- _ = run("iptables", "-I", "FORWARD",
- "-s", "172.16.0.0/16",
- "-j", "ACCEPT")
- _ = run("iptables", "-I", "FORWARD",
- "-d", "172.16.0.0/16",
- "-m", "conntrack", "--ctstate", "RELATED,ESTABLISHED",
- "-j", "ACCEPT")
- }
-
- return nil
-}
-
-// detectDefaultInterface returns the name of the default outgoing network interface.
-func detectDefaultInterface() string {
- out, err := exec.Command("ip", "route", "show", "default").CombinedOutput()
- if err != nil {
- return ""
- }
- // Parse "default via X.X.X.X dev <iface> ..."
- fields := strings.Fields(string(out))
- for i, f := range fields {
- if f == "dev" && i+1 < len(fields) {
- return fields[i+1]
- }
- }
- return ""
-}
-
-// FindFreePort finds a free TCP port on the host.
-func FindFreePort() (int, error) {
- lis, err := net.Listen("tcp", "127.0.0.1:0")
- if err != nil {
- return 0, err
- }
- port := lis.Addr().(*net.TCPAddr).Port
- lis.Close()
- return port, nil
-}
-
-// run executes a command and returns an error with stderr if it fails.
-func run(name string, args ...string) error {
- cmd := exec.Command(name, args...)
- out, err := cmd.CombinedOutput()
- if err != nil {
- return fmt.Errorf("%s %s: %w (%s)", name, strings.Join(args, " "), err, strings.TrimSpace(string(out)))
- }
- return nil
-}
diff --git a/internal/firecracker/rootfs.go b/internal/firecracker/rootfs.go
deleted file mode 100644
index 89f3f9ac..00000000
--- a/internal/firecracker/rootfs.go
+++ /dev/null
@@ -1,87 +0,0 @@
-package firecracker
-
-import (
- "fmt"
- "os"
- "os/exec"
- "path/filepath"
- "strings"
-)
-
-// RootfsConfig holds paths for VM filesystem images.
-type RootfsConfig struct {
- ImagesDir string // directory containing base rootfs images (e.g., /data/firecracker/images/)
-}
-
-// PrepareRootfs copies a base rootfs image to the sandbox directory.
-// Uses reflink (--reflink=auto) on XFS/btrfs for instant copy-on-write.
-func PrepareRootfs(baseImage, destPath string) error {
- // Ensure parent directory exists
- if err := os.MkdirAll(filepath.Dir(destPath), 0755); err != nil {
- return fmt.Errorf("mkdir for rootfs: %w", err)
- }
-
- // Try reflink copy first (instant on XFS with reflink support)
- cmd := exec.Command("cp", "--reflink=auto", baseImage, destPath)
- if out, err := cmd.CombinedOutput(); err != nil {
- return fmt.Errorf("copy rootfs: %w (%s)", err, strings.TrimSpace(string(out)))
- }
-
- return nil
-}
-
-// CreateWorkspace creates a sparse ext4 filesystem for the sandbox workspace.
-// The file is sparse — it only uses disk space as data is written.
-func CreateWorkspace(path string, sizeMB int) error {
- if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
- return fmt.Errorf("mkdir for workspace: %w", err)
- }
-
- // Create sparse file
- f, err := os.Create(path)
- if err != nil {
- return fmt.Errorf("create workspace file: %w", err)
- }
- // Truncate to desired size (sparse — no disk used yet)
- if err := f.Truncate(int64(sizeMB) * 1024 * 1024); err != nil {
- f.Close()
- os.Remove(path)
- return fmt.Errorf("truncate workspace: %w", err)
- }
- f.Close()
-
- // Format as ext4
- cmd := exec.Command("mkfs.ext4", "-q", "-F",
- "-L", "workspace",
- "-O", "^has_journal", // no journal for performance (we have S3 as source of truth)
- path)
- if out, err := cmd.CombinedOutput(); err != nil {
- os.Remove(path)
- return fmt.Errorf("mkfs.ext4: %w (%s)", err, strings.TrimSpace(string(out)))
- }
-
- return nil
-}
-
-// ResolveBaseImage finds the base rootfs image for a given template.
-// Templates map to image files: "ubuntu" → "ubuntu-base.ext4"
-func ResolveBaseImage(imagesDir, template string) (string, error) {
- if template == "" {
- template = "ubuntu"
- }
-
- // Check for exact match first
- candidates := []string{
- filepath.Join(imagesDir, template+".ext4"),
- filepath.Join(imagesDir, template+"-base.ext4"),
- filepath.Join(imagesDir, template),
- }
-
- for _, path := range candidates {
- if _, err := os.Stat(path); err == nil {
- return path, nil
- }
- }
-
- return "", fmt.Errorf("base image not found for template %q in %s", template, imagesDir)
-}
diff --git a/internal/firecracker/snapshot.go b/internal/firecracker/snapshot.go
deleted file mode 100644
index f9bd074b..00000000
--- a/internal/firecracker/snapshot.go
+++ /dev/null
@@ -1,2455 +0,0 @@
-package firecracker
-
-import (
- "bytes"
- "context"
- "encoding/binary"
- "encoding/json"
- "fmt"
- "io"
- "log"
- "os"
- "os/exec"
- "path/filepath"
- "strings"
- "syscall"
- "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.
-// This is needed to restore the exact same VM configuration on wake.
-type SnapshotMeta struct {
- SandboxID string `json:"sandboxId"`
- Network *NetworkConfig `json:"network"`
- GuestCID uint32 `json:"guestCID"`
- GuestMAC string `json:"guestMAC"`
- BootArgs string `json:"bootArgs"`
- RootfsPath string `json:"rootfsPath"`
- WorkspacePath string `json:"workspacePath"`
- VsockPath string `json:"vsockPath"`
- CpuCount int `json:"cpuCount"`
- MemoryMB int `json:"memoryMB"`
- Template string `json:"template"`
- GuestPort int `json:"guestPort"`
- SnapshotedAt time.Time `json:"snapshotedAt,omitempty"`
- // SealedTokens maps sealed token → real value for re-registering the proxy session on wake.
- SealedTokens map[string]string `json:"sealedTokens,omitempty"`
- // ProxyAllowlist and ProxyTokenHosts are persisted so the proxy session
- // can be fully restored with the same restrictions after hibernate → wake.
- ProxyAllowlist []string `json:"proxyAllowlist,omitempty"`
- ProxyTokenHosts map[string][]string `json:"proxyTokenHosts,omitempty"`
-}
-
-// doHibernate pauses a running VM, creates a full memory snapshot, and kicks off
-// an async S3 upload. Drives (rootfs + workspace) stay on local disk for fast
-// same-machine wake. Only mem + vmstate + metadata are archived and uploaded.
-//
-// The API returns as soon as the local snapshot is written — the S3 upload
-// happens in the background so hibernate latency is sub-second for the caller.
-//
-// Flow:
-// 1. SyncFS via agent (flush disk buffers — agent stays alive)
-// 2. Close gRPC connection (vsock must be inactive for snapshot)
-// 3. Pause VM via Firecracker API socket
-// 4. Create snapshot (mem_file + vmstate_file)
-// 5. Kill the paused Firecracker process
-// 6. Write snapshot-meta.json
-// 7. Clean up network
-// 8. (async) Archive snapshot files → tar.zst, upload to S3
-func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointStore *storage.CheckpointStore) (*sandbox.HibernateResult, error) {
- t0 := time.Now()
-
- snapshotDir := filepath.Join(vm.sandboxDir, "snapshot")
- if err := os.MkdirAll(snapshotDir, 0755); err != nil {
- return nil, fmt.Errorf("mkdir snapshot dir: %w", err)
- }
-
- memFile := filepath.Join(snapshotDir, "mem")
- vmstateFile := filepath.Join(snapshotDir, "vmstate")
-
- // Step 1: Sync filesystems inside the VM (agent stays alive for snapshot).
- // Use exec-based sync because syscall.Sync() from PID 1 doesn't reliably flush
- // dirty pages to virtio-blk after snapshot restore.
- if vm.agent != nil {
- syncCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
- _, syncErr := vm.agent.Exec(syncCtx, &pb.ExecRequest{
- Command: "sync",
- })
- cancel()
- if syncErr != nil {
- log.Printf("firecracker: hibernate %s: exec sync failed: %v", vm.ID, syncErr)
- }
- }
- log.Printf("firecracker: hibernate %s: guest sync done (%dms)", vm.ID, time.Since(t0).Milliseconds())
-
- // Step 2: Close gRPC connection — vsock must be inactive before snapshot.
- // Allow time for the vsock virtqueues to drain after closing the connection.
- // Without this delay, FIN-ACK packets from the guest may still be in the
- // vsock TX virtqueue when the VM is paused, leaving vhost-vsock in a broken
- // state after snapshot restore (connections hang indefinitely).
- if vm.agent != nil {
- vm.agent.Close()
- vm.agent = nil
- time.Sleep(500 * time.Millisecond)
- }
-
- // Step 3: Pause the VM
- if vm.fcClient == nil {
- return nil, fmt.Errorf("no API client for VM %s (not in API mode)", vm.ID)
- }
- if err := vm.fcClient.PauseVM(); err != nil {
- return nil, fmt.Errorf("pause VM: %w", err)
- }
- log.Printf("firecracker: hibernate %s: paused (%dms)", vm.ID, time.Since(t0).Milliseconds())
-
- // Step 4: Create memory snapshot
- if err := vm.fcClient.CreateSnapshot(vmstateFile, memFile); err != nil {
- return nil, fmt.Errorf("create snapshot: %w", err)
- }
- log.Printf("firecracker: hibernate %s: snapshot created (%dms)", vm.ID, time.Since(t0).Milliseconds())
-
- // Step 5: Kill the paused Firecracker process
- if vm.cmd != nil && vm.cmd.Process != nil {
- vm.cmd.Process.Kill()
- vm.cmd.Wait()
- }
-
- // Step 6: Write snapshot metadata
- 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,
- SnapshotedAt: time.Now(),
- }
- // Persist sealed token map + proxy config so wake can fully restore the proxy session
- if m.secretsProxy != nil && vm.network != nil {
- meta.SealedTokens = m.secretsProxy.GetSessionTokens(vm.network.GuestIP)
- meta.ProxyAllowlist = m.secretsProxy.GetSessionAllowlist(vm.network.GuestIP)
- meta.ProxyTokenHosts = m.secretsProxy.GetSessionTokenHosts(vm.network.GuestIP)
- }
- metaJSON, err := json.Marshal(meta)
- if err != nil {
- return nil, fmt.Errorf("marshal snapshot meta: %w", err)
- }
- metaPath := filepath.Join(snapshotDir, "snapshot-meta.json")
- if err := os.WriteFile(metaPath, metaJSON, 0644); err != nil {
- return nil, fmt.Errorf("write snapshot meta: %w", err)
- }
-
- // Step 7: Clean up network and proxy session (keep snapshot files on disk for local wake)
- if m.secretsProxy != nil && vm.network != nil {
- m.secretsProxy.UnregisterSession(vm.network.GuestIP)
- }
- if vm.network != nil {
- RemoveProxyRedirect(vm.network)
- RemoveDNAT(vm.network)
- DeleteTAP(vm.network.TAPName)
- m.subnets.Release(vm.network.TAPName)
- }
-
- // Clean up sockets — the vsock UDS must be removed so snapshot restore
- // can re-bind to the same path without "Address in use" errors.
- if vm.apiSockPath != "" {
- os.Remove(vm.apiSockPath)
- }
- if vm.vsockPath != "" {
- os.Remove(vm.vsockPath)
- }
-
- checkpointKey := fmt.Sprintf("checkpoints/%s/%d.tar.zst", vm.ID, time.Now().Unix())
- localElapsed := time.Since(t0)
- log.Printf("firecracker: hibernate %s: local snapshot complete (%dms), starting async S3 upload",
- vm.ID, localElapsed.Milliseconds())
-
- // Step 8: Archive + upload to S3 in the background.
- // The archive includes mem + vmstate + metadata + workspace drive so that
- // the sandbox can be restored on ANY worker (cross-worker migration).
- // The rootfs is NOT archived — it's recreated from the template on wake.
- sandboxDir := vm.sandboxDir
- sandboxID := vm.ID
- m.uploadWg.Add(1)
- go func() {
- defer m.uploadWg.Done()
- t1 := time.Now()
- archivePath := filepath.Join(sandboxDir, "checkpoint.tar.zst")
-
- // Archive snapshot files + workspace drive.
- // Use sandboxDir as base so workspace.ext4 is at the right relative path.
- if err := createArchive(archivePath, sandboxDir, []string{
- "snapshot/mem",
- "snapshot/vmstate",
- "snapshot/snapshot-meta.json",
- "workspace.ext4",
- }); err != nil {
- log.Printf("firecracker: async archive failed for %s: %v", sandboxID, err)
- return
- }
- archiveInfo, err := os.Stat(archivePath)
- if err != nil {
- log.Printf("firecracker: async archive stat failed for %s: %v", sandboxID, err)
- return
- }
- log.Printf("firecracker: hibernate %s: archive created (%dms, %.1f MB)",
- sandboxID, time.Since(t1).Milliseconds(), float64(archiveInfo.Size())/(1024*1024))
-
- t2 := time.Now()
- uploadCtx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
- defer cancel()
- if _, err := checkpointStore.Upload(uploadCtx, checkpointKey, archivePath); err != nil {
- log.Printf("firecracker: async S3 upload failed for %s: %v", sandboxID, err)
- return
- }
- log.Printf("firecracker: hibernate %s: S3 upload complete (%dms, key=%s)",
- sandboxID, time.Since(t2).Milliseconds(), checkpointKey)
-
- os.Remove(archivePath)
- }()
-
- return &sandbox.HibernateResult{
- SandboxID: sandboxID,
- HibernationKey: checkpointKey,
- SizeBytes: 0, // not known yet — archive happens async
- }, nil
-}
-
-// doWake restores a VM from a memory snapshot. The VM resumes exactly where it
-// was paused — all processes, memory, open files, and PIDs are intact.
-//
-// Flow:
-// 1. Check for local snapshot files (fast path for same-machine wake)
-// 2. If missing, download from S3 and extract
-// 3. Read snapshot-meta.json for VM configuration
-// 4. Verify drives exist at original paths
-// 5. Recreate network with same TAP name (required by vmstate)
-// 6. Start fresh Firecracker process with API socket
-// 7. Load snapshot via API (restores full VM state)
-// 8. Wait for agent to become available
-// 9. Register VM
-func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, checkpointStore *storage.CheckpointStore, timeout int) (*types.Sandbox, error) {
- sandboxDir := filepath.Join(m.cfg.DataDir, "sandboxes", sandboxID)
- snapshotDir := filepath.Join(sandboxDir, "snapshot")
-
- memFile := filepath.Join(snapshotDir, "mem")
- vmstateFile := filepath.Join(snapshotDir, "vmstate")
- metaPath := filepath.Join(snapshotDir, "snapshot-meta.json")
-
- // Step 1-2: Ensure snapshot files are local
- t0 := time.Now()
- memExists := fileExists(memFile)
- vmstateExists := fileExists(vmstateFile)
- log.Printf("firecracker: wake %s: checking local files: mem=%s (exists=%v) vmstate=%s (exists=%v)",
- sandboxID, memFile, memExists, vmstateFile, vmstateExists)
-
- // Local workspace-only recovery: no snapshot files, just workspace.ext4 on NVMe.
- // This happens after a hard kill where the worker didn't get to hibernate.
- isLocalWorkspace := strings.HasPrefix(checkpointKey, "local://")
-
- if !memExists || !vmstateExists {
- if isLocalWorkspace {
- // No snapshot to download — cold boot from local workspace.ext4.
- log.Printf("firecracker: wake %s: local workspace recovery (no snapshot)", sandboxID)
- return m.coldBootLocal(ctx, sandboxID, timeout)
- }
- log.Printf("firecracker: wake %s: local snapshot missing, downloading from S3 (key=%s)", sandboxID, checkpointKey)
- if err := os.MkdirAll(sandboxDir, 0755); err != nil {
- return nil, fmt.Errorf("mkdir sandbox dir: %w", err)
- }
- if err := os.MkdirAll(snapshotDir, 0755); err != nil {
- return nil, fmt.Errorf("mkdir snapshot dir: %w", err)
- }
-
- archiveData, err := checkpointStore.Download(ctx, checkpointKey)
- if err != nil {
- return nil, fmt.Errorf("download checkpoint: %w", err)
- }
-
- archivePath := filepath.Join(sandboxDir, "checkpoint.tar.zst")
- archiveFile, err := os.Create(archivePath)
- if err != nil {
- archiveData.Close()
- return nil, fmt.Errorf("create archive file: %w", err)
- }
- if _, err := io.Copy(archiveFile, archiveData); err != nil {
- archiveFile.Close()
- archiveData.Close()
- return nil, fmt.Errorf("write archive: %w", err)
- }
- archiveFile.Close()
- archiveData.Close()
-
- log.Printf("firecracker: wake %s: downloaded + wrote archive (%dms)", sandboxID, time.Since(t0).Milliseconds())
- // Extract to sandboxDir — archive contains snapshot/{mem,vmstate,snapshot-meta.json} + workspace.ext4
- if err := extractArchive(archivePath, sandboxDir); err != nil {
- return nil, fmt.Errorf("extract archive: %w", err)
- }
- os.Remove(archivePath)
- log.Printf("firecracker: wake %s: extracted archive (%dms total)", sandboxID, time.Since(t0).Milliseconds())
- } else {
- log.Printf("firecracker: wake %s: local snapshot found, skipping S3 download", sandboxID)
- }
-
- // Step 3: Read snapshot metadata
- metaJSON, err := os.ReadFile(metaPath)
- if err != nil {
- return nil, fmt.Errorf("read snapshot meta: %w", err)
- }
- var meta SnapshotMeta
- if err := json.Unmarshal(metaJSON, &meta); err != nil {
- return nil, fmt.Errorf("parse snapshot meta: %w", err)
- }
-
- // Step 4: Ensure drives exist — provision if missing (cross-worker wake)
- rootfsPath := filepath.Join(sandboxDir, "rootfs.ext4")
- workspacePath := filepath.Join(sandboxDir, "workspace.ext4")
-
- if !fileExists(rootfsPath) {
- // Cross-worker wake: recreate rootfs from template image
- log.Printf("firecracker: wake %s: rootfs missing, recreating from template %q", sandboxID, meta.Template)
- baseImage, err := ResolveBaseImage(m.cfg.ImagesDir, meta.Template)
- if err != nil {
- return nil, fmt.Errorf("resolve base image for wake: %w", err)
- }
- if err := PrepareRootfs(baseImage, rootfsPath); err != nil {
- return nil, fmt.Errorf("prepare rootfs for wake: %w", err)
- }
- log.Printf("firecracker: wake %s: rootfs recreated from %s", sandboxID, baseImage)
- }
- if !fileExists(workspacePath) {
- // workspace.ext4 should have been extracted from the S3 archive above.
- // If still missing, the archive was created before workspace archiving was added.
- return nil, fmt.Errorf("workspace not found at %s (not in S3 archive — sandbox was hibernated before workspace archiving was enabled)", workspacePath)
- }
-
- // Update metadata paths to this worker's sandboxDir (they may differ from the original worker).
- // Keep the vsock filename from the original — it's baked into the vmstate for snapshot restore.
- meta.RootfsPath = rootfsPath
- meta.WorkspacePath = workspacePath
- meta.VsockPath = filepath.Join(sandboxDir, filepath.Base(meta.VsockPath))
-
- // Step 5: Try snapshot restore (fast path) or cold boot (cross-worker fallback).
- //
- // Snapshot restore requires the exact same TAP name (baked into vmstate).
- // If the TAP name is already taken (cross-worker wake), fall back to cold boot:
- // boot a fresh VM with the restored rootfs + workspace. Processes won't survive
- // but filesystem state (user files, installed packages) is preserved.
- snapshotRestore := true
- netCfg, err := m.subnets.AllocateSpecific(meta.Network.TAPName)
- if err != nil {
- // TAP name collision — fall back to cold boot
- log.Printf("firecracker: wake %s: TAP %s unavailable (%v), falling back to cold boot",
- sandboxID, meta.Network.TAPName, err)
- snapshotRestore = false
- netCfg, err = m.subnets.Allocate()
- if err != nil {
- return nil, fmt.Errorf("allocate subnet for cold boot: %w", err)
- }
- }
- if err := CreateTAP(netCfg); err != nil {
- m.subnets.Release(netCfg.TAPName)
- return nil, fmt.Errorf("create TAP: %w", err)
- }
-
- hostPort, err := FindFreePort()
- if err != nil {
- DeleteTAP(netCfg.TAPName)
- m.subnets.Release(netCfg.TAPName)
- return nil, fmt.Errorf("find free port: %w", err)
- }
- netCfg.HostPort = hostPort
- netCfg.GuestPort = meta.GuestPort
- if netCfg.GuestPort == 0 {
- netCfg.GuestPort = 80
- }
-
- if err := AddDNAT(netCfg); err != nil {
- DeleteTAP(netCfg.TAPName)
- m.subnets.Release(netCfg.TAPName)
- return nil, fmt.Errorf("add DNAT: %w", err)
- }
-
- 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 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, "")
- 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, "")
- return nil, fmt.Errorf("wait for API socket: %w", err)
- }
-
- if snapshotRestore {
- // Hot restore: load snapshot, VM resumes exactly where it was paused
- if err := fcClient.LoadSnapshot(vmstateFile, memFile, true); err != nil {
- cmd.Process.Kill()
- cmd.Wait()
- m.cleanupVM(netCfg, "")
- return nil, fmt.Errorf("load snapshot: %w", err)
- }
- log.Printf("firecracker: wake %s: snapshot restored (hot)", sandboxID)
-
- // Wait for vsock.sock to appear — Firecracker recreates it from vmstate
- vsockDeadline := time.Now().Add(5 * time.Second)
- for !fileExists(vsockPath) && time.Now().Before(vsockDeadline) {
- time.Sleep(50 * time.Millisecond)
- }
- if !fileExists(vsockPath) {
- // Log Firecracker output for diagnosis
- if logData, err := os.ReadFile(filepath.Join(sandboxDir, "firecracker.log")); err == nil {
- log.Printf("firecracker: wake %s: vsock.sock NOT found at %s after 5s — FC log:\n%s",
- sandboxID, vsockPath, string(logData))
- }
- // Check if Firecracker process is still alive
- if cmd.Process != nil {
- if err := cmd.Process.Signal(syscall.Signal(0)); err != nil {
- log.Printf("firecracker: wake %s: FC process died: %v", sandboxID, err)
- }
- }
- } else {
- log.Printf("firecracker: wake %s: vsock.sock ready at %s", sandboxID, vsockPath)
- }
- } else {
- // Cold boot: configure + boot fresh VM with restored drives.
- // Filesystem state is preserved but running processes are not.
- guestCID := m.allocateCID()
- guestMAC := generateMAC(sandboxID)
- 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,
- )
- meta.GuestCID = guestCID
- meta.GuestMAC = guestMAC
- meta.BootArgs = bootArgs
-
- if err := fcClient.PutMachineConfig(meta.CpuCount, meta.MemoryMB); err != nil {
- cmd.Process.Kill(); cmd.Wait(); m.cleanupVM(netCfg, "")
- return nil, fmt.Errorf("cold boot: put machine config: %w", err)
- }
- if err := fcClient.PutBootSource(m.cfg.KernelPath, bootArgs); err != nil {
- cmd.Process.Kill(); cmd.Wait(); m.cleanupVM(netCfg, "")
- return nil, fmt.Errorf("cold boot: put boot source: %w", err)
- }
- if err := fcClient.PutDrive("rootfs", rootfsPath, true, false); err != nil {
- cmd.Process.Kill(); cmd.Wait(); m.cleanupVM(netCfg, "")
- return nil, fmt.Errorf("cold boot: put rootfs drive: %w", err)
- }
- if err := fcClient.PutDrive("workspace", workspacePath, false, false); err != nil {
- cmd.Process.Kill(); cmd.Wait(); m.cleanupVM(netCfg, "")
- return nil, fmt.Errorf("cold boot: put workspace drive: %w", err)
- }
- if err := fcClient.PutNetworkInterface("eth0", guestMAC, netCfg.TAPName); err != nil {
- cmd.Process.Kill(); cmd.Wait(); m.cleanupVM(netCfg, "")
- return nil, fmt.Errorf("cold boot: put network interface: %w", err)
- }
- if err := fcClient.PutVsock(guestCID, vsockPath); err != nil {
- cmd.Process.Kill(); cmd.Wait(); m.cleanupVM(netCfg, "")
- return nil, fmt.Errorf("cold boot: put vsock: %w", err)
- }
- if err := fcClient.StartInstance(); err != nil {
- cmd.Process.Kill(); cmd.Wait(); m.cleanupVM(netCfg, "")
- return nil, fmt.Errorf("cold boot: start instance: %w", err)
- }
- log.Printf("firecracker: wake %s: cold boot complete (cross-worker migration, tap=%s)",
- sandboxID, netCfg.TAPName)
- }
-
- now := time.Now()
- ttl := time.Duration(timeout) * time.Second
- if ttl <= 0 {
- ttl = 300 * time.Second
- }
-
- vm := &VMInstance{
- ID: sandboxID,
- Template: meta.Template,
- Status: types.SandboxStatusRunning,
- StartedAt: now,
- EndAt: now.Add(ttl),
- 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,
- }
-
- // Wait for agent
- agentClient, err := m.waitForAgent(context.Background(), vsockPath, 30*time.Second)
- if err != nil {
- cmd.Process.Kill()
- cmd.Wait()
- m.cleanupVM(netCfg, "")
- return nil, fmt.Errorf("agent not ready after wake: %w", err)
- }
- vm.agent = agentClient
-
- // Sync guest clock — frozen at snapshot time
- if err := syncGuestClock(context.Background(), agentClient); err != nil {
- log.Printf("firecracker: wake %s: clock sync failed: %v", sandboxID, err)
- }
-
- // Re-register secrets proxy session if token map was persisted
- if m.secretsProxy != nil && len(meta.SealedTokens) > 0 {
- m.secretsProxy.ReregisterSession(sandboxID, netCfg.GuestIP, meta.SealedTokens, meta.ProxyAllowlist, meta.ProxyTokenHosts)
- if err := AddProxyRedirect(netCfg); err != nil {
- log.Printf("firecracker: warning: proxy redirect failed for %s on wake: %v", sandboxID, err)
- }
- }
-
- // Register VM
- m.mu.Lock()
- m.vms[sandboxID] = vm
- m.mu.Unlock()
-
- mode := "snapshot restore"
- if !snapshotRestore {
- mode = "cold boot (cross-worker)"
- }
- log.Printf("firecracker: woke VM %s (%s, port=%d, tap=%s)",
- sandboxID, mode, hostPort, netCfg.TAPName)
-
- return vmToSandbox(vm), nil
-}
-
-// coldBootLocal boots a fresh VM using an existing workspace.ext4 on NVMe.
-// Used for hard kill recovery — processes are lost but /workspace files are preserved.
-func (m *Manager) coldBootLocal(ctx context.Context, sandboxID string, timeout int) (*types.Sandbox, error) {
- sandboxDir := filepath.Join(m.cfg.DataDir, "sandboxes", sandboxID)
- workspacePath := filepath.Join(sandboxDir, "workspace.ext4")
- rootfsPath := filepath.Join(sandboxDir, "rootfs.ext4")
-
- if !fileExists(workspacePath) {
- return nil, fmt.Errorf("workspace not found at %s", workspacePath)
- }
-
- // Read sandbox-meta.json for template + config
- sbMetaPath := filepath.Join(sandboxDir, "sandbox-meta.json")
- metaJSON, err := os.ReadFile(sbMetaPath)
- if err != nil {
- return nil, fmt.Errorf("read sandbox-meta.json: %w", err)
- }
- var meta SandboxMeta
- if err := json.Unmarshal(metaJSON, &meta); err != nil {
- return nil, fmt.Errorf("parse sandbox-meta.json: %w", err)
- }
-
- // Recreate rootfs from template if missing
- if !fileExists(rootfsPath) {
- baseImage, err := ResolveBaseImage(m.cfg.ImagesDir, meta.Template)
- if err != nil {
- return nil, fmt.Errorf("resolve base image: %w", err)
- }
- if err := PrepareRootfs(baseImage, rootfsPath); err != nil {
- return nil, fmt.Errorf("prepare rootfs: %w", err)
- }
- log.Printf("firecracker: cold-boot-local %s: rootfs recreated from template %q", sandboxID, meta.Template)
- }
-
- // Allocate fresh network
- netCfg, err := m.subnets.Allocate()
- if err != nil {
- return nil, fmt.Errorf("allocate subnet: %w", err)
- }
- if err := CreateTAP(netCfg); err != nil {
- m.subnets.Release(netCfg.TAPName)
- return nil, fmt.Errorf("create TAP: %w", err)
- }
-
- hostPort, err := FindFreePort()
- if err != nil {
- DeleteTAP(netCfg.TAPName)
- m.subnets.Release(netCfg.TAPName)
- return nil, fmt.Errorf("find free port: %w", err)
- }
- guestPort := meta.GuestPort
- if guestPort == 0 {
- guestPort = 80
- }
- netCfg.HostPort = hostPort
- netCfg.GuestPort = guestPort
-
- if err := AddDNAT(netCfg); err != nil {
- DeleteTAP(netCfg.TAPName)
- m.subnets.Release(netCfg.TAPName)
- return nil, fmt.Errorf("add DNAT: %w", err)
- }
-
- cpus := meta.CpuCount
- if cpus <= 0 {
- cpus = m.cfg.DefaultCPUs
- }
- memMB := meta.MemoryMB
- if memMB <= 0 {
- memMB = m.cfg.DefaultMemoryMB
- }
-
- vsockPath := filepath.Join(sandboxDir, "vsock.sock")
- guestCID := m.allocateCID()
- guestMAC := generateMAC(sandboxID)
- 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,
- )
-
- 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, "")
- 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, "")
- 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, "")
- return nil, fmt.Errorf("wait for API socket: %w", err)
- }
-
- // Configure and start VM
- if err := fcClient.PutMachineConfig(cpus, memMB); err != nil {
- cmd.Process.Kill(); cmd.Wait(); m.cleanupVM(netCfg, "")
- return nil, 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, "")
- return nil, 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, "")
- return nil, 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, "")
- return nil, 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, "")
- return nil, fmt.Errorf("put network interface: %w", err)
- }
- if err := fcClient.PutVsock(guestCID, vsockPath); err != nil {
- cmd.Process.Kill(); cmd.Wait(); m.cleanupVM(netCfg, "")
- return nil, fmt.Errorf("put vsock: %w", err)
- }
- if err := fcClient.StartInstance(); err != nil {
- cmd.Process.Kill(); cmd.Wait(); m.cleanupVM(netCfg, "")
- return nil, fmt.Errorf("start instance: %w", err)
- }
-
- now := time.Now()
- ttl := time.Duration(timeout) * time.Second
- if ttl <= 0 {
- ttl = 300 * time.Second
- }
-
- vm := &VMInstance{
- ID: sandboxID,
- Template: meta.Template,
- Status: types.SandboxStatusRunning,
- StartedAt: now,
- EndAt: now.Add(ttl),
- 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: guestMAC,
- guestCID: guestCID,
- bootArgs: bootArgs,
- }
-
- agentClient, err := m.waitForAgent(context.Background(), vsockPath, 30*time.Second)
- if err != nil {
- cmd.Process.Kill()
- cmd.Wait()
- m.cleanupVM(netCfg, "")
- return nil, fmt.Errorf("agent not ready after cold boot: %w", err)
- }
- vm.agent = agentClient
-
- // Sync guest clock — golden snapshot time is stale
- if err := syncGuestClock(context.Background(), agentClient); err != nil {
- log.Printf("firecracker: cold-boot-local %s: clock sync failed: %v", sandboxID, err)
- }
-
- m.mu.Lock()
- m.vms[sandboxID] = vm
- m.mu.Unlock()
-
- log.Printf("firecracker: cold-boot-local %s (template=%s, port=%d, tap=%s)", sandboxID, meta.Template, hostPort, netCfg.TAPName)
- return vmToSandbox(vm), nil
-}
-
-// createArchive creates a tar.zst archive of specific files from a directory.
-func createArchive(archivePath, baseDir string, files []string) error {
- args := []string{
- "--zstd",
- "-cf", archivePath,
- "-C", baseDir,
- }
- args = append(args, files...)
-
- cmd := exec.Command("tar", args...)
- if out, err := cmd.CombinedOutput(); err != nil {
- return fmt.Errorf("tar create: %w (%s)", err, strings.TrimSpace(string(out)))
- }
- return nil
-}
-
-// extractArchive extracts a tar.zst archive to a directory.
-func extractArchive(archivePath, destDir string) error {
- cmd := exec.Command("tar", "--zstd", "-xf", archivePath, "-C", destDir)
- if out, err := cmd.CombinedOutput(); err != nil {
- return fmt.Errorf("tar extract: %w (%s)", err, strings.TrimSpace(string(out)))
- }
- return nil
-}
-
-// fileExists checks if a file exists and is not a directory.
-func fileExists(path string) bool {
- info, err := os.Stat(path)
- return err == nil && !info.IsDir()
-}
-
-// templateCacheDir returns the local cache directory for a template's ext4 drives.
-func (m *Manager) templateCacheDir(templateID string) string {
- return filepath.Join(m.cfg.DataDir, "templates", templateID)
-}
-
-// TemplateCachePath returns the local path to a cached template drive, or "" if not cached.
-func (m *Manager) TemplateCachePath(templateID, filename string) string {
- p := filepath.Join(m.templateCacheDir(templateID), filename)
- if _, err := os.Stat(p); err == nil {
- return p
- }
- return ""
-}
-
-// checkpointCacheDir returns the local cache directory for a checkpoint's ext4 drives.
-func (m *Manager) checkpointCacheDir(checkpointID string) string {
- return filepath.Join(m.cfg.DataDir, "checkpoints", checkpointID)
-}
-
-// CheckpointCachePath returns the local path to a cached checkpoint drive, or "" if not cached.
-func (m *Manager) CheckpointCachePath(checkpointID, filename string) string {
- p := filepath.Join(m.checkpointCacheDir(checkpointID), filename)
- if _, err := os.Stat(p); err == nil {
- return p
- }
- return ""
-}
-
-// 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 {
- return "", "", err
- }
-
- t0 := time.Now()
-
- rootfsKey = fmt.Sprintf("checkpoints/%s/%s/rootfs.tar.zst", sandboxID, checkpointID)
- workspaceKey = fmt.Sprintf("checkpoints/%s/%s/workspace.sparse.zst", sandboxID, checkpointID)
-
- srcRootfs := filepath.Join(vm.sandboxDir, "rootfs.ext4")
- srcWorkspace := filepath.Join(vm.sandboxDir, "workspace.ext4")
-
- // Cache checkpoint drives locally for fast restore
- cacheDir := m.checkpointCacheDir(checkpointID)
- if err := os.MkdirAll(cacheDir, 0755); err != nil {
- return "", "", fmt.Errorf("create checkpoint cache dir: %w", err)
- }
- cachedRootfs := filepath.Join(cacheDir, "rootfs.ext4")
- cachedWorkspace := filepath.Join(cacheDir, "workspace.ext4")
-
- // Step 1: Flush guest filesystem data to disk (required for cold boot forks that don't use memory snapshot).
- // We run `sync` as a subprocess because syscall.Sync() from PID 1 (the agent) doesn't reliably
- // flush dirty pages to the virtio-blk device after snapshot restore. Running sync as a child
- // process works correctly and ensures all dirty pages are written to the host file.
- if vm.agent != nil {
- tSync1 := time.Now()
- syncCtx, syncCancel := context.WithTimeout(ctx, 10*time.Second)
- resp, syncErr := vm.agent.Exec(syncCtx, &pb.ExecRequest{
- Command: "sync",
- })
- syncCancel()
- if syncErr != nil {
- log.Printf("firecracker: CreateCheckpoint %s/%s: exec sync failed: %v", vm.ID, checkpointID, syncErr)
- } else if resp.ExitCode != 0 {
- log.Printf("firecracker: CreateCheckpoint %s/%s: exec sync exit code %d: %s", vm.ID, checkpointID, resp.ExitCode, resp.Stderr)
- } else {
- log.Printf("firecracker: CreateCheckpoint %s/%s: guest sync completed (%dms)", vm.ID, checkpointID, time.Since(tSync1).Milliseconds())
- }
- } else {
- log.Printf("firecracker: CreateCheckpoint %s/%s: WARNING: vm.agent is nil, guest sync SKIPPED!", vm.ID, checkpointID)
- }
-
- // Step 1b: Quiesce eth0 before snapshotting to ensure clean virtio-net virtqueues.
- // Flush addresses first so the host stops sending ARP/IPv6 ND traffic to this TAP,
- // then bring eth0 down to drain the virtqueues. Without the flush, a race exists
- // where packets arrive in the RX used ring while NAPI drains, corrupting the snapshot.
- // Warm forks get a new TAP and the guest kernel resumes with clean virtqueues.
- if vm.agent != nil {
- _, _ = vm.agent.Exec(ctx, &pb.ExecRequest{
- Command: "/bin/sh",
- Args: []string{"-c", "ip addr flush dev eth0 && ip link set eth0 down"},
- TimeoutSeconds: 5,
- })
- }
-
- // Step 2: Close gRPC connection (vsock must be inactive before pause).
- // Drain delay prevents stale vsock virtqueue entries from breaking vhost-vsock after restore.
- if vm.agent != nil {
- vm.agent.Close()
- vm.agent = nil
- time.Sleep(500 * time.Millisecond)
- }
-
- // Step 3: Pause the VM
- if err = vm.fcClient.PauseVM(); err != nil {
- if agent, reconnErr := m.waitForAgent(ctx, vm.vsockPath, 5*time.Second); reconnErr == nil {
- vm.agent = agent
- // eth0 was taken down in step 1b — bring it back up since we're aborting
- if vm.network != nil {
- reconfigureGuestNetwork(ctx, agent, vm.network.GuestIP, vm.network.HostIP, vm.network.CIDR)
- }
- }
- os.RemoveAll(cacheDir)
- return "", "", fmt.Errorf("pause VM for checkpoint: %w", err)
- }
- log.Printf("firecracker: CreateCheckpoint %s/%s: VM paused (%dms)", vm.ID, checkpointID, time.Since(t0).Milliseconds())
-
- // Step 4: Create memory snapshot to tmpfs (/dev/shm) for fast write.
- // Writing to tmpfs avoids NVMe fsync overhead (the main bottleneck: 15-100s on disk).
- // Tmpfs writes are memory-bandwidth limited (~30-100ms for 1GB) since they're just memcpy.
- // The memory file is moved from tmpfs to the checkpoint cache dir in the background after resume.
- snapshotDir := filepath.Join(cacheDir, "snapshot")
- if mkdirErr := os.MkdirAll(snapshotDir, 0755); mkdirErr != nil {
- log.Printf("firecracker: CreateCheckpoint %s: mkdir snapshot dir failed: %v", vm.ID, mkdirErr)
- }
- vmstateFile := filepath.Join(snapshotDir, "vmstate")
- tmpfsMemFile := fmt.Sprintf("/dev/shm/fc-snap-%s-%s.mem", sandboxID, checkpointID)
- finalMemFile := filepath.Join(snapshotDir, "mem")
-
- var snapshotErr error
- tSnap := time.Now()
- if err := vm.fcClient.CreateSnapshot(vmstateFile, tmpfsMemFile); err != nil {
- log.Printf("firecracker: CreateCheckpoint %s/%s: memory snapshot failed: %v (will fall back to cold boot restore)", vm.ID, checkpointID, err)
- snapshotErr = err
- // Clean up partial snapshot files
- os.Remove(tmpfsMemFile)
- os.Remove(vmstateFile)
- os.RemoveAll(snapshotDir)
- } else {
- log.Printf("firecracker: CreateCheckpoint %s/%s: memory snapshot to tmpfs (%dms)", vm.ID, checkpointID, time.Since(tSnap).Milliseconds())
- }
-
- // Step 5: Host-side fsync as insurance — guest sync should have already flushed
- // all dirty pages via Firecracker pwrite, but this ensures XFS CoW block allocation.
- for _, drivePath := range []string{srcRootfs, srcWorkspace} {
- if f, err := os.OpenFile(drivePath, os.O_RDWR, 0); err == nil {
- f.Sync()
- f.Close()
- }
- }
-
- // Step 5b: Copy drive files while VM is paused (drives are stable via reflink, sub-ms)
- copyErr := copyFileReflink(srcRootfs, cachedRootfs)
- if copyErr == nil {
- copyErr = copyFileReflink(srcWorkspace, cachedWorkspace)
- if copyErr != nil {
- os.Remove(cachedRootfs)
- }
- }
-
- // Step 6: Resume the VM regardless of copy/snapshot result
- resumeErr := vm.fcClient.ResumeVM()
- if resumeErr != nil {
- log.Printf("firecracker: CreateCheckpoint %s: CRITICAL: resume failed: %v", vm.ID, resumeErr)
- os.Remove(tmpfsMemFile)
- os.RemoveAll(cacheDir)
- return "", "", fmt.Errorf("resume VM after checkpoint: %w", resumeErr)
- }
- pauseDuration := time.Since(t0)
- log.Printf("firecracker: CreateCheckpoint %s/%s: VM resumed, total pause=%dms", vm.ID, checkpointID, pauseDuration.Milliseconds())
-
- if copyErr != nil {
- os.Remove(tmpfsMemFile)
- if agent, reconnErr := m.waitForAgent(ctx, vm.vsockPath, 10*time.Second); reconnErr == nil {
- vm.agent = agent
- // eth0 was taken down in step 1b — bring it back up since we're aborting
- if vm.network != nil {
- reconfigureGuestNetwork(ctx, agent, vm.network.GuestIP, vm.network.HostIP, vm.network.CIDR)
- }
- }
- os.RemoveAll(cacheDir)
- return "", "", fmt.Errorf("copy drives for checkpoint: %w", copyErr)
- }
-
- // Step 7: Reconnect agent
- agent, reconnErr := m.waitForAgent(ctx, vm.vsockPath, 10*time.Second)
- if reconnErr != nil {
- log.Printf("firecracker: CreateCheckpoint %s: agent reconnect failed: %v (VM still running)", vm.ID, reconnErr)
- } else {
- vm.agent = agent
- // Bring eth0 back up — it was taken down before snapshotting to drain virtio-net queues
- if vm.network != nil {
- if err := reconfigureGuestNetwork(ctx, agent, vm.network.GuestIP, vm.network.HostIP, vm.network.CIDR); err != nil {
- log.Printf("firecracker: CreateCheckpoint %s: eth0 restore failed: %v", vm.ID, err)
- }
- }
- // Sync guest clock — paused during snapshot
- if err := syncGuestClock(ctx, agent); err != nil {
- log.Printf("firecracker: CreateCheckpoint %s: clock sync failed: %v", vm.ID, err)
- }
- }
-
- // Step 8: Write snapshot metadata + move mem from tmpfs (background)
- // If memory snapshot succeeded, write metadata and move the mem file
- // from /dev/shm to the checkpoint cache dir. This happens after resume
- // so it doesn't contribute to pause duration.
- hasSnapshot := snapshotErr == nil
-
- if hasSnapshot {
- // Write snapshot metadata (needed for warm restore)
- 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,
- SnapshotedAt: time.Now(),
- }
- metaJSON, _ := json.MarshalIndent(meta, "", " ")
- if writeErr := os.WriteFile(filepath.Join(snapshotDir, "snapshot-meta.json"), metaJSON, 0644); writeErr != nil {
- log.Printf("firecracker: CreateCheckpoint %s: write snapshot meta failed: %v", vm.ID, writeErr)
- hasSnapshot = false
- os.Remove(tmpfsMemFile)
- }
- }
-
- // Step 9: Async move mem from tmpfs + compress + upload to S3
- 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)
- }
- }()
-
- // Move memory file from tmpfs to checkpoint cache (frees tmpfs RAM)
- if hasSnapshot {
- tMove := time.Now()
- if moveErr := os.Rename(tmpfsMemFile, finalMemFile); moveErr != nil {
- // Rename across filesystems (tmpfs→xfs) won't work, fall back to copy+delete
- if cpErr := copyFile(tmpfsMemFile, finalMemFile); cpErr != nil {
- log.Printf("firecracker: checkpoint %s: move mem from tmpfs failed: %v", checkpointID, cpErr)
- os.Remove(tmpfsMemFile)
- } else {
- os.Remove(tmpfsMemFile)
- log.Printf("firecracker: checkpoint %s: mem copied from tmpfs (%dms)", checkpointID, time.Since(tMove).Milliseconds())
- }
- } else {
- log.Printf("firecracker: checkpoint %s: mem moved from tmpfs (%dms)", checkpointID, time.Since(tMove).Milliseconds())
- }
- }
-
- uploadCtx, cancel := context.WithTimeout(context.Background(), 15*time.Minute)
- defer cancel()
-
- t1 := time.Now()
- if err := compressAndUploadFile(uploadCtx, cachedRootfs, rootfsKey, checkpointStore); err != nil {
- log.Printf("firecracker: checkpoint %s: rootfs upload failed: %v", checkpointID, err)
- return
- }
- log.Printf("firecracker: checkpoint %s: rootfs uploaded (%dms)", checkpointID, time.Since(t1).Milliseconds())
-
- t2 := time.Now()
- if err := sparseCompressAndUpload(uploadCtx, cachedWorkspace, workspaceKey, checkpointStore); err != nil {
- log.Printf("firecracker: checkpoint %s: workspace upload failed: %v", checkpointID, err)
- return
- }
- log.Printf("firecracker: checkpoint %s: ready (%dms, total=%dms)", checkpointID, time.Since(t2).Milliseconds(), time.Since(t0).Milliseconds())
- if onReady != nil {
- onReady()
- }
- }()
-
- return rootfsKey, workspaceKey, nil
-}
-
-// RestoreFromCheckpoint reverts a running sandbox to a checkpoint.
-// 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 drives exist locally
- if _, err := os.Stat(cachedRootfs); err != nil {
- return fmt.Errorf("checkpoint rootfs not found locally: %w", err)
- }
- if _, err := os.Stat(cachedWorkspace); err != nil {
- return fmt.Errorf("checkpoint workspace not found locally: %w", err)
- }
-
- // 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 + kill VM + clean up
- 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()
- }
- _ = os.Remove(vm.vsockPath)
- if vm.apiSockPath != "" {
- _ = os.Remove(vm.apiSockPath)
- }
- log.Printf("firecracker: warmRestore %s: killed (%dms)", sandboxID, time.Since(t0).Milliseconds())
-
- // Step 2: 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)
- }
- log.Printf("firecracker: warmRestore %s: drives copied (%dms)", sandboxID, time.Since(t0).Milliseconds())
-
- // Step 3: 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)
- }
-
- 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)
- }
-
- log.Printf("firecracker: warmRestore %s: network ready (%dms)", sandboxID, time.Since(t0).Milliseconds())
-
- // Step 4: 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)
- }
-
- log.Printf("firecracker: warmRestore %s: FC started (%dms)", sandboxID, time.Since(t0).Milliseconds())
-
- // Step 5: 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 6: 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 7: Bring eth0 back up (snapshot drains virtqueues by taking eth0 down)
- if err := reconfigureGuestNetwork(ctx, agentClient, netCfg.GuestIP, netCfg.HostIP, netCfg.CIDR); err != nil {
- log.Printf("firecracker: warmRestore %s: network reconfig failed: %v (VM still running, network may not work)", sandboxID, err)
- }
-
- // Sync guest clock — frozen at checkpoint time
- if err := syncGuestClock(ctx, agentClient); err != nil {
- log.Printf("firecracker: warmRestore %s: clock sync failed: %v", sandboxID, err)
- }
-
- // Step 8: 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) // remove old entry if still present
- m.vms[sandboxID] = newVM
- m.mu.Unlock()
-
- 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,
- MemoryMB: memoryMB,
- Port: guestPort,
- NetworkEnabled: true,
- TemplateRootfsKey: "local://" + cachedRootfs,
- TemplateWorkspaceKey: "local://" + cachedWorkspace,
- }
-
- sb, err := m.createWithID(ctx, sandboxID, cfg)
- if err != nil {
- return fmt.Errorf("cold boot after checkpoint restore: %w", err)
- }
- log.Printf("firecracker: RestoreFromCheckpoint %s/%s: VM cold booted (status=%s)", sandboxID, checkpointID, sb.Status)
-
- return nil
-}
-
-// copyFileReflink copies a file using cp --reflink=auto (instant on XFS reflink, fallback to full copy).
-func copyFileReflink(src, dst string) error {
- cmd := exec.Command("cp", "--reflink=auto", src, dst)
- if out, err := cmd.CombinedOutput(); err != nil {
- return fmt.Errorf("cp %s → %s: %w (%s)", src, dst, err, strings.TrimSpace(string(out)))
- }
- return nil
-}
-
-// copyFile copies a file using standard cp (no reflink). Used for cross-filesystem
-// copies like tmpfs → xfs where os.Rename doesn't work.
-func copyFile(src, dst string) error {
- cmd := exec.Command("cp", src, dst)
- if out, err := cmd.CombinedOutput(); err != nil {
- return fmt.Errorf("cp %s → %s: %w (%s)", src, dst, err, strings.TrimSpace(string(out)))
- }
- return nil
-}
-
-// sparseCompressAndUpload creates a sparse archive of a file and uploads it to S3.
-// Only non-zero 4KB blocks are stored, making archive size proportional to actual content.
-func sparseCompressAndUpload(ctx context.Context, srcPath, s3Key string, store *storage.CheckpointStore) error {
- archivePath := srcPath + ".sparse.zst"
- blocks, err := sparse.Create(srcPath, archivePath)
- if err != nil {
- return fmt.Errorf("sparse compress: %w", err)
- }
- defer os.Remove(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)
-
- if _, err := store.Upload(ctx, s3Key, archivePath); err != nil {
- return fmt.Errorf("upload to %s: %w", s3Key, err)
- }
- return nil
-}
-
-// compressAndUploadFile compresses a single file as a tar.zst archive and uploads it to S3.
-func compressAndUploadFile(ctx context.Context, srcPath, s3Key string, store *storage.CheckpointStore) error {
- archivePath := srcPath + ".tar.zst"
- if err := createArchive(archivePath, filepath.Dir(srcPath), []string{filepath.Base(srcPath)}); err != nil {
- return fmt.Errorf("compress: %w", err)
- }
- defer os.Remove(archivePath)
-
- if _, err := store.Upload(ctx, s3Key, archivePath); err != nil {
- return fmt.Errorf("upload to %s: %w", s3Key, err)
- }
- 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
-}
-
-// syncGuestClock sets the guest clock to the current host time via agent exec.
-// After snapshot restore the guest clock is frozen at the time the snapshot was taken.
-// Without correction, TLS, timeouts, and time-sensitive operations will break.
-func syncGuestClock(ctx context.Context, agent *AgentClient) error {
- now := time.Now().Unix()
- cmd := fmt.Sprintf("date -s @%d > /dev/null 2>&1", now)
- resp, err := agent.Exec(ctx, &pb.ExecRequest{
- Command: "/bin/sh",
- Args: []string{"-c", cmd},
- TimeoutSeconds: 5,
- })
- if err != nil {
- return fmt.Errorf("exec clock sync: %w", err)
- }
- if resp.ExitCode != 0 {
- return fmt.Errorf("clock sync 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
- }
-
- // Sync guest clock — frozen at checkpoint time
- if err := syncGuestClock(ctx, agentClient); err != nil {
- log.Printf("firecracker: warmFork %s: clock sync failed: %v", newID, err)
- }
-
- // Secrets proxy integration: seal env vars and set up proxy redirect
- envsToInject := cfg.Envs
- if m.secretsProxy != nil && len(cfg.Envs) > 0 {
- sealedEnvs := m.secretsProxy.CreateSealedEnvs(newID, netCfg.GuestIP, netCfg.HostIP, cfg.Envs, cfg.EgressAllowlist, cfg.SecretAllowedHosts)
- if sealedEnvs != nil {
- envsToInject = sealedEnvs
- if err := AddProxyRedirect(netCfg); err != nil {
- log.Printf("firecracker: warning: proxy redirect failed for %s: %v", newID, err)
- }
- m.injectCACert(ctx, agentClient, newID)
- }
- }
-
- // Send sandbox-level env vars into the forked VM agent
- if len(envsToInject) > 0 {
- envCtx, envCancel := context.WithTimeout(context.Background(), 5*time.Second)
- if err := agentClient.SetEnvs(envCtx, envsToInject); err != nil {
- envCancel()
- log.Printf("firecracker: warning: SetEnvs failed for %s: %v", newID, err)
- }
- envCancel()
- }
-
- // 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())
-
- // Quiesce networking before snapshotting to ensure clean virtio-net virtqueues.
- //
- // The host-side TAP must be brought down FIRST to stop all packet delivery
- // into the guest's virtio-net RX ring. Only then is the guest side flushed
- // and downed. Without this ordering, the host can push ARP/IPv6 ND packets
- // into the RX used ring between the guest flush and the VM pause, corrupting
- // the virtqueue state. On restore this manifests as:
- // "virtio_net virtio2: input.0:id 0 is not a head!"
- // (vq->broken=true) which permanently breaks virtio-net RX for every
- // sandbox created from this golden snapshot.
- _ = run("ip", "link", "set", netCfg.TAPName, "down")
-
- _, _ = agent.Exec(context.Background(), &pb.ExecRequest{
- Command: "/bin/sh",
- Args: []string{"-c", "ip addr flush dev eth0 && ip link set eth0 down"},
- TimeoutSeconds: 5,
- })
-
- agent.Close()
- time.Sleep(500 * time.Millisecond) // drain vsock virtqueues before pause
-
- 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,
- SnapshotedAt: time.Now(),
- }
- 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
-}
-
-// registerTemplateGoldenFromCache creates a per-checkpoint golden snapshot by reflink-copying
-// files from the checkpoint cache. Called after CreateCheckpoint when the checkpoint is for
-// an image/snapshot build. All copies are reflink (instant CoW) — no extra VM boot needed.
-func (m *Manager) RegisterTemplateGoldenFromCache(checkpointID string) {
- m.goldenMu.RLock()
- existing := m.templateGoldens[checkpointID]
- m.goldenMu.RUnlock()
- if existing != nil {
- return
- }
-
- t0 := time.Now()
- cacheDir := m.checkpointCacheDir(checkpointID)
- goldenDir := filepath.Join(m.cfg.DataDir, "golden-snapshot", "template-"+checkpointID)
-
- // Verify checkpoint cache has all required files
- requiredFiles := []string{
- filepath.Join(cacheDir, "rootfs.ext4"),
- filepath.Join(cacheDir, "workspace.ext4"),
- filepath.Join(cacheDir, "snapshot", "mem"),
- filepath.Join(cacheDir, "snapshot", "vmstate"),
- filepath.Join(cacheDir, "snapshot", "snapshot-meta.json"),
- }
- for _, f := range requiredFiles {
- if !fileExists(f) {
- log.Printf("firecracker: template golden %s: missing %s, skipping", checkpointID, f)
- return
- }
- }
-
- os.RemoveAll(goldenDir)
- if err := os.MkdirAll(filepath.Join(goldenDir, "snapshot"), 0755); err != nil {
- log.Printf("firecracker: template golden %s: mkdir failed: %v", checkpointID, err)
- return
- }
-
- // Reflink-copy drives and snapshot files (~1ms total with CoW)
- copies := [][2]string{
- {filepath.Join(cacheDir, "rootfs.ext4"), filepath.Join(goldenDir, "rootfs.ext4")},
- {filepath.Join(cacheDir, "workspace.ext4"), filepath.Join(goldenDir, "workspace.ext4")},
- {filepath.Join(cacheDir, "snapshot", "mem"), filepath.Join(goldenDir, "snapshot", "mem")},
- {filepath.Join(cacheDir, "snapshot", "vmstate"), filepath.Join(goldenDir, "snapshot", "vmstate")},
- }
- for _, cp := range copies {
- if err := copyFileReflink(cp[0], cp[1]); err != nil {
- log.Printf("firecracker: template golden %s: copy %s failed: %v", checkpointID, cp[0], err)
- os.RemoveAll(goldenDir)
- return
- }
- }
-
- // Read the checkpoint's snapshot metadata and use it for the golden snapshot
- metaBytes, err := os.ReadFile(filepath.Join(cacheDir, "snapshot", "snapshot-meta.json"))
- if err != nil {
- log.Printf("firecracker: template golden %s: read meta failed: %v", checkpointID, err)
- os.RemoveAll(goldenDir)
- return
- }
- var meta SnapshotMeta
- if err := json.Unmarshal(metaBytes, &meta); err != nil {
- log.Printf("firecracker: template golden %s: parse meta failed: %v", checkpointID, err)
- os.RemoveAll(goldenDir)
- return
- }
-
- // Write golden snapshot metadata (copy to golden dir)
- _ = os.WriteFile(filepath.Join(goldenDir, "snapshot", "snapshot-meta.json"), metaBytes, 0644)
-
- gs := &GoldenSnapshot{
- Dir: goldenDir,
- Meta: meta,
- Ready: true,
- }
- m.goldenMu.Lock()
- m.templateGoldens[checkpointID] = gs
- m.goldenMu.Unlock()
-
- log.Printf("firecracker: template golden snapshot ready for %s at %s (%dms)", checkpointID, goldenDir, time.Since(t0).Milliseconds())
-}
-
-// 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) {
- // Pick the right golden snapshot: per-template if CheckpointID is set, otherwise the default.
- m.goldenMu.RLock()
- var gs *GoldenSnapshot
- if cfg.CheckpointID != "" {
- gs = m.templateGoldens[cfg.CheckpointID]
- } else {
- 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, advancing guest clock to compensate for time since golden snapshot was taken
- 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
- // Use background context — the HTTP request context may be cancelled by the client
- bgCtx := context.Background()
- if err := reconfigureGuestNetwork(bgCtx, agentClient, netCfg.GuestIP, netCfg.HostIP, netCfg.CIDR); err != nil {
- log.Printf("firecracker: goldenCreate %s: network reconfig failed: %v (VM still running)", id, err)
- }
-
- // Sync guest clock — golden snapshot time is stale
- if err := syncGuestClock(bgCtx, agentClient); err != nil {
- log.Printf("firecracker: goldenCreate %s: clock sync failed: %v", id, err)
- }
-
- // Secrets proxy integration: seal env vars and set up proxy redirect
- envsToInject := cfg.Envs
- if m.secretsProxy != nil && len(cfg.Envs) > 0 {
- sealedEnvs := m.secretsProxy.CreateSealedEnvs(id, netCfg.GuestIP, netCfg.HostIP, cfg.Envs, cfg.EgressAllowlist, cfg.SecretAllowedHosts)
- if sealedEnvs != nil {
- envsToInject = sealedEnvs
- if err := AddProxyRedirect(netCfg); err != nil {
- log.Printf("firecracker: warning: proxy redirect failed for %s: %v", id, err)
- }
- m.injectCACert(ctx, agentClient, id)
- }
- }
-
- // Send sandbox-level env vars into the VM agent
- if len(envsToInject) > 0 {
- envCtx, envCancel := context.WithTimeout(context.Background(), 5*time.Second)
- if err := agentClient.SetEnvs(envCtx, envsToInject); err != nil {
- envCancel()
- log.Printf("firecracker: warning: SetEnvs failed for %s: %v", id, err)
- }
- envCancel()
- }
-
- // 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/qemu/manager.go b/internal/qemu/manager.go
index b2ec896b..915209f7 100644
--- a/internal/qemu/manager.go
+++ b/internal/qemu/manager.go
@@ -67,7 +67,7 @@ type SandboxMeta struct {
}
// SecretsProxyIntegration provides the interface for the secrets proxy to integrate
-// with VM lifecycle. Defined here (not imported from firecracker) to avoid circular deps.
+// with VM lifecycle.
type SecretsProxyIntegration interface {
// CreateSealedEnvs generates sealed tokens for env vars, registers a proxy session,
// and returns the full env map (sealed tokens + proxy config vars) to inject into the VM.
@@ -130,10 +130,10 @@ func NewManager(cfg Config) (*Manager, error) {
return nil, fmt.Errorf("DataDir is required")
}
if cfg.KernelPath == "" {
- cfg.KernelPath = filepath.Join(cfg.DataDir, "firecracker", "vmlinux-docker-5.10.bin")
+ cfg.KernelPath = filepath.Join(cfg.DataDir, "vmlinux")
}
if cfg.ImagesDir == "" {
- cfg.ImagesDir = filepath.Join(cfg.DataDir, "firecracker", "images")
+ cfg.ImagesDir = filepath.Join(cfg.DataDir, "images")
}
if cfg.QEMUBin == "" {
cfg.QEMUBin = "qemu-system-x86_64"