An open-source, faster Devin alternative
TypeScript
Add QEMU q35 VM backend and Azure deployment scripts
motatoesbc63b501f220
diff --git a/.gitignore b/.gitignoreindex f6d84f67..66d5bce0 100644--- a/.gitignore+++ b/.gitignore@@ -57,3 +57,4 @@ deploy/ec2/*.pem*.tmp*.logdelme+deploy/azure/.dev-env-state-*diff --git a/cmd/worker/main.go b/cmd/worker/main.goindex 29a8c72f..12a0f891 100644--- a/cmd/worker/main.go+++ b/cmd/worker/main.go@@ -15,6 +15,7 @@ import ("github.com/opensandbox/opensandbox/internal/config""github.com/opensandbox/opensandbox/internal/db"fc "github.com/opensandbox/opensandbox/internal/firecracker"+ qm "github.com/opensandbox/opensandbox/internal/qemu"agentpb "github.com/opensandbox/opensandbox/proto/agent""github.com/opensandbox/opensandbox/internal/metrics""github.com/opensandbox/opensandbox/internal/proxy"@@ -30,196 +31,202 @@ func main() {log.Fatalf("failed to load config: %v", err)}- log.Printf("opensandbox-worker: starting (id=%s, region=%s)...", cfg.WorkerID, cfg.Region)+ log.Printf("opensandbox-worker: starting (id=%s, region=%s, backend=%s)...", cfg.WorkerID, cfg.Region, cfg.VMBackend)ctx := context.Background()- // Initialize Firecracker-based sandbox manager- fcCfg := fc.Config{- DataDir: cfg.DataDir,- KernelPath: cfg.KernelPath,- ImagesDir: cfg.ImagesDir,- FirecrackerBin: cfg.FirecrackerBin,- DefaultMemoryMB: cfg.DefaultSandboxMemoryMB,- DefaultCPUs: cfg.DefaultSandboxCPUs,- DefaultDiskMB: cfg.DefaultSandboxDiskMB,- }-- fcMgr, err := fc.NewManager(fcCfg)- if err != nil {- log.Fatalf("failed to initialize Firecracker manager: %v", err)- }- defer fcMgr.Close()- log.Println("opensandbox-worker: Firecracker VM manager initialized")-- // Clean up orphaned Firecracker processes + TAP devices BEFORE starting golden snapshot.- // Must run first to avoid killing the golden snapshot VM (race condition).- fcMgr.CleanupOrphanedProcesses()-- // Prepare golden snapshot for fast default VM creation (~500ms vs ~2s cold boot)- go func() {- if err := fcMgr.PrepareGoldenSnapshot(); err != nil {- log.Printf("opensandbox-worker: golden snapshot preparation failed: %v (cold boot fallback active)", err)+ var mgr sandbox.Manager++ // Backend-specific exec session factory+ var execSessionFactory func(sandboxID string, req types.ExecSessionCreateRequest) (*sandbox.ExecSessionHandle, error)+ // Backend-specific PTY session factory+ var ptySessionFactory func(sandboxID string, req types.PTYCreateRequest) (*sandbox.PTYSessionHandle, error)+ // Backend-specific autosaver syncer+ var autosaverSyncer worker.SyncFSer+ // Backend-specific graceful shutdown+ var doGracefulShutdown func(checkpointStore *storage.CheckpointStore, store *db.Store)++ switch cfg.VMBackend {+ case "firecracker":+ fcCfg := fc.Config{+ DataDir: cfg.DataDir,+ KernelPath: cfg.KernelPath,+ ImagesDir: cfg.ImagesDir,+ FirecrackerBin: cfg.FirecrackerBin,+ DefaultMemoryMB: cfg.DefaultSandboxMemoryMB,+ DefaultCPUs: cfg.DefaultSandboxCPUs,+ DefaultDiskMB: cfg.DefaultSandboxDiskMB,}- }()-- // The Firecracker manager implements sandbox.Manager- var mgr sandbox.Manager = fcMgr- // Initialize PTY manager using Firecracker agent gRPC- // Initialize exec session manager using Firecracker agent gRPC- execMgr := sandbox.NewAgentExecSessionManager(func(sandboxID string, req types.ExecSessionCreateRequest) (*sandbox.ExecSessionHandle, error) {- agent, err := fcMgr.GetAgent(sandboxID)+ fcMgr, err := fc.NewManager(fcCfg)if err != nil {- return nil, fmt.Errorf("get agent for %s: %w", sandboxID, err)+ log.Fatalf("failed to initialize Firecracker manager: %v", err)}+ defer fcMgr.Close()+ log.Println("opensandbox-worker: Firecracker VM manager initialized")- agentPB := &agentpb.ExecSessionCreateRequest{- Command: req.Command,- Args: req.Args,- Envs: req.Env,- Cwd: req.Cwd,- TimeoutSeconds: int32(req.Timeout),- MaxRunAfterDisconnect: int32(req.MaxRunAfterDisconnect),- }+ fcMgr.CleanupOrphanedProcesses()- sessionID, err := agent.ExecSessionCreate(context.Background(), agentPB)- if err != nil {- return nil, fmt.Errorf("create exec session in VM: %w", err)- }+ go func() {+ if err := fcMgr.PrepareGoldenSnapshot(); err != nil {+ log.Printf("opensandbox-worker: golden snapshot preparation failed: %v (cold boot fallback active)", err)+ }+ }()- scrollback := sandbox.NewScrollbackBuffer(0)- done := make(chan struct{})-- // Create a pipe for stdin: writes to stdinW are forwarded to the gRPC stream- stdinR, stdinW := io.Pipe()-- handle := &sandbox.ExecSessionHandle{- ID: sessionID,- SandboxID: sandboxID,- Command: req.Command,- Args: req.Args,- Running: true,- StartedAt: time.Now(),- Done: done,- Scrollback: scrollback,- StdinWriter: stdinW,- OnKill: func(signal int) error {- stdinW.Close()- return agent.ExecSessionKill(context.Background(), sessionID, int32(signal))- },+ mgr = fcMgr+ autosaverSyncer = fcMgr++ execSessionFactory = func(sandboxID string, req types.ExecSessionCreateRequest) (*sandbox.ExecSessionHandle, error) {+ agent, err := fcMgr.GetAgent(sandboxID)+ if err != nil {+ return nil, fmt.Errorf("get agent for %s: %w", sandboxID, err)+ }+ return createExecSession(agent, sandboxID, req)}- // Attach to the session to pipe output into the host-side scrollback- go func() {- defer close(done)- defer stdinR.Close()- stream, err := agent.ExecSessionAttach(context.Background())+ ptySessionFactory = func(sandboxID string, req types.PTYCreateRequest) (*sandbox.PTYSessionHandle, error) {+ agent, err := fcMgr.GetAgent(sandboxID)+ if err != nil {+ return nil, fmt.Errorf("get agent for %s: %w", sandboxID, err)+ }+ vsockPath, err := fcMgr.GetVsockPath(sandboxID)if err != nil {+ return nil, fmt.Errorf("get vsock path for %s: %w", sandboxID, err)+ }+ return createPTYSessionFC(agent, vsockPath, sandboxID, req)+ }++ doGracefulShutdown = func(checkpointStore *storage.CheckpointStore, store *db.Store) {+ if checkpointStore == nil {return}- // Send first message with session_id- if err := stream.Send(&agentpb.ExecSessionInput{SessionId: sessionID}); err != nil {+ vms, _ := mgr.List(context.Background())+ if len(vms) == 0 {return}+ log.Printf("opensandbox-worker: hibernating %d sandboxes...", len(vms))+ shutCtx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)+ results := fcMgr.HibernateAll(shutCtx, checkpointStore)+ cancel()+ processHibernateResults(results, store, func(r interface{}) (string, string, error) {+ hr := r.(fc.HibernateAllResult)+ return hr.SandboxID, hr.HibernationKey, hr.Err+ })+ log.Println("opensandbox-worker: waiting for S3 uploads...")+ fcMgr.WaitUploads(3 * time.Minute)+ log.Println("opensandbox-worker: graceful shutdown complete")+ }- // Forward stdin pipe to gRPC stream in a separate goroutine- go func() {- buf := make([]byte, 4096)- for {- n, err := stdinR.Read(buf)- if err != nil {- return- }- if n > 0 {- data := make([]byte, n)- copy(data, buf[:n])- if err := stream.Send(&agentpb.ExecSessionInput{Stdin: data}); err != nil {- return- }- }- }- }()-- for {- msg, err := stream.Recv()- if err != nil {- return- }- switch msg.Type {- case agentpb.ExecSessionOutput_STDOUT:- scrollback.Write(1, msg.Data)- case agentpb.ExecSessionOutput_STDERR:- scrollback.Write(2, msg.Data)- case agentpb.ExecSessionOutput_EXIT:- exitCode := int(msg.ExitCode)- handle.ExitCode = &exitCode- handle.Running = false- return- case agentpb.ExecSessionOutput_SCROLLBACK_END:- // Transition from scrollback replay to live- }- }+ // Local recovery for Firecracker+ defer func() {+ // Recovery is done below after DB connection}()- return handle, nil- })- defer execMgr.CloseAll()+ // Wire up local recovery+ if dbURL := getDBURL(cfg); dbURL != "" {+ if store, err := db.NewStore(ctx, dbURL); err == nil {+ defer store.Close()+ recoverLocalFC(ctx, fcMgr, store, cfg)+ }+ }- // Initialize PTY manager using Firecracker agent gRPC- ptyMgr := sandbox.NewAgentPTYManager(func(sandboxID string, req types.PTYCreateRequest) (*sandbox.PTYSessionHandle, error) {- agent, err := fcMgr.GetAgent(sandboxID)- if err != nil {- return nil, fmt.Errorf("get agent for %s: %w", sandboxID, err)+ case "qemu":+ qmCfg := qm.Config{+ DataDir: cfg.DataDir,+ KernelPath: cfg.KernelPath,+ ImagesDir: cfg.ImagesDir,+ QEMUBin: cfg.QEMUBin,+ DefaultMemoryMB: cfg.DefaultSandboxMemoryMB,+ DefaultCPUs: cfg.DefaultSandboxCPUs,+ DefaultDiskMB: cfg.DefaultSandboxDiskMB,}- vsockPath, err := fcMgr.GetVsockPath(sandboxID)++ qmMgr, err := qm.NewManager(qmCfg)if err != nil {- return nil, fmt.Errorf("get vsock path for %s: %w", sandboxID, err)+ log.Fatalf("failed to initialize QEMU manager: %v", err)}+ defer qmMgr.Close()+ log.Println("opensandbox-worker: QEMU VM manager initialized")++ qmMgr.CleanupOrphanedProcesses()++ // No golden snapshot for QEMU (cold boot ~2-4s is acceptable)- cols := int32(req.Cols)- if cols <= 0 {- cols = 80+ mgr = qmMgr+ autosaverSyncer = qmMgr++ execSessionFactory = func(sandboxID string, req types.ExecSessionCreateRequest) (*sandbox.ExecSessionHandle, error) {+ agent, err := qmMgr.GetAgent(sandboxID)+ if err != nil {+ return nil, fmt.Errorf("get agent for %s: %w", sandboxID, err)+ }+ return createExecSessionQEMU(agent, sandboxID, req)}- rows := int32(req.Rows)- if rows <= 0 {- rows = 24++ ptySessionFactory = func(sandboxID string, req types.PTYCreateRequest) (*sandbox.PTYSessionHandle, error) {+ agent, err := qmMgr.GetAgent(sandboxID)+ if err != nil {+ return nil, fmt.Errorf("get agent for %s: %w", sandboxID, err)+ }+ guestCID, err := qmMgr.GetGuestCID(sandboxID)+ if err != nil {+ return nil, fmt.Errorf("get guest CID for %s: %w", sandboxID, err)+ }+ return createPTYSessionQEMU(agent, guestCID, sandboxID, req)}- sessionID, dataPort, err := agent.PTYCreate(context.Background(), cols, rows, req.Shell)- if err != nil {- return nil, fmt.Errorf("create PTY in VM: %w", err)+ doGracefulShutdown = func(checkpointStore *storage.CheckpointStore, store *db.Store) {+ if checkpointStore == nil {+ return+ }+ vms, _ := mgr.List(context.Background())+ if len(vms) == 0 {+ return+ }+ log.Printf("opensandbox-worker: hibernating %d sandboxes...", len(vms))+ shutCtx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)+ results := qmMgr.HibernateAll(shutCtx, checkpointStore)+ cancel()+ processHibernateResults(results, store, func(r interface{}) (string, string, error) {+ hr := r.(qm.HibernateAllResult)+ return hr.SandboxID, hr.HibernationKey, hr.Err+ })+ log.Println("opensandbox-worker: waiting for S3 uploads...")+ qmMgr.WaitUploads(3 * time.Minute)+ log.Println("opensandbox-worker: graceful shutdown complete")}- // Connect to the PTY data stream via vsock- conn, err := agent.ConnectPTYData(vsockPath, dataPort)- if err != nil {- _ = agent.PTYKill(context.Background(), sessionID)- return nil, fmt.Errorf("connect PTY data: %w", err)+ // Wire up local recovery+ if dbURL := getDBURL(cfg); dbURL != "" {+ if store, err := db.NewStore(ctx, dbURL); err == nil {+ defer store.Close()+ recoverLocalQEMU(ctx, qmMgr, store, cfg)+ }}- done := make(chan struct{})+ default:+ log.Fatalf("unknown VM backend %q (expected 'firecracker' or 'qemu')", cfg.VMBackend)+ }- return &sandbox.PTYSessionHandle{- ID: sessionID,- SandboxID: sandboxID,- PTY: conn,- Done: done,- }, nil- })+ // Initialize exec session manager+ execMgr := sandbox.NewAgentExecSessionManager(execSessionFactory)+ defer execMgr.CloseAll()++ // Initialize PTY manager+ ptyMgr := sandbox.NewAgentPTYManager(ptySessionFactory)defer ptyMgr.CloseAll()// Initialize per-sandbox SQLite managersandboxDBMgr := sandbox.NewSandboxDBManager(cfg.DataDir)defer sandboxDBMgr.Close()- // JWT issuer for validating sandbox tokens+ // JWT issuerif cfg.JWTSecret == "" {log.Fatalf("OPENSANDBOX_JWT_SECRET is required for worker mode")}jwtIssuer := auth.NewJWTIssuer(cfg.JWTSecret)- // Initialize S3 checkpoint store for hibernation (if configured)+ // S3 checkpoint storevar checkpointStore *storage.CheckpointStoreif cfg.S3Bucket != "" {var err error@@ -236,7 +243,6 @@ func main() {}log.Printf("opensandbox-worker: S3 checkpoint store configured (bucket=%s, region=%s)", cfg.S3Bucket, cfg.S3Region)- // Enable local NVMe checkpoint cache if data dir is configuredif cfg.DataDir != "" {cacheDir := filepath.Join(cfg.DataDir, "checkpoints")if err := checkpointStore.SetCacheDir(cacheDir); err != nil {@@ -245,12 +251,9 @@ func main() {}}- // Initialize PostgreSQL store for checkpoint lookups (auto-wake)+ // PostgreSQL storevar store *db.Store- dbURL := cfg.DatabaseURL- if dbURL == "" {- dbURL = os.Getenv("DATABASE_URL")- }+ dbURL := getDBURL(cfg)if dbURL != "" {var err errorstore, err = db.NewStore(ctx, dbURL)@@ -260,36 +263,6 @@ func main() {defer store.Close()log.Println("opensandbox-worker: PostgreSQL store connected (auto-wake enabled)")- // Local NVMe recovery: scan for sandbox data left from a previous run- recoveries := fcMgr.RecoverLocalSandboxes()- if len(recoveries) > 0 {- snapshotCount, workspaceCount := 0, 0- for _, r := range recoveries {- session, err := store.GetSandboxSession(ctx, r.SandboxID)- if err != nil {- log.Printf("opensandbox-worker: no DB session for %s, skipping recovery", r.SandboxID)- continue- }- if r.HasSnapshot {- // Full snapshot on NVMe — create hibernation record so doWake finds local files- _, _ = store.CreateHibernation(ctx, r.SandboxID, session.OrgID,- "local://"+r.SandboxID, 0, session.Region, session.Template, session.Config)- _ = store.UpdateSandboxSessionStatus(ctx, r.SandboxID, "hibernated", nil)- snapshotCount++- } else {- // Workspace only — create local sentinel hibernation for cold boot- _, _ = store.CreateHibernation(ctx, r.SandboxID, session.OrgID,- "local://"+r.SandboxID, 0, session.Region, session.Template, session.Config)- _ = store.UpdateSandboxSessionStatus(ctx, r.SandboxID, "hibernated", nil)- workspaceCount++- }- }- if snapshotCount+workspaceCount > 0 {- log.Printf("opensandbox-worker: local recovery: %d with snapshot, %d workspace-only", snapshotCount, workspaceCount)- }- }-- // Mark any remaining stale "running" sessions (no local data) as stopped_, stopped, err := store.ReconcileWorkerSessions(ctx, cfg.WorkerID)if err != nil {log.Printf("opensandbox-worker: warning: session reconciliation failed: %v", err)@@ -299,7 +272,7 @@ func main() {}}- // Initialize SandboxRouter for rolling timeouts, auto-wake, and command routing+ // Sandbox routersbRouter := sandbox.NewSandboxRouter(sandbox.RouterConfig{Manager: mgr,CheckpointStore: checkpointStore,@@ -310,7 +283,6 @@ func main() {sandboxID, result.HibernationKey, result.SizeBytes)execMgr.RemoveSessions(sandboxID)if store != nil {- // Create hibernation record so wake-on-request can find itsession, err := store.GetSandboxSession(context.Background(), sandboxID)if err == nil {_, _ = store.CreateHibernation(context.Background(), sandboxID, session.OrgID,@@ -330,12 +302,12 @@ func main() {defer sbRouter.Close()log.Println("opensandbox-worker: sandbox router initialized (rolling timeouts, auto-wake)")- // Start Prometheus metrics server on :9091+ // MetricsmetricsSrv := metrics.StartMetricsServer(":9091")defer metricsSrv.Close()log.Println("opensandbox-worker: metrics server started on :9091")- // Start gRPC server for control plane communication+ // gRPC servergrpcServer := worker.NewGRPCServer(mgr, ptyMgr, execMgr, sandboxDBMgr, checkpointStore, sbRouter, store)grpcAddr := ":9090"log.Printf("opensandbox-worker: starting gRPC server on %s", grpcAddr)@@ -345,14 +317,14 @@ func main() {}}()- // Initialize subdomain reverse proxy+ // Subdomain proxyvar sbProxy *proxy.SandboxProxyif cfg.SandboxDomain != "" {sbProxy = proxy.New(cfg.SandboxDomain, mgr, sbRouter)log.Printf("opensandbox-worker: subdomain proxy configured (*.%s)", cfg.SandboxDomain)}- // Start HTTP server for direct SDK access+ // HTTP serverhttpServer := worker.NewHTTPServer(mgr, ptyMgr, execMgr, jwtIssuer, sandboxDBMgr, sbProxy, sbRouter, cfg.SandboxDomain)httpAddr := fmt.Sprintf(":%d", cfg.Port)log.Printf("opensandbox-worker: starting HTTP server on %s", httpAddr)@@ -362,7 +334,7 @@ func main() {}}()- // Start Redis heartbeat for control plane discovery+ // Redis heartbeatif cfg.RedisURL != "" {grpcAdvertise := grpcAddrif addr := os.Getenv("OPENSANDBOX_GRPC_ADVERTISE"); addr != "" {@@ -375,7 +347,7 @@ func main() {} else {if machineID := worker.GetEC2InstanceID(); machineID != "" {hb.SetMachineID(machineID)- log.Printf("opensandbox-worker: EC2 instance ID: %s", machineID)+ log.Printf("opensandbox-worker: instance ID: %s", machineID)}hb.Start(func() (int, int, float64, float64) {count, _ := mgr.Count(context.Background())@@ -387,7 +359,7 @@ func main() {}}- // Start NATS event publisher if configured+ // NATSif cfg.NATSURL != "" {pub, err := worker.NewEventPublisher(cfg.NATSURL, cfg.Region, cfg.WorkerID, sandboxDBMgr)if err != nil {@@ -404,8 +376,8 @@ func main() {}}- // Start periodic SyncFS to keep workspace.ext4 crash-consistent on NVMe- autosaver := worker.NewWorkspaceAutosaver(mgr, fcMgr, 5*time.Minute)+ // Periodic SyncFS+ autosaver := worker.NewWorkspaceAutosaver(mgr, autosaverSyncer, 5*time.Minute)autosaver.Start()quit := make(chan os.Signal, 1)@@ -414,48 +386,337 @@ func main() {log.Println("opensandbox-worker: graceful shutdown starting...")- // 1. Stop accepting new workgrpcServer.Stop()if err := httpServer.Close(); err != nil {log.Printf("error closing HTTP server: %v", err)}- // Stop autosaver before hibernatingautosaver.Stop()- // 2. Hibernate all running sandboxes for seamless resume- if checkpointStore != nil {- vms, _ := mgr.List(context.Background())- if len(vms) > 0 {- log.Printf("opensandbox-worker: hibernating %d sandboxes...", len(vms))- shutCtx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)- results := fcMgr.HibernateAll(shutCtx, checkpointStore)- cancel()+ doGracefulShutdown(checkpointStore, store)+}++// getDBURL returns the database URL from config or environment.+func getDBURL(cfg *config.Config) string {+ if cfg.DatabaseURL != "" {+ return cfg.DatabaseURL+ }+ return os.Getenv("DATABASE_URL")+}++// createExecSession creates an exec session using a Firecracker agent client.+func createExecSession(agent *fc.AgentClient, sandboxID string, req types.ExecSessionCreateRequest) (*sandbox.ExecSessionHandle, error) {+ agentPB := &agentpb.ExecSessionCreateRequest{+ Command: req.Command,+ Args: req.Args,+ Envs: req.Env,+ Cwd: req.Cwd,+ TimeoutSeconds: int32(req.Timeout),+ MaxRunAfterDisconnect: int32(req.MaxRunAfterDisconnect),+ }++ sessionID, err := agent.ExecSessionCreate(context.Background(), agentPB)+ if err != nil {+ return nil, fmt.Errorf("create exec session in VM: %w", err)+ }++ scrollback := sandbox.NewScrollbackBuffer(0)+ done := make(chan struct{})+ stdinR, stdinW := io.Pipe()++ handle := &sandbox.ExecSessionHandle{+ ID: sessionID,+ SandboxID: sandboxID,+ Command: req.Command,+ Args: req.Args,+ Running: true,+ StartedAt: time.Now(),+ Done: done,+ Scrollback: scrollback,+ StdinWriter: stdinW,+ OnKill: func(signal int) error {+ stdinW.Close()+ return agent.ExecSessionKill(context.Background(), sessionID, int32(signal))+ },+ }- for _, r := range results {- if r.Err != nil {- log.Printf("opensandbox-worker: hibernate failed for %s: %v", r.SandboxID, r.Err)- if store != nil {- errMsg := "hibernate failed on shutdown: " + r.Err.Error()- _ = store.UpdateSandboxSessionStatus(context.Background(), r.SandboxID, "stopped", &errMsg)- }- continue+ go runExecStream(agent, sessionID, stdinR, done, scrollback, handle)++ return handle, nil+}++// createExecSessionQEMU creates an exec session using a QEMU agent client.+func createExecSessionQEMU(agent *qm.AgentClient, sandboxID string, req types.ExecSessionCreateRequest) (*sandbox.ExecSessionHandle, error) {+ agentPB := &agentpb.ExecSessionCreateRequest{+ Command: req.Command,+ Args: req.Args,+ Envs: req.Env,+ Cwd: req.Cwd,+ TimeoutSeconds: int32(req.Timeout),+ MaxRunAfterDisconnect: int32(req.MaxRunAfterDisconnect),+ }++ sessionID, err := agent.ExecSessionCreate(context.Background(), agentPB)+ if err != nil {+ return nil, fmt.Errorf("create exec session in VM: %w", err)+ }++ scrollback := sandbox.NewScrollbackBuffer(0)+ done := make(chan struct{})+ stdinR, stdinW := io.Pipe()++ handle := &sandbox.ExecSessionHandle{+ ID: sessionID,+ SandboxID: sandboxID,+ Command: req.Command,+ Args: req.Args,+ Running: true,+ StartedAt: time.Now(),+ Done: done,+ Scrollback: scrollback,+ StdinWriter: stdinW,+ OnKill: func(signal int) error {+ stdinW.Close()+ return agent.ExecSessionKill(context.Background(), sessionID, int32(signal))+ },+ }++ go runExecStreamQEMU(agent, sessionID, stdinR, done, scrollback, handle)++ return handle, nil+}++// runExecStream attaches to an exec session stream (Firecracker backend).+func runExecStream(agent *fc.AgentClient, sessionID string, stdinR *io.PipeReader, done chan struct{}, scrollback *sandbox.ScrollbackBuffer, handle *sandbox.ExecSessionHandle) {+ defer close(done)+ defer stdinR.Close()+ stream, err := agent.ExecSessionAttach(context.Background())+ if err != nil {+ return+ }+ if err := stream.Send(&agentpb.ExecSessionInput{SessionId: sessionID}); err != nil {+ return+ }+ go forwardStdin(stdinR, stream)+ consumeExecOutput(stream, scrollback, handle)+}++// runExecStreamQEMU attaches to an exec session stream (QEMU backend).+func runExecStreamQEMU(agent *qm.AgentClient, sessionID string, stdinR *io.PipeReader, done chan struct{}, scrollback *sandbox.ScrollbackBuffer, handle *sandbox.ExecSessionHandle) {+ defer close(done)+ defer stdinR.Close()+ stream, err := agent.ExecSessionAttach(context.Background())+ if err != nil {+ return+ }+ if err := stream.Send(&agentpb.ExecSessionInput{SessionId: sessionID}); err != nil {+ return+ }+ go forwardStdin(stdinR, stream)+ consumeExecOutput(stream, scrollback, handle)+}++// forwardStdin pipes stdin data to a gRPC stream.+func forwardStdin(stdinR *io.PipeReader, stream agentpb.SandboxAgent_ExecSessionAttachClient) {+ buf := make([]byte, 4096)+ for {+ n, err := stdinR.Read(buf)+ if err != nil {+ return+ }+ if n > 0 {+ data := make([]byte, n)+ copy(data, buf[:n])+ if err := stream.Send(&agentpb.ExecSessionInput{Stdin: data}); err != nil {+ return+ }+ }+ }+}++// consumeExecOutput reads output from a gRPC exec stream into a scrollback buffer.+func consumeExecOutput(stream agentpb.SandboxAgent_ExecSessionAttachClient, scrollback *sandbox.ScrollbackBuffer, handle *sandbox.ExecSessionHandle) {+ for {+ msg, err := stream.Recv()+ if err != nil {+ return+ }+ switch msg.Type {+ case agentpb.ExecSessionOutput_STDOUT:+ scrollback.Write(1, msg.Data)+ case agentpb.ExecSessionOutput_STDERR:+ scrollback.Write(2, msg.Data)+ case agentpb.ExecSessionOutput_EXIT:+ exitCode := int(msg.ExitCode)+ handle.ExitCode = &exitCode+ handle.Running = false+ return+ case agentpb.ExecSessionOutput_SCROLLBACK_END:+ // Transition from scrollback replay to live+ }+ }+}++// createPTYSessionFC creates a PTY session using Firecracker's vsock UDS protocol.+func createPTYSessionFC(agent *fc.AgentClient, vsockPath, sandboxID string, req types.PTYCreateRequest) (*sandbox.PTYSessionHandle, error) {+ cols := int32(req.Cols)+ if cols <= 0 {+ cols = 80+ }+ rows := int32(req.Rows)+ if rows <= 0 {+ rows = 24+ }++ sessionID, dataPort, err := agent.PTYCreate(context.Background(), cols, rows, req.Shell)+ if err != nil {+ return nil, fmt.Errorf("create PTY in VM: %w", err)+ }++ conn, err := agent.ConnectPTYData(vsockPath, dataPort)+ if err != nil {+ _ = agent.PTYKill(context.Background(), sessionID)+ return nil, fmt.Errorf("connect PTY data: %w", err)+ }++ done := make(chan struct{})+ return &sandbox.PTYSessionHandle{+ ID: sessionID,+ SandboxID: sandboxID,+ PTY: conn,+ Done: done,+ }, nil+}++// createPTYSessionQEMU creates a PTY session using AF_VSOCK (QEMU backend).+func createPTYSessionQEMU(agent *qm.AgentClient, guestCID uint32, sandboxID string, req types.PTYCreateRequest) (*sandbox.PTYSessionHandle, error) {+ cols := int32(req.Cols)+ if cols <= 0 {+ cols = 80+ }+ rows := int32(req.Rows)+ if rows <= 0 {+ rows = 24+ }++ sessionID, dataPort, err := agent.PTYCreate(context.Background(), cols, rows, req.Shell)+ if err != nil {+ return nil, fmt.Errorf("create PTY in VM: %w", err)+ }++ conn, err := agent.ConnectPTYData(guestCID, dataPort)+ if err != nil {+ _ = agent.PTYKill(context.Background(), sessionID)+ return nil, fmt.Errorf("connect PTY data: %w", err)+ }++ done := make(chan struct{})+ return &sandbox.PTYSessionHandle{+ ID: sessionID,+ SandboxID: sandboxID,+ PTY: conn,+ Done: done,+ }, nil+}++// processHibernateResults handles results from HibernateAll for both backends.+func processHibernateResults(results interface{}, store *db.Store, extract func(interface{}) (string, string, error)) {+ // This is intentionally generic — each backend calls it with its own result type+ switch rs := results.(type) {+ case []fc.HibernateAllResult:+ for _, r := range rs {+ if r.Err != nil {+ log.Printf("opensandbox-worker: hibernate failed for %s: %v", r.SandboxID, r.Err)+ if store != nil {+ errMsg := "hibernate failed on shutdown: " + r.Err.Error()+ _ = store.UpdateSandboxSessionStatus(context.Background(), r.SandboxID, "stopped", &errMsg)}- log.Printf("opensandbox-worker: hibernated %s (key=%s)", r.SandboxID, r.HibernationKey)+ continue+ }+ log.Printf("opensandbox-worker: hibernated %s (key=%s)", r.SandboxID, r.HibernationKey)+ if store != nil {+ session, err := store.GetSandboxSession(context.Background(), r.SandboxID)+ if err == nil {+ _, _ = store.CreateHibernation(context.Background(), r.SandboxID, session.OrgID,+ r.HibernationKey, 0, session.Region, session.Template, session.Config)+ _ = store.UpdateSandboxSessionStatus(context.Background(), r.SandboxID, "hibernated", nil)+ }+ }+ }+ case []qm.HibernateAllResult:+ for _, r := range rs {+ if r.Err != nil {+ log.Printf("opensandbox-worker: hibernate failed for %s: %v", r.SandboxID, r.Err)if store != nil {- session, err := store.GetSandboxSession(context.Background(), r.SandboxID)- if err == nil {- _, _ = store.CreateHibernation(context.Background(), r.SandboxID, session.OrgID,- r.HibernationKey, 0, session.Region, session.Template, session.Config)- _ = store.UpdateSandboxSessionStatus(context.Background(), r.SandboxID, "hibernated", nil)- }+ errMsg := "hibernate failed on shutdown: " + r.Err.Error()+ _ = store.UpdateSandboxSessionStatus(context.Background(), r.SandboxID, "stopped", &errMsg)+ }+ continue+ }+ log.Printf("opensandbox-worker: hibernated %s (key=%s)", r.SandboxID, r.HibernationKey)+ if store != nil {+ session, err := store.GetSandboxSession(context.Background(), r.SandboxID)+ if err == nil {+ _, _ = store.CreateHibernation(context.Background(), r.SandboxID, session.OrgID,+ r.HibernationKey, 0, session.Region, session.Template, session.Config)+ _ = store.UpdateSandboxSessionStatus(context.Background(), r.SandboxID, "hibernated", nil)}}+ }+ }+}- // 3. Wait for async S3 uploads to complete- log.Println("opensandbox-worker: waiting for S3 uploads...")- fcMgr.WaitUploads(3 * time.Minute)- log.Println("opensandbox-worker: graceful shutdown complete")+// recoverLocalFC handles local NVMe recovery for Firecracker backend.+func recoverLocalFC(ctx context.Context, fcMgr *fc.Manager, store *db.Store, cfg *config.Config) {+ recoveries := fcMgr.RecoverLocalSandboxes()+ if len(recoveries) == 0 {+ return+ }+ snapshotCount, workspaceCount := 0, 0+ for _, r := range recoveries {+ session, err := store.GetSandboxSession(ctx, r.SandboxID)+ if err != nil {+ log.Printf("opensandbox-worker: no DB session for %s, skipping recovery", r.SandboxID)+ continue+ }+ _, _ = store.CreateHibernation(ctx, r.SandboxID, session.OrgID,+ "local://"+r.SandboxID, 0, session.Region, session.Template, session.Config)+ _ = store.UpdateSandboxSessionStatus(ctx, r.SandboxID, "hibernated", nil)+ if r.HasSnapshot {+ snapshotCount+++ } else {+ workspaceCount++}}+ if snapshotCount+workspaceCount > 0 {+ log.Printf("opensandbox-worker: local recovery: %d with snapshot, %d workspace-only", snapshotCount, workspaceCount)+ }}++// recoverLocalQEMU handles local disk recovery for QEMU backend.+func recoverLocalQEMU(ctx context.Context, qmMgr *qm.Manager, store *db.Store, cfg *config.Config) {+ recoveries := qmMgr.RecoverLocalSandboxes()+ if len(recoveries) == 0 {+ return+ }+ snapshotCount, workspaceCount := 0, 0+ for _, r := range recoveries {+ session, err := store.GetSandboxSession(ctx, r.SandboxID)+ if err != nil {+ log.Printf("opensandbox-worker: no DB session for %s, skipping recovery", r.SandboxID)+ continue+ }+ _, _ = store.CreateHibernation(ctx, r.SandboxID, session.OrgID,+ "local://"+r.SandboxID, 0, session.Region, session.Template, session.Config)+ _ = store.UpdateSandboxSessionStatus(ctx, r.SandboxID, "hibernated", nil)+ if r.HasSnapshot {+ snapshotCount+++ } else {+ workspaceCount+++ }+ }+ if snapshotCount+workspaceCount > 0 {+ log.Printf("opensandbox-worker: local recovery: %d with snapshot, %d workspace-only", snapshotCount, workspaceCount)+ }+}+diff --git a/deploy/azure/deploy-azure-dev.sh b/deploy/azure/deploy-azure-dev.shnew file mode 100755index 00000000..7caba2fc--- /dev/null+++ b/deploy/azure/deploy-azure-dev.sh@@ -0,0 +1,348 @@+#!/usr/bin/env bash+# deploy-azure-dev.sh — Quick dev deployment on Azure D96as_v5 with QEMU backend.+# Usage: ./deploy-azure-dev.sh [create|deploy|ssh|status|destroy]+set -euo pipefail++SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"++# --- Defaults ---+AZURE_LOCATION="${AZURE_LOCATION:-eastus}"+AZURE_VM_SIZE="${AZURE_VM_SIZE:-Standard_D96as_v5}"+AZURE_RG="${AZURE_RG:-opensandbox-dev}"+AZURE_VM_NAME="${AZURE_VM_NAME:-opensandbox-dev}"+AZURE_IMAGE="${AZURE_IMAGE:-Canonical:ubuntu-24_04-lts:server:latest}"+AZURE_ADMIN_USER="${AZURE_ADMIN_USER:-ubuntu}"+AZURE_DATA_DISK_GB="${AZURE_DATA_DISK_GB:-500}"+OPENSANDBOX_API_KEY="${OPENSANDBOX_API_KEY:-opensandbox-dev}"+SSH_KEY_PATH="${SSH_KEY_PATH:-$HOME/.ssh/id_rsa}"++STATE_DIR="$SCRIPT_DIR"+STATE_FILE="$STATE_DIR/.dev-env-state-${AZURE_LOCATION}"++# --- Helpers ---+log() { echo "$(date '+%H:%M:%S') [azure-dev] $*"; }++save_state() { echo "$1=$2" >> "$STATE_FILE"; }+load_state() {+ if [ -f "$STATE_FILE" ]; then+ # shellcheck disable=SC1090+ source "$STATE_FILE"+ fi+}++ssh_cmd() {+ load_state+ ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null \+ -i "$SSH_KEY_PATH" "${AZURE_ADMIN_USER}@${VM_PUBLIC_IP}" "$@"+}++# --- Create ---+cmd_create() {+ log "Creating Azure dev environment in $AZURE_LOCATION..."++ # Clean state+ rm -f "$STATE_FILE"++ # Create resource group+ log "Creating resource group $AZURE_RG..."+ az group create --name "$AZURE_RG" --location "$AZURE_LOCATION" --output none+ save_state "RESOURCE_GROUP" "$AZURE_RG"++ # Create VM with public IP and data disk+ log "Creating VM $AZURE_VM_NAME ($AZURE_VM_SIZE)..."+ VM_INFO=$(az vm create \+ --resource-group "$AZURE_RG" \+ --name "$AZURE_VM_NAME" \+ --image "$AZURE_IMAGE" \+ --size "$AZURE_VM_SIZE" \+ --admin-username "$AZURE_ADMIN_USER" \+ --ssh-key-values "${SSH_KEY_PATH}.pub" \+ --os-disk-size-gb 100 \+ --data-disk-sizes-gb "$AZURE_DATA_DISK_GB" \+ --security-type Standard \+ --public-ip-sku Standard \+ --output json)++ VM_PUBLIC_IP=$(echo "$VM_INFO" | jq -r '.publicIpAddress')+ save_state "VM_PUBLIC_IP" "$VM_PUBLIC_IP"+ save_state "VM_NAME" "$AZURE_VM_NAME"+ log "VM created with public IP: $VM_PUBLIC_IP"++ # Open ports: SSH (22), API (8080), Worker SDK (8081)+ # SSH port is already opened by az vm create. Open API and worker ports.+ log "Opening ports 8080, 8081..."+ az vm open-port --resource-group "$AZURE_RG" --name "$AZURE_VM_NAME" \+ --port 8080,8081 --priority 1001 --output none++ # Wait for SSH+ log "Waiting for SSH readiness..."+ for i in $(seq 1 60); do+ if ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null \+ -o ConnectTimeout=5 -i "$SSH_KEY_PATH" \+ "${AZURE_ADMIN_USER}@${VM_PUBLIC_IP}" "echo ready" 2>/dev/null; then+ break+ fi+ sleep 5+ done++ # Format and mount data disk+ log "Setting up data disk..."+ ssh_cmd << 'SETUP_DISK'+set -euo pipefail+# Find the unformatted data disk (typically /dev/sdc on Azure)+DATA_DISK=""+for disk in /dev/sd{c,d,e}; do+ if [ -b "$disk" ] && ! blkid "$disk" > /dev/null 2>&1; then+ DATA_DISK="$disk"+ break+ fi+done+if [ -z "$DATA_DISK" ]; then+ # Try partitioned disk+ for disk in /dev/sd{c,d,e}1; do+ if [ -b "$disk" ] && ! blkid "$disk" > /dev/null 2>&1; then+ DATA_DISK="$disk"+ break+ fi+ done+fi+if [ -z "$DATA_DISK" ]; then+ echo "WARNING: No unformatted data disk found, using root volume"+ sudo mkdir -p /data+ exit 0+fi+echo "Formatting $DATA_DISK as ext4..."+sudo mkfs.ext4 -L opensandbox-data "$DATA_DISK"+sudo mkdir -p /data+echo "LABEL=opensandbox-data /data ext4 defaults,nofail 0 2" | sudo tee -a /etc/fstab+sudo mount /data+sudo mkdir -p /data/sandboxes /data/firecracker/images /data/checkpoints+SETUP_DISK++ # Sync code and run setup+ log "Syncing codebase..."+ rsync -az --progress \+ --exclude '.git' --exclude 'bin/' --exclude 'node_modules/' \+ --exclude '.dev-env-state*' --exclude '*.ext4' --exclude 'vendor/' \+ "$REPO_ROOT/" "${AZURE_ADMIN_USER}@${VM_PUBLIC_IP}:~/opensandbox/"++ log "Running host setup..."+ ssh_cmd "cd ~/opensandbox && sudo bash deploy/azure/setup-azure-host.sh"++ log "=== Azure dev environment created ==="+ log " VM: $AZURE_VM_NAME ($AZURE_VM_SIZE)"+ log " IP: $VM_PUBLIC_IP"+ log " SSH: ./deploy/azure/deploy-azure-dev.sh ssh"+ log " Deploy: ./deploy/azure/deploy-azure-dev.sh deploy"+ log ""+ log "Next: run './deploy/azure/deploy-azure-dev.sh deploy' to build and start services"+}++# --- Deploy ---+cmd_deploy() {+ load_state+ if [ -z "${VM_PUBLIC_IP:-}" ]; then+ log "ERROR: No VM found. Run 'create' first."+ exit 1+ fi++ log "Deploying to $VM_PUBLIC_IP..."++ # Sync code+ log "Syncing code..."+ rsync -az --progress \+ --exclude '.git' --exclude 'bin/' --exclude 'node_modules/' \+ --exclude '.dev-env-state*' --exclude '*.ext4' --exclude 'vendor/' \+ "$REPO_ROOT/" "${AZURE_ADMIN_USER}@${VM_PUBLIC_IP}:~/opensandbox/"++ # Build binaries on instance+ log "Building binaries..."+ ssh_cmd << 'BUILD'+set -euo pipefail+export PATH="/usr/local/go/bin:$HOME/go/bin:$PATH"+cd ~/opensandbox++echo "Building server..."+CGO_ENABLED=0 go build -o bin/opensandbox-server ./cmd/server/+echo "Building worker..."+CGO_ENABLED=0 go build -o bin/opensandbox-worker ./cmd/worker/+echo "Building agent..."+CGO_ENABLED=0 GOARCH=amd64 go build -o bin/osb-agent ./cmd/agent/++sudo cp bin/opensandbox-server /usr/local/bin/+sudo cp bin/opensandbox-worker /usr/local/bin/+sudo cp bin/osb-agent /usr/local/bin/+echo "Binaries installed."+BUILD++ # Build rootfs if needed+ ssh_cmd << 'ROOTFS'+set -euo pipefail+if [ ! -f /data/firecracker/images/default.ext4 ]; then+ echo "Building rootfs image..."+ cd ~/opensandbox+ export PATH="/usr/local/go/bin:$HOME/go/bin:$PATH"+ sudo bash deploy/ec2/build-rootfs-docker.sh+else+ echo "Rootfs image already exists."+fi+ROOTFS++ # Setup env files+ SANDBOX_DOMAIN="${VM_PUBLIC_IP}.nip.io"+ ssh_cmd << ENVSETUP+set -euo pipefail+# Worker env+sudo tee /etc/opensandbox/worker.env > /dev/null << EOF+OPENSANDBOX_MODE=worker+OPENSANDBOX_DATA_DIR=/data/sandboxes+OPENSANDBOX_KERNEL_PATH=/opt/opensandbox/vmlinux+OPENSANDBOX_IMAGES_DIR=/data/firecracker/images+OPENSANDBOX_VM_BACKEND=qemu+OPENSANDBOX_QEMU_BIN=qemu-system-x86_64+OPENSANDBOX_JWT_SECRET=dev-jwt-secret-change-me+OPENSANDBOX_WORKER_ID=w-azure-1+OPENSANDBOX_REGION=azure-${AZURE_LOCATION}+OPENSANDBOX_DATABASE_URL=postgres://opensandbox:opensandbox@localhost:5432/opensandbox?sslmode=disable+OPENSANDBOX_REDIS_URL=redis://localhost:6379+OPENSANDBOX_SANDBOX_DOMAIN=${SANDBOX_DOMAIN}+OPENSANDBOX_HTTP_ADDR=http://${VM_PUBLIC_IP}:8081+OPENSANDBOX_NATS_URL=+OPENSANDBOX_PORT=8081+OPENSANDBOX_DEFAULT_SANDBOX_MEMORY_MB=1024+OPENSANDBOX_DEFAULT_SANDBOX_CPUS=2+EOF++# Server env+sudo tee /etc/opensandbox/server.env > /dev/null << EOF+OPENSANDBOX_MODE=server+OPENSANDBOX_DATABASE_URL=postgres://opensandbox:opensandbox@localhost:5432/opensandbox?sslmode=disable+OPENSANDBOX_JWT_SECRET=dev-jwt-secret-change-me+OPENSANDBOX_API_KEY=\$(echo -n "${OPENSANDBOX_API_KEY}" | sha256sum | cut -d' ' -f1)+OPENSANDBOX_REDIS_URL=redis://localhost:6379+OPENSANDBOX_SANDBOX_DOMAIN=${SANDBOX_DOMAIN}+OPENSANDBOX_PORT=8080+OPENSANDBOX_REGION=azure-${AZURE_LOCATION}+EOF+ENVSETUP++ # Restart services+ ssh_cmd << 'RESTART'+set -euo pipefail+# Ensure iptables rules for VM networking+sudo iptables -t nat -C POSTROUTING -s 172.16.0.0/16 -o $(ip route show default | awk '/default/ {print $5}') -j MASQUERADE 2>/dev/null || \+ sudo iptables -t nat -A POSTROUTING -s 172.16.0.0/16 -o $(ip route show default | awk '/default/ {print $5}') -j MASQUERADE+sudo iptables -C FORWARD -s 172.16.0.0/16 -j ACCEPT 2>/dev/null || \+ sudo iptables -I FORWARD -s 172.16.0.0/16 -j ACCEPT+sudo iptables -C FORWARD -d 172.16.0.0/16 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT 2>/dev/null || \+ sudo iptables -I FORWARD -d 172.16.0.0/16 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT+sudo sysctl -w net.ipv4.ip_forward=1 > /dev/null+sudo sysctl -w net.ipv4.conf.all.route_localnet=1 > /dev/null++sudo systemctl daemon-reload+sudo systemctl restart opensandbox-server || true+sleep 2+sudo systemctl restart opensandbox-worker || true+RESTART++ # Wait for server to be ready and run migrations+ log "Waiting for server..."+ for i in $(seq 1 30); do+ if ssh_cmd "curl -sf http://localhost:8080/health" 2>/dev/null; then+ break+ fi+ sleep 2+ done++ # Seed database+ ssh_cmd << SEED+set -euo pipefail+export PGPASSWORD=opensandbox+# Create org and API key if not exists+psql -h localhost -U opensandbox -d opensandbox -c "+ INSERT INTO organizations (id, name, slug) VALUES ('org-dev', 'Dev Org', 'dev')+ ON CONFLICT DO NOTHING;+ INSERT INTO api_keys (id, org_id, key_hash, name)+ VALUES ('key-dev', 'org-dev', '$(echo -n "${OPENSANDBOX_API_KEY}" | sha256sum | cut -d' ' -f1)', 'dev-key')+ ON CONFLICT DO NOTHING;+" 2>/dev/null || echo "DB seed skipped (tables may not exist yet)"+SEED++ log "=== Deployment complete ==="+ log " Server: http://${VM_PUBLIC_IP}:8080"+ log " Worker: http://${VM_PUBLIC_IP}:8081"+ log " API key: ${OPENSANDBOX_API_KEY}"+ log ""+ log "Test: curl -X POST http://${VM_PUBLIC_IP}:8080/api/sandboxes -H 'Authorization: Bearer ${OPENSANDBOX_API_KEY}'"+}++# --- SSH ---+cmd_ssh() {+ load_state+ if [ -z "${VM_PUBLIC_IP:-}" ]; then+ log "ERROR: No VM found. Run 'create' first."+ exit 1+ fi+ ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null \+ -i "$SSH_KEY_PATH" "${AZURE_ADMIN_USER}@${VM_PUBLIC_IP}"+}++# --- Status ---+cmd_status() {+ load_state+ if [ -z "${VM_PUBLIC_IP:-}" ]; then+ log "No dev environment found."+ exit 0+ fi+ log "VM: $AZURE_VM_NAME IP: $VM_PUBLIC_IP"+ az vm show --resource-group "$AZURE_RG" --name "$AZURE_VM_NAME" \+ --show-details --query "{Status:powerState, Location:location, Size:hardwareProfile.vmSize}" \+ --output table 2>/dev/null || log "VM not found"+}++# --- Destroy ---+cmd_destroy() {+ load_state+ if [ -z "${RESOURCE_GROUP:-}" ]; then+ log "No dev environment to destroy."+ exit 0+ fi++ log "WARNING: This will destroy ALL resources in resource group $RESOURCE_GROUP"+ read -p "Continue? (y/N) " confirm+ if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then+ log "Aborted."+ exit 0+ fi++ log "Deleting resource group $RESOURCE_GROUP..."+ az group delete --name "$RESOURCE_GROUP" --yes --no-wait+ rm -f "$STATE_FILE"+ log "Resource group deletion initiated (async). Resources will be cleaned up shortly."+}++# --- Main ---+CMD="${1:-help}"+case "$CMD" in+ create) cmd_create ;;+ deploy) cmd_deploy ;;+ ssh) cmd_ssh ;;+ status) cmd_status ;;+ destroy) cmd_destroy ;;+ *)+ echo "Usage: $0 {create|deploy|ssh|status|destroy}"+ echo ""+ echo "Commands:"+ echo " create Create Azure VM and infrastructure"+ echo " deploy Build and deploy code to VM"+ echo " ssh SSH into the VM"+ echo " status Show VM status"+ echo " destroy Delete all Azure resources"+ echo ""+ echo "Environment variables:"+ echo " AZURE_LOCATION Azure region (default: eastus)"+ echo " AZURE_VM_SIZE VM size (default: Standard_D96as_v5)"+ echo " AZURE_DATA_DISK_GB Data disk size (default: 500)"+ ;;+esacdiff --git a/deploy/azure/setup-azure-host.sh b/deploy/azure/setup-azure-host.shnew file mode 100755index 00000000..713fbd02--- /dev/null+++ b/deploy/azure/setup-azure-host.sh@@ -0,0 +1,194 @@+#!/usr/bin/env bash+# setup-azure-host.sh — Provision an Azure VM for OpenSandbox with QEMU backend.+# Run as root on a fresh Ubuntu 24.04 x86_64 instance.+set -euo pipefail++echo "=== OpenSandbox Azure Host Setup ==="++# Architecture detection+ARCH=$(uname -m)+case "$ARCH" in+ x86_64) GOARCH="amd64"; KERNEL_ARCH="x86_64" ;;+ aarch64) GOARCH="arm64"; KERNEL_ARCH="aarch64" ;;+ *) echo "Unsupported architecture: $ARCH"; exit 1 ;;+esac+echo "Architecture: $ARCH (Go: $GOARCH)"++# --- System packages ---+echo "Installing system packages..."+export DEBIAN_FRONTEND=noninteractive+apt-get update -qq+apt-get upgrade -y -qq+apt-get install -y -qq \+ qemu-system-x86 qemu-utils \+ e2fsprogs git podman uidmap slirp4netns \+ postgresql-client jq curl zstd++# --- Docker ---+echo "Installing Docker..."+if ! command -v docker &>/dev/null; then+ curl -fsSL https://get.docker.com | sh+fi+systemctl enable --now docker++# --- Go ---+GO_VERSION="1.24.1"+if [ ! -d "/usr/local/go" ] || ! /usr/local/go/bin/go version 2>/dev/null | grep -q "$GO_VERSION"; then+ echo "Installing Go $GO_VERSION..."+ rm -rf /usr/local/go+ curl -fsSL "https://go.dev/dl/go${GO_VERSION}.linux-${GOARCH}.tar.gz" | tar -C /usr/local -xzf -+fi+cat > /etc/profile.d/golang.sh << 'EOF'+export PATH="/usr/local/go/bin:$HOME/go/bin:$PATH"+EOF+export PATH="/usr/local/go/bin:$HOME/go/bin:$PATH"+echo "Go: $(/usr/local/go/bin/go version)"++# --- Kernel for QEMU ---+# Use the same kernel as Firecracker — vmlinux-docker-5.10.bin from AWS S3 quickstart.+# This kernel has CONFIG_VIRTIO_VSOCKETS, CONFIG_VIRTIO_BLK, CONFIG_VIRTIO_NET enabled.+echo "Downloading guest kernel..."+KERNEL_DIR="/opt/opensandbox"+mkdir -p "$KERNEL_DIR"+KERNEL_URL="https://s3.amazonaws.com/spec.ccfc.min/img/quickstart_guide/${KERNEL_ARCH}/kernels/vmlinux-docker-5.10.bin"+if [ ! -f "$KERNEL_DIR/vmlinux" ]; then+ curl -fsSL "$KERNEL_URL" -o "$KERNEL_DIR/vmlinux"+ chmod 644 "$KERNEL_DIR/vmlinux"+ echo "Kernel downloaded: $KERNEL_DIR/vmlinux"+else+ echo "Kernel already exists: $KERNEL_DIR/vmlinux"+fi++# --- KVM + vhost-vsock ---+echo "Loading kernel modules..."+modprobe kvm || true++# Load architecture-specific KVM module+case "$ARCH" in+ x86_64)+ modprobe kvm_intel 2>/dev/null || modprobe kvm_amd 2>/dev/null || true+ ;;+ aarch64)+ # KVM is built-in on ARM64, no separate module needed+ ;;+esac++modprobe vhost_vsock || true++# Persist modules across reboots+cat > /etc/modules-load.d/kvm.conf << 'EOF'+kvm+vhost_vsock+EOF++# Ensure /dev/kvm and /dev/vhost-vsock are accessible+chmod 666 /dev/kvm 2>/dev/null || true+chmod 666 /dev/vhost-vsock 2>/dev/null || true++# Add udev rule for persistent permissions+cat > /etc/udev/rules.d/99-opensandbox.rules << 'EOF'+KERNEL=="kvm", GROUP="kvm", MODE="0666"+KERNEL=="vhost-vsock", MODE="0666"+EOF++# --- sysctl tuning ---+cat > /etc/sysctl.d/99-opensandbox.conf << 'EOF'+# IP forwarding for VM networking+net.ipv4.ip_forward = 1+net.ipv4.conf.all.route_localnet = 1++# ARP table thresholds (many VMs = many ARP entries)+net.ipv4.neigh.default.gc_thresh1 = 1024+net.ipv4.neigh.default.gc_thresh2 = 4096+net.ipv4.neigh.default.gc_thresh3 = 8192++# File and inotify limits+fs.file-max = 1000000+fs.inotify.max_user_watches = 524288+fs.inotify.max_user_instances = 8192+EOF+sysctl --system -q++# --- Directory structure ---+mkdir -p /data/sandboxes /data/firecracker/images /data/checkpoints /etc/opensandbox++# --- PostgreSQL + Redis containers ---+echo "Starting PostgreSQL and Redis..."+if ! docker ps --format '{{.Names}}' | grep -q '^opensandbox-postgres$'; then+ docker run -d --name opensandbox-postgres \+ --restart unless-stopped \+ -p 5432:5432 \+ -e POSTGRES_USER=opensandbox \+ -e POSTGRES_PASSWORD=opensandbox \+ -e POSTGRES_DB=opensandbox \+ -v /data/postgres:/var/lib/postgresql/data \+ postgres:16+fi++if ! docker ps --format '{{.Names}}' | grep -q '^opensandbox-redis$'; then+ docker run -d --name opensandbox-redis \+ --restart unless-stopped \+ -p 6379:6379 \+ redis:7-alpine+fi++# Wait for PostgreSQL+echo "Waiting for PostgreSQL..."+for i in $(seq 1 30); do+ if PGPASSWORD=opensandbox psql -h localhost -U opensandbox -d opensandbox -c '\q' 2>/dev/null; then+ break+ fi+ sleep 2+done++# --- systemd units ---+echo "Installing systemd units..."++cat > /etc/systemd/system/opensandbox-worker.service << 'EOF'+[Unit]+Description=OpenSandbox Worker (QEMU backend)+After=network-online.target docker.service+Wants=network-online.target++[Service]+Type=simple+ExecStartPre=/sbin/modprobe vhost_vsock+EnvironmentFile=/etc/opensandbox/worker.env+ExecStart=/usr/local/bin/opensandbox-worker+Restart=on-failure+RestartSec=5+LimitNOFILE=1000000+LimitNPROC=unlimited+KillMode=mixed+TimeoutStopSec=180++[Install]+WantedBy=multi-user.target+EOF++cat > /etc/systemd/system/opensandbox-server.service << 'EOF'+[Unit]+Description=OpenSandbox Server+After=network-online.target docker.service+Wants=network-online.target++[Service]+Type=simple+EnvironmentFile=/etc/opensandbox/server.env+ExecStart=/usr/local/bin/opensandbox-server+Restart=on-failure+RestartSec=5+LimitNOFILE=1000000++[Install]+WantedBy=multi-user.target+EOF++systemctl daemon-reload+systemctl enable opensandbox-worker opensandbox-server++echo "=== Azure host setup complete ==="+echo " QEMU: $(qemu-system-x86_64 --version | head -1)"+echo " Go: $(/usr/local/go/bin/go version)"+echo " KVM: $(ls -la /dev/kvm 2>/dev/null || echo 'not available')"+echo " VSOCK: $(ls -la /dev/vhost-vsock 2>/dev/null || echo 'not available')"diff --git a/internal/config/config.go b/internal/config/config.goindex f3c772e4..733e7958 100644--- a/internal/config/config.go+++ b/internal/config/config.go@@ -70,11 +70,17 @@ type Config struct {DefaultSandboxCPUs int // default vCPUs per sandbox, default 1DefaultSandboxDiskMB 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")+// AWS EC2 compute pool (server mode only — for auto-scaling worker machines)EC2AMI string // Custom AMI with Firecracker pre-installedEC2InstanceType string // e.g. "c7gd.metal", "r6gd.metal", "r7gd.metal"@@ -150,9 +156,11 @@ 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 DataDirImagesDir: os.Getenv("OPENSANDBOX_IMAGES_DIR"), // default derived from DataDir+ QEMUBin: envOrDefault("OPENSANDBOX_QEMU_BIN", "qemu-system-x86_64"),EC2AMI: os.Getenv("OPENSANDBOX_EC2_AMI"),EC2InstanceType: envOrDefault("OPENSANDBOX_EC2_INSTANCE_TYPE", "c7gd.metal"),diff --git a/internal/qemu/agent_client.go b/internal/qemu/agent_client.gonew file mode 100644index 00000000..6ae5ac13--- /dev/null+++ b/internal/qemu/agent_client.go@@ -0,0 +1,296 @@+package qemu++import (+ "context"+ "fmt"+ "net"+ "time"++ "golang.org/x/sys/unix"+ "google.golang.org/grpc"+ "google.golang.org/grpc/backoff"+ "google.golang.org/grpc/credentials/insecure"++ pb "github.com/opensandbox/opensandbox/proto/agent"+)++// AgentClient is the host-side gRPC client that connects to the+// osb-agent running inside a QEMU VM via AF_VSOCK.+type AgentClient struct {+ conn *grpc.ClientConn+ client pb.SandboxAgentClient+}++// NewAgentClient connects to the agent via AF_VSOCK using the guest CID.+// QEMU uses the kernel's vhost-vsock directly — no UDS file needed.+// Port 1024 is the agent gRPC server inside the VM.+func NewAgentClient(guestCID uint32) (*AgentClient, error) {+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()++ conn, err := grpc.DialContext(ctx,+ "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, guestCID, 1024)+ }),+ grpc.WithDefaultCallOptions(+ grpc.MaxCallRecvMsgSize(64*1024*1024),+ grpc.MaxCallSendMsgSize(64*1024*1024),+ ),+ )+ if err != nil {+ return nil, fmt.Errorf("connect to agent at CID %d: %w", guestCID, err)+ }++ return &AgentClient{+ conn: conn,+ client: pb.NewSandboxAgentClient(conn),+ }, nil+}++// dialVsock connects to a guest port via AF_VSOCK (kernel vhost-vsock).+func dialVsock(ctx context.Context, cid uint32, port uint32) (net.Conn, error) {+ fd, err := unix.Socket(unix.AF_VSOCK, unix.SOCK_STREAM, 0)+ if err != nil {+ return nil, fmt.Errorf("create AF_VSOCK socket: %w", err)+ }++ sa := &unix.SockaddrVM{+ CID: cid,+ Port: port,+ }++ // Use a goroutine for connect with context cancellation+ connectDone := make(chan error, 1)+ go func() {+ connectDone <- unix.Connect(fd, sa)+ }()++ select {+ case err := <-connectDone:+ if err != nil {+ unix.Close(fd)+ return nil, fmt.Errorf("connect AF_VSOCK CID=%d port=%d: %w", cid, port, err)+ }+ case <-ctx.Done():+ unix.Close(fd)+ return nil, ctx.Err()+ }++ // Wrap the raw fd in a net.Conn+ file := fdToConn(fd)+ return file, nil+}++// fdToConn wraps a raw file descriptor into a net.Conn.+func fdToConn(fd int) net.Conn {+ // AF_VSOCK sockets are not supported by net.FileConn, so use+ // the raw syscall-based implementation directly.+ return &rawVsockConn{fd: fd}+}++// rawVsockConn is a fallback net.Conn implementation using raw syscalls.+type rawVsockConn struct {+ fd int+}++func (c *rawVsockConn) Read(b []byte) (int, error) {+ n, err := unix.Read(c.fd, b)+ if err != nil {+ return 0, err+ }+ return n, nil+}++func (c *rawVsockConn) Write(b []byte) (int, error) {+ return unix.Write(c.fd, b)+}++func (c *rawVsockConn) Close() error {+ return unix.Close(c.fd)+}++func (c *rawVsockConn) LocalAddr() net.Addr { return vsockAddr{} }+func (c *rawVsockConn) RemoteAddr() net.Addr { return vsockAddr{} }+func (c *rawVsockConn) SetDeadline(t time.Time) error { return nil }+func (c *rawVsockConn) SetReadDeadline(t time.Time) error { return nil }+func (c *rawVsockConn) SetWriteDeadline(t time.Time) error { return nil }++type vsockAddr struct{}++func (vsockAddr) Network() string { return "vsock" }+func (vsockAddr) String() string { return "vsock" }++// 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.+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.+// Uses AF_VSOCK directly instead of Firecracker's UDS protocol.+func (c *AgentClient) ConnectPTYData(guestCID uint32, dataPort uint32) (net.Conn, error) {+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ conn, err := dialVsock(ctx, guestCID, dataPort)+ if err != nil {+ return nil, fmt.Errorf("connect to PTY data port %d: %w", dataPort, err)+ }+ return conn, nil+}diff --git a/internal/qemu/fd_linux.go b/internal/qemu/fd_linux.gonew file mode 100644index 00000000..e4501616--- /dev/null+++ b/internal/qemu/fd_linux.go@@ -0,0 +1,8 @@+package qemu++import "os"++// newFileFromFD wraps a raw file descriptor in an *os.File.+func newFileFromFD(fd int) *os.File {+ return os.NewFile(uintptr(fd), "vsock")+}diff --git a/internal/qemu/manager.go b/internal/qemu/manager.gonew file mode 100644index 00000000..88d09bc2--- /dev/null+++ b/internal/qemu/manager.go@@ -0,0 +1,1028 @@+// Package qemu implements sandbox.Manager using QEMU q35 VMs with KVM acceleration.+// Each sandbox is a full VM with virtio devices, communicating with the host+// via gRPC over AF_VSOCK (kernel vhost-vsock).+package qemu++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)++// ErrNotImplemented is returned for features not yet ported to the QEMU backend.+var ErrNotImplemented = fmt.Errorf("not implemented in QEMU backend")++// VMInstance holds the state of a running QEMU VM.+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+ cmd *exec.Cmd+ network *NetworkConfig+ sandboxDir string+ agent *AgentClient+ qmpSockPath string+ qmp *QMPClient+ guestMAC string+ guestCID uint32+ bootArgs string+ restoring chan struct{}+}++// SandboxMeta is persisted to sandbox-meta.json for recovery after hard kills.+type SandboxMeta struct {+ SandboxID string `json:"sandboxId"`+ Template string `json:"template"`+ CpuCount int `json:"cpuCount"`+ MemoryMB int `json:"memoryMB"`+ GuestPort int `json:"guestPort"`+}++// Config holds configuration for the QEMU Manager.+type Config struct {+ DataDir string // base data directory (e.g., /data)+ KernelPath string // path to vmlinux kernel+ ImagesDir string // path to base rootfs images+ QEMUBin string // path to qemu-system-x86_64 binary+ DefaultMemoryMB int+ DefaultCPUs int+ DefaultDiskMB int+ DefaultPort int+}++// Manager implements sandbox.Manager using QEMU VMs.+type Manager struct {+ cfg Config+ subnets *SubnetAllocator++ mu sync.RWMutex+ vms map[string]*VMInstance+ nextCID uint32+ uploadWg sync.WaitGroup+}++// NewManager creates a new QEMU-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-docker-5.10.bin")+ }+ if cfg.ImagesDir == "" {+ cfg.ImagesDir = filepath.Join(cfg.DataDir, "firecracker", "images")+ }+ if cfg.QEMUBin == "" {+ cfg.QEMUBin = "qemu-system-x86_64"+ }+ if cfg.DefaultMemoryMB == 0 {+ cfg.DefaultMemoryMB = 512+ }+ if cfg.DefaultCPUs == 0 {+ cfg.DefaultCPUs = 1+ }+ if cfg.DefaultDiskMB == 0 {+ cfg.DefaultDiskMB = 20480+ }+ if cfg.DefaultPort == 0 {+ cfg.DefaultPort = 80+ }++ if _, err := os.Stat(cfg.KernelPath); err != nil {+ return nil, fmt.Errorf("kernel not found at %s: %w", cfg.KernelPath, err)+ }+ if _, err := exec.LookPath(cfg.QEMUBin); err != nil {+ return nil, fmt.Errorf("QEMU binary not found: %w", err)+ }++ if err := EnableForwarding(); err != nil {+ log.Printf("qemu: warning: could not enable IP forwarding: %v", err)+ }++ return &Manager{+ cfg: cfg,+ subnets: NewSubnetAllocator(),+ vms: make(map[string]*VMInstance),+ nextCID: 3,+ }, nil+}++// 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+}++// buildQEMUArgs constructs the QEMU command-line arguments.+func (m *Manager) buildQEMUArgs(cpus, memMB int, rootfsPath, workspacePath, tapName, mac string, cid uint32, qmpSock, bootArgs string) []string {+ return []string{+ "-machine", "q35,accel=kvm",+ "-cpu", "host",+ "-m", fmt.Sprintf("%dM", memMB),+ "-smp", fmt.Sprintf("%d", cpus),+ "-kernel", m.cfg.KernelPath,+ "-append", bootArgs,+ "-drive", fmt.Sprintf("file=%s,format=raw,if=virtio", rootfsPath),+ "-drive", fmt.Sprintf("file=%s,format=raw,if=virtio", workspacePath),+ "-netdev", fmt.Sprintf("tap,id=net0,ifname=%s,script=no,downscript=no", tapName),+ "-device", fmt.Sprintf("virtio-net-pci,netdev=net0,mac=%s", mac),+ "-device", fmt.Sprintf("vhost-vsock-pci,guest-cid=%d", cid),+ "-qmp", fmt.Sprintf("unix:%s,server,nowait", qmpSock),+ "-nographic",+ "-nodefaults",+ "-serial", "stdio",+ }+}++// Create launches a new QEMU VM.+func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (*types.Sandbox, error) {+ id := cfg.SandboxID+ if id == "" {+ id = "sb-" + uuid.New().String()[:8]+ }++ template := cfg.Template+ if template == "" || template == "base" {+ template = "default"+ }++ 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 != "" {+ srcRootfs := strings.TrimPrefix(cfg.TemplateRootfsKey, "local://")+ srcWorkspace := strings.TrimPrefix(cfg.TemplateWorkspaceKey, "local://")+ log.Printf("qemu: 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 {+ 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)+ }+ if err := CreateTAP(netCfg); err != nil {+ m.subnets.Release(netCfg.TAPName)+ os.RemoveAll(sandboxDir)+ return nil, fmt.Errorf("create TAP: %w", err)+ }++ 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++ 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)+ }++ cpus := cfg.CpuCount+ if cpus <= 0 {+ cpus = m.cfg.DefaultCPUs+ }+ memMB := cfg.MemoryMB+ if memMB <= 0 {+ memMB = m.cfg.DefaultMemoryMB+ }++ guestCID := m.allocateCID()+ guestMAC := generateMAC(id)++ // Build kernel boot args — no pci=off (QEMU needs PCI for virtio-pci)+ bootArgs := fmt.Sprintf(+ "console=ttyS0 reboot=k panic=1 "++ "root=/dev/vda rw "++ "ip=%s::%s:%s::eth0:off "++ "init=/sbin/init "++ "osb.gateway=%s",+ netCfg.GuestIP, netCfg.HostIP, netCfg.Mask, netCfg.HostIP,+ )++ qmpSockPath := filepath.Join(sandboxDir, "qmp.sock")+ os.Remove(qmpSockPath)++ logPath := filepath.Join(sandboxDir, "qemu.log")+ logFile, err := os.Create(logPath)+ if err != nil {+ m.cleanupVM(netCfg, sandboxDir)+ return nil, fmt.Errorf("create log file: %w", err)+ }++ args := m.buildQEMUArgs(cpus, memMB, rootfsPath, workspacePath,+ netCfg.TAPName, guestMAC, guestCID, qmpSockPath, bootArgs)++ cmd := exec.Command(m.cfg.QEMUBin, args...)+ cmd.Stdout = logFile+ cmd.Stderr = logFile++ if err := cmd.Start(); err != nil {+ logFile.Close()+ m.cleanupVM(netCfg, sandboxDir)+ return nil, fmt.Errorf("start qemu: %w", err)+ }+ logFile.Close()++ // Connect QMP+ qmpClient, err := waitForQMP(qmpSockPath, 10*time.Second)+ if err != nil {+ cmd.Process.Kill()+ cmd.Wait()+ m.cleanupVM(netCfg, sandboxDir)+ return nil, fmt.Errorf("QMP connect: %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,+ sandboxDir: sandboxDir,+ qmpSockPath: qmpSockPath,+ qmp: qmpClient,+ guestMAC: guestMAC,+ guestCID: guestCID,+ bootArgs: bootArgs,+ }++ // Wait for agent via AF_VSOCK+ agentClient, err := m.waitForAgent(context.Background(), guestCID, 30*time.Second)+ if err != nil {+ log.Printf("qemu: agent not ready for %s, killing VM: %v", id, err)+ qmpClient.Close()+ cmd.Process.Kill()+ cmd.Wait()+ m.cleanupVM(netCfg, sandboxDir)+ return nil, fmt.Errorf("agent not ready: %w", err)+ }+ vm.agent = agentClient++ if len(cfg.Envs) > 0 {+ envCtx, envCancel := context.WithTimeout(context.Background(), 5*time.Second)+ if err := agentClient.SetEnvs(envCtx, cfg.Envs); err != nil {+ envCancel()+ log.Printf("qemu: warning: SetEnvs failed for %s: %v", id, err)+ }+ envCancel()+ }++ m.mu.Lock()+ m.vms[id] = vm+ m.mu.Unlock()++ 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("qemu: created VM %s (template=%s, cpu=%d, mem=%dMB, port=%d→%d, tap=%s, mac=%s, cid=%d)",+ id, template, cpus, memMB, hostPort, guestPort, netCfg.TAPName, guestMAC, guestCID)++ 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/AF_VSOCK until it responds or times out.+func (m *Manager) waitForAgent(ctx context.Context, guestCID uint32, timeout time.Duration) (*AgentClient, error) {+ t0 := time.Now()+ deadline := t0.Add(timeout)+ var lastErr error+ attempts := 0++ for time.Now().Before(deadline) {+ attempts+++ tAttempt := time.Now()+ client, err := NewAgentClient(guestCID)+ if err != nil {+ lastErr = err+ if attempts <= 3 || attempts%10 == 0 {+ log.Printf("qemu: waitForAgent: attempt %d dial CID=%d failed (%dms): %v",+ attempts, guestCID, 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("qemu: waitForAgent: attempt %d ping CID=%d failed (%dms): %v",+ attempts, guestCID, time.Since(tAttempt).Milliseconds(), err)+ }+ time.Sleep(50 * time.Millisecond)+ continue+ }++ log.Printf("qemu: waitForAgent: connected to CID=%d on attempt %d (%dms total)",+ guestCID, 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()+ }++ // Try QMP quit first, fall back to process kill+ if vm.qmp != nil {+ _ = vm.qmp.Quit()+ vm.qmp.Close()+ }++ if vm.cmd != nil && vm.cmd.Process != nil {+ vm.cmd.Process.Kill()+ vm.cmd.Wait()+ }++ if vm.network != nil {+ RemoveDNAT(vm.network)+ DeleteTAP(vm.network.TAPName)+ m.subnets.Release(vm.network.TAPName)+ }++ if vm.qmpSockPath != "" {+ os.Remove(vm.qmpSockPath)+ }++ if vm.sandboxDir != "" {+ os.RemoveAll(vm.sandboxDir)+ }++ log.Printf("qemu: destroyed VM %s", vm.ID)+ return nil+}++// cleanupVM cleans up resources on failed creation.+func (m *Manager) cleanupVM(netCfg *NetworkConfig, sandboxDir string) {+ if netCfg != nil {+ 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("qemu: manager closed, %d VMs destroyed", len(vms))+}++// WaitUploads blocks until all in-flight async S3 uploads complete.+func (m *Manager) WaitUploads(timeout time.Duration) {+ done := make(chan struct{})+ go func() {+ m.uploadWg.Wait()+ close(done)+ }()+ select {+ case <-done:+ log.Println("qemu: all S3 uploads complete")+ case <-time.After(timeout):+ log.Printf("qemu: timed out waiting for S3 uploads after %s", timeout)+ }+}++// HibernateAllResult holds the result of a single VM hibernation.+type HibernateAllResult struct {+ SandboxID string+ HibernationKey string+ Err error+}++// HibernateAll hibernates all running VMs concurrently.+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("qemu: 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+ }++ 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+}++// 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 port.+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.+func (m *Manager) ContainerName(id string) string {+ return "qm-" + id+}++// Hibernate snapshots a VM and uploads to S3.+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+ }++ 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)+}++// SaveAsTemplate is not implemented in the QEMU backend.+func (m *Manager) SaveAsTemplate(ctx context.Context, sandboxID, templateID string, checkpointStore *storage.CheckpointStore, onReady func()) (rootfsKey, workspaceKey string, err error) {+ return "", "", ErrNotImplemented+}++// TemplateCachePath returns "" — not implemented.+func (m *Manager) TemplateCachePath(templateID, filename string) string {+ return ""+}++// CreateCheckpoint is not implemented in the QEMU backend.+func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID string, checkpointStore *storage.CheckpointStore, onReady func()) (rootfsKey, workspaceKey string, err error) {+ return "", "", ErrNotImplemented+}++// RestoreFromCheckpoint is not implemented in the QEMU backend.+func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpointID string) error {+ return ErrNotImplemented+}++// ForkFromCheckpoint is not implemented in the QEMU backend.+func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, cfg types.SandboxConfig) (*types.Sandbox, error) {+ return nil, ErrNotImplemented+}++// CheckpointCachePath returns "" — not implemented.+func (m *Manager) CheckpointCachePath(checkpointID, filename string) string {+ return ""+}++// getVM retrieves a VM by ID.+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.+func (m *Manager) getReadyVM(ctx context.Context, id string) (*VMInstance, error) {+ vm, err := m.getVM(id)+ if err != nil {+ return nil, err+ }++ if vm.restoring != nil {+ select {+ case <-vm.restoring:+ 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:CE:00:00:XX:XX where XX:XX are derived from the ID.+// Uses locally-administered unicast prefix (bit 1 of first octet set).+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:CE:00:00:%02x:%02x", b4, b5)+}++// GetGuestCID returns the guest CID for a sandbox (used by PTY manager).+func (m *Manager) GetGuestCID(sandboxID string) (uint32, error) {+ vm, err := m.getVM(sandboxID)+ if err != nil {+ return 0, err+ }+ return vm.guestCID, 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.+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.+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 QEMU processes and TAP devices+// left over from a previous worker run.+func (m *Manager) CleanupOrphanedProcesses() {+ out, err := exec.Command("pgrep", "-f", "qemu-system").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("qemu: killed %d orphaned qemu process(es)", count)+ }+ }++ 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+ }+ tapName := strings.TrimSuffix(fields[1], ":")+ if strings.HasPrefix(tapName, "qm-") {+ _ = exec.Command("ip", "link", "del", tapName).Run()+ log.Printf("qemu: cleaned up orphaned TAP %s", tapName)+ }+ }+ }+}++// LocalRecovery describes a sandbox found on disk that can be recovered.+type LocalRecovery struct {+ SandboxID string+ HasSnapshot bool+ Meta SandboxMeta+}++// RecoverLocalSandboxes scans the sandboxes directory for sandbox data left+// on disk from a previous run.+func (m *Manager) RecoverLocalSandboxes() []LocalRecovery {+ sandboxesDir := filepath.Join(m.cfg.DataDir, "sandboxes")+ entries, err := os.ReadDir(sandboxesDir)+ if err != nil {+ log.Printf("qemu: 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)++ snapshotMetaPath := filepath.Join(sandboxDir, "snapshot", "snapshot-meta.json")+ if fileExists(filepath.Join(sandboxDir, "snapshot", "mem")) &&+ 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+ }+ }+ }++ 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+ }+ }+ log.Printf("qemu: skipping %s: workspace exists but no sandbox-meta.json", sandboxID)+ }+ }+ return recoveries+}diff --git a/internal/qemu/network.go b/internal/qemu/network.gonew file mode 100644index 00000000..d8b57f84--- /dev/null+++ b/internal/qemu/network.go@@ -0,0 +1,254 @@+package qemu++import (+ "fmt"+ "net"+ "os/exec"+ "strings"+ "sync"+)++// NetworkConfig holds the networking state for a single VM.+type NetworkConfig struct {+ TAPName string // e.g., "qm-tap0000000"+ 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+}++// 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.+func (a *SubnetAllocator) Allocate() (*NetworkConfig, error) {+ a.mu.Lock()+ defer a.mu.Unlock()++ block := a.next+ for a.used[block] {+ block+++ if block > 16383 {+ return nil, fmt.Errorf("subnet pool exhausted")+ }+ }+ a.used[block] = true+ a.next = block + 1++ base := block * 4+ b2 := byte(base >> 8)+ b3 := byte(base & 0xFF)++ hostIP := fmt.Sprintf("172.16.%d.%d", b2, b3+1)+ guestIP := fmt.Sprintf("172.16.%d.%d", b2, b3+2)++ tapName := fmt.Sprintf("qm-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 migration state.+func (a *SubnetAllocator) AllocateSpecific(tapName string) (*NetworkConfig, error) {+ a.mu.Lock()+ defer a.mu.Unlock()++ var block uint32+ if _, err := fmt.Sscanf(tapName, "qm-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++ 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()++ var block uint32+ if _, err := fmt.Sscanf(tapName, "qm-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 {+ if err := run("ip", "tuntap", "add", "dev", cfg.TAPName, "mode", "tap"); err != nil {+ return fmt.Errorf("create tap %s: %w", cfg.TAPName, err)+ }++ 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)+ }++ 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+ _ = 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))++ 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))+}++// EnableForwarding enables IPv4 forwarding and masquerading for the VM subnet.+func EnableForwarding() error {+ if err := run("sysctl", "-w", "net.ipv4.ip_forward=1"); err != nil {+ return fmt.Errorf("enable ip_forward: %w", err)+ }++ if err := run("sysctl", "-w", "net.ipv4.conf.all.route_localnet=1"); err != nil {+ return fmt.Errorf("enable route_localnet: %w", err)+ }++ out, _ := exec.Command("iptables", "-t", "nat", "-S", "POSTROUTING").CombinedOutput()+ outRules := string(out)+ if !strings.Contains(outRules, "172.16.0.0/16") {+ outIface := detectDefaultInterface()+ if outIface != "" {+ _ = run("iptables", "-t", "nat", "-A", "POSTROUTING",+ "-s", "172.16.0.0/16", "-o", outIface,+ "-j", "MASQUERADE")+ } else {+ _ = run("iptables", "-t", "nat", "-A", "POSTROUTING",+ "-s", "172.16.0.0/16", "!", "-o", "qm-tap+",+ "-j", "MASQUERADE")+ }+ }++ 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")+ }++ 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+}++func detectDefaultInterface() string {+ out, err := exec.Command("ip", "route", "show", "default").CombinedOutput()+ if err != nil {+ return ""+ }+ 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+}++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/qemu/qmp.go b/internal/qemu/qmp.gonew file mode 100644index 00000000..a2b4cd44--- /dev/null+++ b/internal/qemu/qmp.go@@ -0,0 +1,222 @@+// Package qemu implements sandbox.Manager using QEMU q35 VMs with KVM acceleration.+package qemu++import (+ "bufio"+ "encoding/json"+ "fmt"+ "net"+ "sync"+ "time"+)++// QMPClient communicates with a QEMU instance via QMP (QEMU Machine Protocol)+// over a Unix domain socket. QMP uses line-delimited JSON messages.+type QMPClient struct {+ mu sync.Mutex+ conn net.Conn+ r *bufio.Reader+}++// qmpResponse is the generic QMP response envelope.+type qmpResponse struct {+ Return json.RawMessage `json:"return,omitempty"`+ Error *qmpError `json:"error,omitempty"`+ Event string `json:"event,omitempty"`+ QMP json.RawMessage `json:"QMP,omitempty"`+}++type qmpError struct {+ Class string `json:"class"`+ Desc string `json:"desc"`+}++// qmpCommand is the generic QMP command envelope.+type qmpCommand struct {+ Execute string `json:"execute"`+ Arguments interface{} `json:"arguments,omitempty"`+}++// QMPStatus represents the response from query-status.+type QMPStatus struct {+ Running bool `json:"running"`+ Status string `json:"status"`+}++// QMPMigrateStatus represents the response from query-migrate.+type QMPMigrateStatus struct {+ Status string `json:"status"`+}++// ConnectQMP connects to the QMP socket and completes the handshake:+// 1. Read greeting {"QMP": {...}}+// 2. Send {"execute": "qmp_capabilities"}+// 3. Read {"return": {}}+func ConnectQMP(socketPath string, timeout time.Duration) (*QMPClient, error) {+ conn, err := net.DialTimeout("unix", socketPath, timeout)+ if err != nil {+ return nil, fmt.Errorf("dial QMP socket %s: %w", socketPath, err)+ }++ _ = conn.SetDeadline(time.Now().Add(timeout))+ r := bufio.NewReader(conn)++ // Read greeting+ line, err := r.ReadBytes('\n')+ if err != nil {+ conn.Close()+ return nil, fmt.Errorf("read QMP greeting: %w", err)+ }+ var greeting qmpResponse+ if err := json.Unmarshal(line, &greeting); err != nil || greeting.QMP == nil {+ conn.Close()+ return nil, fmt.Errorf("invalid QMP greeting: %s", string(line))+ }++ // Send qmp_capabilities+ capCmd, _ := json.Marshal(qmpCommand{Execute: "qmp_capabilities"})+ capCmd = append(capCmd, '\n')+ if _, err := conn.Write(capCmd); err != nil {+ conn.Close()+ return nil, fmt.Errorf("send qmp_capabilities: %w", err)+ }++ // Read response+ line, err = r.ReadBytes('\n')+ if err != nil {+ conn.Close()+ return nil, fmt.Errorf("read qmp_capabilities response: %w", err)+ }+ var capResp qmpResponse+ if err := json.Unmarshal(line, &capResp); err != nil {+ conn.Close()+ return nil, fmt.Errorf("parse qmp_capabilities response: %w", err)+ }+ if capResp.Error != nil {+ conn.Close()+ return nil, fmt.Errorf("qmp_capabilities error: %s: %s", capResp.Error.Class, capResp.Error.Desc)+ }++ _ = conn.SetDeadline(time.Time{}) // clear deadline++ return &QMPClient{conn: conn, r: r}, nil+}++// execute sends a QMP command and returns the response, filtering out async events.+func (q *QMPClient) execute(cmd qmpCommand, timeout time.Duration) (*qmpResponse, error) {+ q.mu.Lock()+ defer q.mu.Unlock()++ data, _ := json.Marshal(cmd)+ data = append(data, '\n')++ _ = q.conn.SetDeadline(time.Now().Add(timeout))+ defer q.conn.SetDeadline(time.Time{})++ if _, err := q.conn.Write(data); err != nil {+ return nil, fmt.Errorf("write QMP command %s: %w", cmd.Execute, err)+ }++ // Read response, skipping async events+ for {+ line, err := q.r.ReadBytes('\n')+ if err != nil {+ return nil, fmt.Errorf("read QMP response for %s: %w", cmd.Execute, err)+ }+ var resp qmpResponse+ if err := json.Unmarshal(line, &resp); err != nil {+ return nil, fmt.Errorf("parse QMP response for %s: %w (%s)", cmd.Execute, err, string(line))+ }+ // Skip async events+ if resp.Event != "" {+ continue+ }+ if resp.Error != nil {+ return nil, fmt.Errorf("QMP %s error: %s: %s", cmd.Execute, resp.Error.Class, resp.Error.Desc)+ }+ return &resp, nil+ }+}++// Stop pauses the VM (equivalent to pressing the pause button).+func (q *QMPClient) Stop() error {+ _, err := q.execute(qmpCommand{Execute: "stop"}, 10*time.Second)+ return err+}++// Cont resumes the VM after a stop.+func (q *QMPClient) Cont() error {+ _, err := q.execute(qmpCommand{Execute: "cont"}, 10*time.Second)+ return err+}++// Quit terminates the QEMU process.+func (q *QMPClient) Quit() error {+ _, err := q.execute(qmpCommand{Execute: "quit"}, 10*time.Second)+ return err+}++// QueryStatus returns the current VM status.+func (q *QMPClient) QueryStatus() (*QMPStatus, error) {+ resp, err := q.execute(qmpCommand{Execute: "query-status"}, 10*time.Second)+ if err != nil {+ return nil, err+ }+ var status QMPStatus+ if err := json.Unmarshal(resp.Return, &status); err != nil {+ return nil, fmt.Errorf("parse query-status: %w", err)+ }+ return &status, nil+}++// Migrate saves the VM state to the given URI.+// URI format: "exec:cat > /path/to/statefile"+func (q *QMPClient) Migrate(uri string) error {+ _, err := q.execute(qmpCommand{+ Execute: "migrate",+ Arguments: map[string]string{"uri": uri},+ }, 5*time.Minute)+ return err+}++// QueryMigrate returns the current migration status.+func (q *QMPClient) QueryMigrate() (*QMPMigrateStatus, error) {+ resp, err := q.execute(qmpCommand{Execute: "query-migrate"}, 10*time.Second)+ if err != nil {+ return nil, err+ }+ var status QMPMigrateStatus+ if err := json.Unmarshal(resp.Return, &status); err != nil {+ return nil, fmt.Errorf("parse query-migrate: %w", err)+ }+ return &status, nil+}++// WaitMigration polls query-migrate until status is "completed" or an error occurs.+func (q *QMPClient) WaitMigration(timeout time.Duration) error {+ deadline := time.Now().Add(timeout)+ for time.Now().Before(deadline) {+ status, err := q.QueryMigrate()+ if err != nil {+ return err+ }+ switch status.Status {+ case "completed":+ return nil+ case "failed":+ return fmt.Errorf("migration failed")+ case "cancelled":+ return fmt.Errorf("migration cancelled")+ }+ time.Sleep(100 * time.Millisecond)+ }+ return fmt.Errorf("migration timed out after %v", timeout)+}++// Close closes the QMP connection.+func (q *QMPClient) Close() error {+ if q == nil || q.conn == nil {+ return nil+ }+ return q.conn.Close()+}diff --git a/internal/qemu/rootfs.go b/internal/qemu/rootfs.gonew file mode 100644index 00000000..a23ea386--- /dev/null+++ b/internal/qemu/rootfs.go@@ -0,0 +1,74 @@+package qemu++import (+ "fmt"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+)++// 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 {+ if err := os.MkdirAll(filepath.Dir(destPath), 0755); err != nil {+ return fmt.Errorf("mkdir for rootfs: %w", err)+ }++ 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.+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)+ }++ f, err := os.Create(path)+ if err != nil {+ return fmt.Errorf("create workspace file: %w", err)+ }+ if err := f.Truncate(int64(sizeMB) * 1024 * 1024); err != nil {+ f.Close()+ os.Remove(path)+ return fmt.Errorf("truncate workspace: %w", err)+ }+ f.Close()++ cmd := exec.Command("mkfs.ext4", "-q", "-F",+ "-L", "workspace",+ "-O", "^has_journal",+ 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.+func ResolveBaseImage(imagesDir, template string) (string, error) {+ if template == "" {+ template = "ubuntu"+ }++ 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/qemu/snapshot.go b/internal/qemu/snapshot.gonew file mode 100644index 00000000..5f9db886--- /dev/null+++ b/internal/qemu/snapshot.go@@ -0,0 +1,767 @@+package qemu++import (+ "context"+ "encoding/json"+ "fmt"+ "io"+ "log"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "time"++ "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"+)++// SnapshotMeta holds metadata persisted alongside snapshot files.+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"`+ CpuCount int `json:"cpuCount"`+ MemoryMB int `json:"memoryMB"`+ Template string `json:"template"`+ GuestPort int `json:"guestPort"`+ SnapshotedAt time.Time `json:"snapshotedAt,omitempty"`+}++// doHibernate pauses a running VM, saves VM state via QMP migrate, and kicks off+// an async S3 upload. QEMU migration produces a single state file (memory + device+// state combined), unlike Firecracker's separate mem + vmstate files.+//+// Flow:+// 1. SyncFS via agent (flush disk buffers — agent stays alive)+// 2. Close gRPC connection (vsock must be inactive for migration)+// 3. QMP stop (pause VM)+// 4. QMP migrate "exec:cat > /path/snapshot/mem" (saves full VM state)+// 5. Poll query-migrate until completed+// 6. QMP quit (kill QEMU process)+// 7. Write snapshot-meta.json+// 8. Clean up network+// 9. (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")++ // Step 1: Sync filesystems inside the VM+ 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("qemu: hibernate %s: exec sync failed: %v", vm.ID, syncErr)+ }+ }+ log.Printf("qemu: hibernate %s: guest sync done (%dms)", vm.ID, time.Since(t0).Milliseconds())++ // Step 2: Close gRPC connection — vsock must be inactive before migration.+ if vm.agent != nil {+ vm.agent.Close()+ vm.agent = nil+ time.Sleep(500 * time.Millisecond)+ }++ // Step 3: Stop (pause) the VM via QMP+ if vm.qmp == nil {+ return nil, fmt.Errorf("no QMP client for VM %s", vm.ID)+ }+ if err := vm.qmp.Stop(); err != nil {+ return nil, fmt.Errorf("QMP stop: %w", err)+ }+ log.Printf("qemu: hibernate %s: paused (%dms)", vm.ID, time.Since(t0).Milliseconds())++ // Step 4: Migrate — saves full VM state (memory + devices) to a single file+ migrateURI := fmt.Sprintf("exec:cat > %s", memFile)+ if err := vm.qmp.Migrate(migrateURI); err != nil {+ return nil, fmt.Errorf("QMP migrate: %w", err)+ }++ // Step 5: Wait for migration to complete+ if err := vm.qmp.WaitMigration(5 * time.Minute); err != nil {+ return nil, fmt.Errorf("migration wait: %w", err)+ }+ log.Printf("qemu: hibernate %s: migration complete (%dms)", vm.ID, time.Since(t0).Milliseconds())++ // Step 6: Quit QEMU process+ _ = vm.qmp.Quit()+ vm.qmp.Close()+ vm.qmp = nil++ // Also wait for the process to exit+ if vm.cmd != nil && vm.cmd.Process != nil {+ done := make(chan error, 1)+ go func() { done <- vm.cmd.Wait() }()+ select {+ case <-done:+ case <-time.After(5 * time.Second):+ vm.cmd.Process.Kill()+ <-done+ }+ }++ // Step 7: 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"),+ CpuCount: vm.CpuCount,+ MemoryMB: vm.MemoryMB,+ Template: vm.Template,+ GuestPort: vm.GuestPort,+ SnapshotedAt: time.Now(),+ }+ 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 8: Clean up network+ if vm.network != nil {+ RemoveDNAT(vm.network)+ DeleteTAP(vm.network.TAPName)+ m.subnets.Release(vm.network.TAPName)+ }++ // Clean up QMP socket+ if vm.qmpSockPath != "" {+ os.Remove(vm.qmpSockPath)+ }++ checkpointKey := fmt.Sprintf("checkpoints/%s/%d.tar.zst", vm.ID, time.Now().Unix())+ localElapsed := time.Since(t0)+ log.Printf("qemu: hibernate %s: local snapshot complete (%dms), starting async S3 upload",+ vm.ID, localElapsed.Milliseconds())++ // Step 9: Archive + upload to S3 in the background.+ 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")++ if err := createArchive(archivePath, sandboxDir, []string{+ "snapshot/mem",+ "snapshot/snapshot-meta.json",+ "workspace.ext4",+ }); err != nil {+ log.Printf("qemu: async archive failed for %s: %v", sandboxID, err)+ return+ }+ archiveInfo, err := os.Stat(archivePath)+ if err != nil {+ log.Printf("qemu: async archive stat failed for %s: %v", sandboxID, err)+ return+ }+ log.Printf("qemu: 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("qemu: async S3 upload failed for %s: %v", sandboxID, err)+ return+ }+ log.Printf("qemu: 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,+ }, nil+}++// doWake restores a VM from a migration snapshot. The VM resumes exactly where it+// was paused — all processes, memory, open files, and PIDs are intact.+//+// QEMU hot restore: start QEMU with -incoming "exec:cat /path/snapshot/mem" flag+// plus all normal CLI args. QEMU loads state from the incoming migration and resumes.+//+// 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+// 4. Verify drives exist+// 5. Recreate network — try same TAP name for hot restore, fall back to cold boot+// 6. Start QEMU with -incoming flag for hot restore, or cold boot fresh VM+// 7. QMP cont to resume+// 8. Wait for agent, sync clock+// 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")+ metaPath := filepath.Join(snapshotDir, "snapshot-meta.json")++ // Step 1-2: Ensure snapshot files are local+ t0 := time.Now()+ memExists := fileExists(memFile)+ log.Printf("qemu: wake %s: checking local files: mem=%s (exists=%v)", sandboxID, memFile, memExists)++ isLocalWorkspace := strings.HasPrefix(checkpointKey, "local://")++ if !memExists {+ if isLocalWorkspace {+ log.Printf("qemu: wake %s: local workspace recovery (no snapshot)", sandboxID)+ return m.coldBootLocal(ctx, sandboxID, timeout)+ }+ log.Printf("qemu: 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("qemu: wake %s: downloaded + wrote archive (%dms)", sandboxID, time.Since(t0).Milliseconds())+ if err := extractArchive(archivePath, sandboxDir); err != nil {+ return nil, fmt.Errorf("extract archive: %w", err)+ }+ os.Remove(archivePath)+ log.Printf("qemu: wake %s: extracted archive (%dms total)", sandboxID, time.Since(t0).Milliseconds())+ } else {+ log.Printf("qemu: 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+ rootfsPath := filepath.Join(sandboxDir, "rootfs.ext4")+ workspacePath := filepath.Join(sandboxDir, "workspace.ext4")++ if !fileExists(rootfsPath) {+ log.Printf("qemu: 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)+ }+ }+ if !fileExists(workspacePath) {+ return nil, fmt.Errorf("workspace not found at %s", workspacePath)+ }++ // Step 5: Try snapshot restore (fast path) or cold boot fallback+ snapshotRestore := true+ netCfg, err := m.subnets.AllocateSpecific(meta.Network.TAPName)+ if err != nil {+ log.Printf("qemu: 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)+ }++ guestCID := meta.GuestCID+ guestMAC := meta.GuestMAC+ bootArgs := meta.BootArgs++ if snapshotRestore {+ // Hot restore: start QEMU with -incoming to load migration state+ // Update boot args to use new network config IPs (same TAP name)+ qmpSockPath := filepath.Join(sandboxDir, "qmp.sock")+ os.Remove(qmpSockPath)++ logPath := filepath.Join(sandboxDir, "qemu.log")+ logFile, err := os.Create(logPath)+ if err != nil {+ m.cleanupVM(netCfg, "")+ return nil, fmt.Errorf("create log file: %w", err)+ }++ incomingURI := fmt.Sprintf("exec:cat %s", memFile)+ args := m.buildQEMUArgs(meta.CpuCount, meta.MemoryMB, rootfsPath, workspacePath,+ netCfg.TAPName, guestMAC, guestCID, qmpSockPath, bootArgs)+ args = append(args, "-incoming", incomingURI)++ cmd := exec.Command(m.cfg.QEMUBin, args...)+ cmd.Stdout = logFile+ cmd.Stderr = logFile++ if err := cmd.Start(); err != nil {+ logFile.Close()+ m.cleanupVM(netCfg, "")+ return nil, fmt.Errorf("start qemu for restore: %w", err)+ }+ logFile.Close()++ // Connect QMP+ qmpClient, err := waitForQMP(qmpSockPath, 10*time.Second)+ if err != nil {+ cmd.Process.Kill()+ cmd.Wait()+ m.cleanupVM(netCfg, "")+ return nil, fmt.Errorf("QMP connect for restore: %w", err)+ }++ // Resume the VM after migration load+ if err := qmpClient.Cont(); err != nil {+ qmpClient.Close()+ cmd.Process.Kill()+ cmd.Wait()+ m.cleanupVM(netCfg, "")+ return nil, fmt.Errorf("QMP cont after restore: %w", err)+ }+ log.Printf("qemu: wake %s: snapshot restored (hot)", sandboxID)++ 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,+ sandboxDir: sandboxDir,+ qmpSockPath: qmpSockPath,+ qmp: qmpClient,+ guestMAC: guestMAC,+ guestCID: guestCID,+ bootArgs: bootArgs,+ }++ // Wait for agent — AF_VSOCK is available immediately when QEMU starts+ agentClient, err := m.waitForAgent(context.Background(), guestCID, 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+ if err := syncGuestClock(context.Background(), agentClient); err != nil {+ log.Printf("qemu: wake %s: clock sync failed: %v", sandboxID, err)+ }++ m.mu.Lock()+ m.vms[sandboxID] = vm+ m.mu.Unlock()++ log.Printf("qemu: woke VM %s (snapshot restore, port=%d, tap=%s)",+ sandboxID, hostPort, netCfg.TAPName)+ return vmToSandbox(vm), nil+ }++ // Cold boot fallback: boot fresh VM with restored drives+ guestCID = m.allocateCID()+ guestMAC = generateMAC(sandboxID)+ bootArgs = fmt.Sprintf(+ "console=ttyS0 reboot=k panic=1 "++ "root=/dev/vda rw "++ "ip=%s::%s:%s::eth0:off "++ "init=/sbin/init "++ "osb.gateway=%s",+ netCfg.GuestIP, netCfg.HostIP, netCfg.Mask, netCfg.HostIP,+ )++ qmpSockPath := filepath.Join(sandboxDir, "qmp.sock")+ os.Remove(qmpSockPath)++ logPath := filepath.Join(sandboxDir, "qemu.log")+ logFile, err := os.Create(logPath)+ if err != nil {+ m.cleanupVM(netCfg, "")+ return nil, fmt.Errorf("create log file: %w", err)+ }++ args := m.buildQEMUArgs(meta.CpuCount, meta.MemoryMB, rootfsPath, workspacePath,+ netCfg.TAPName, guestMAC, guestCID, qmpSockPath, bootArgs)++ cmd := exec.Command(m.cfg.QEMUBin, args...)+ cmd.Stdout = logFile+ cmd.Stderr = logFile+ if err := cmd.Start(); err != nil {+ logFile.Close()+ m.cleanupVM(netCfg, "")+ return nil, fmt.Errorf("start qemu cold boot: %w", err)+ }+ logFile.Close()++ qmpClient, err := waitForQMP(qmpSockPath, 10*time.Second)+ if err != nil {+ cmd.Process.Kill()+ cmd.Wait()+ m.cleanupVM(netCfg, "")+ return nil, fmt.Errorf("QMP connect for cold boot: %w", err)+ }++ log.Printf("qemu: 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,+ sandboxDir: sandboxDir,+ qmpSockPath: qmpSockPath,+ qmp: qmpClient,+ guestMAC: guestMAC,+ guestCID: guestCID,+ bootArgs: bootArgs,+ }++ agentClient, err := m.waitForAgent(context.Background(), guestCID, 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++ if err := syncGuestClock(context.Background(), agentClient); err != nil {+ log.Printf("qemu: wake %s: clock sync failed: %v", sandboxID, err)+ }++ m.mu.Lock()+ m.vms[sandboxID] = vm+ m.mu.Unlock()++ log.Printf("qemu: woke VM %s (cold boot, port=%d, tap=%s)",+ sandboxID, hostPort, netCfg.TAPName)+ return vmToSandbox(vm), nil+}++// coldBootLocal boots a fresh VM using an existing workspace.ext4 on disk.+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)+ }++ 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)+ }++ 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("qemu: cold-boot-local %s: rootfs recreated from template %q", sandboxID, meta.Template)+ }++ 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+ }++ guestCID := m.allocateCID()+ guestMAC := generateMAC(sandboxID)+ bootArgs := fmt.Sprintf(+ "console=ttyS0 reboot=k panic=1 "++ "root=/dev/vda rw "++ "ip=%s::%s:%s::eth0:off "++ "init=/sbin/init "++ "osb.gateway=%s",+ netCfg.GuestIP, netCfg.HostIP, netCfg.Mask, netCfg.HostIP,+ )++ qmpSockPath := filepath.Join(sandboxDir, "qmp.sock")+ os.Remove(qmpSockPath)++ logPath := filepath.Join(sandboxDir, "qemu.log")+ logFile, err := os.Create(logPath)+ if err != nil {+ m.cleanupVM(netCfg, "")+ return nil, fmt.Errorf("create log file: %w", err)+ }++ args := m.buildQEMUArgs(cpus, memMB, rootfsPath, workspacePath,+ netCfg.TAPName, guestMAC, guestCID, qmpSockPath, bootArgs)++ cmd := exec.Command(m.cfg.QEMUBin, args...)+ cmd.Stdout = logFile+ cmd.Stderr = logFile+ if err := cmd.Start(); err != nil {+ logFile.Close()+ m.cleanupVM(netCfg, "")+ return nil, fmt.Errorf("start qemu: %w", err)+ }+ logFile.Close()++ qmpClient, err := waitForQMP(qmpSockPath, 10*time.Second)+ if err != nil {+ cmd.Process.Kill()+ cmd.Wait()+ m.cleanupVM(netCfg, "")+ return nil, fmt.Errorf("QMP connect: %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,+ sandboxDir: sandboxDir,+ qmpSockPath: qmpSockPath,+ qmp: qmpClient,+ guestMAC: guestMAC,+ guestCID: guestCID,+ bootArgs: bootArgs,+ }++ agentClient, err := m.waitForAgent(context.Background(), guestCID, 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++ if err := syncGuestClock(context.Background(), agentClient); err != nil {+ log.Printf("qemu: cold-boot-local %s: clock sync failed: %v", sandboxID, err)+ }++ m.mu.Lock()+ m.vms[sandboxID] = vm+ m.mu.Unlock()++ log.Printf("qemu: 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()+}++// copyFileReflink copies a file using cp --reflink=auto.+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+}++// syncGuestClock sets the guest clock to the current host time via agent exec.+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+}++// waitForQMP polls until the QMP socket appears and connects.+func waitForQMP(socketPath string, timeout time.Duration) (*QMPClient, error) {+ deadline := time.Now().Add(timeout)+ for time.Now().Before(deadline) {+ if _, err := os.Stat(socketPath); err == nil {+ qmp, err := ConnectQMP(socketPath, 5*time.Second)+ if err == nil {+ return qmp, nil+ }+ }+ time.Sleep(50 * time.Millisecond)+ }+ return nil, fmt.Errorf("QMP socket %s not ready after %v", socketPath, timeout)+}diff --git a/internal/worker/autosave.go b/internal/worker/autosave.goindex 9a868a0f..092baf2f 100644--- a/internal/worker/autosave.go+++ b/internal/worker/autosave.go@@ -6,17 +6,21 @@ import ("sync""time"- fc "github.com/opensandbox/opensandbox/internal/firecracker""github.com/opensandbox/opensandbox/internal/sandbox")+// SyncFSer is implemented by any VM manager that can flush filesystem buffers.+type SyncFSer interface {+ SyncFS(ctx context.Context, sandboxID string) error+}+// WorkspaceAutosaver periodically flushes filesystem buffers inside each// running VM. This ensures workspace.ext4 on the host NVMe is crash-consistent.// On hard kill recovery, the worker cold-boots from template + existing// workspace.ext4 on disk (processes lost, but user files in /workspace are safe).type WorkspaceAutosaver struct {manager sandbox.Manager- fcMgr *fc.Manager+ syncer SyncFSerinterval time.Durationconcurrency intstop chan struct{}@@ -26,12 +30,12 @@ type WorkspaceAutosaver struct {// NewWorkspaceAutosaver creates a new autosaver.func NewWorkspaceAutosaver(mgr sandbox.Manager,- fcMgr *fc.Manager,+ syncer SyncFSer,interval time.Duration,) *WorkspaceAutosaver {return &WorkspaceAutosaver{manager: mgr,- fcMgr: fcMgr,+ syncer: syncer,interval: interval,concurrency: 10,stop: make(chan struct{}),@@ -96,7 +100,7 @@ func (a *WorkspaceAutosaver) syncAll() {syncCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)defer cancel()- if err := a.fcMgr.SyncFS(syncCtx, sandboxID); err != nil {+ if err := a.syncer.SyncFS(syncCtx, sandboxID); err != nil {log.Printf("autosave: syncfs failed for %s: %v", sandboxID, err)mu.Lock()failCount++