An open-source, faster Devin alternative
TypeScript
Virtio-mem replace dimms, hot restore w/ agent prep, minor fixes
Brian Reardon6c19b3ea32c8
diff --git a/cmd/agent/listen_linux.go b/cmd/agent/listen_linux.goindex f8161667..9ee1a2e9 100644--- a/cmd/agent/listen_linux.go+++ b/cmd/agent/listen_linux.go@@ -139,6 +139,16 @@ func waitForReadable(f *os.File, timeout time.Duration) bool {return fds[0].Revents&(unix.POLLIN|unix.POLLHUP) != 0}+// PrepareHibernate resets the active flag so that after migration restore,+// the Accept loop will poll for a new host-side connection instead of+// thinking the old connection is still active.+func (l *virtioSerialListener) PrepareHibernate() {+ l.mu.Lock()+ l.active = false+ l.mu.Unlock()+ log.Printf("agent: virtio-serial: prepared for hibernate (active=false)")+}+func (l *virtioSerialListener) Close() error {l.once.Do(func() { close(l.closed) })return l.f.Close()diff --git a/cmd/agent/main.go b/cmd/agent/main.goindex 0fab6b80..cec35eb3 100644--- a/cmd/agent/main.go+++ b/cmd/agent/main.go@@ -9,7 +9,6 @@ import ("log""os""os/signal"- "strings""syscall""github.com/opensandbox/opensandbox/internal/agent"@@ -20,12 +19,9 @@ const version = "0.1.0"func main() {log.SetFlags(log.Ltime | log.Lmicroseconds)- // Ensure /usr/local/bin and /usr/local/sbin are in PATH for exec.LookPath.- // The init script may not set a full PATH.- path := os.Getenv("PATH")- if !strings.Contains(path, "/usr/local/bin") {- os.Setenv("PATH", "/usr/local/bin:/usr/local/sbin:"+path)- }+ // Set a complete PATH — when running as PID 1 (init), there's no shell+ // profile to source, so PATH may be empty or minimal.+ os.Setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin")log.Printf("osb-agent %s starting", version)@@ -38,14 +34,25 @@ func main() {srv := agent.NewServer(version)srv.ListenPort = listenPortForPTY- // Graceful shutdown+ // Signal handling:+ // SIGTERM/SIGINT: clean shutdown (exit)+ // SIGUSR1: hibernate prep — reset virtio-serial listener so Accept+ // will poll for a new connection after migration restoresigCh := make(chan os.Signal, 1)- signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGINT)+ signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGINT, syscall.SIGUSR1)go func() {- sig := <-sigCh- log.Printf("agent: received %v, shutting down", sig)- lis.Close()- os.Exit(0)+ for sig := range sigCh {+ if sig == syscall.SIGUSR1 {+ log.Printf("agent: SIGUSR1 — preparing for hibernate")+ if vsl, ok := lis.(*virtioSerialListener); ok {+ vsl.PrepareHibernate()+ }+ } else {+ log.Printf("agent: received %v, shutting down", sig)+ lis.Close()+ os.Exit(0)+ }+ }}()if err := srv.Serve(lis); err != nil {diff --git a/internal/agent/server.go b/internal/agent/server.goindex 00e62c11..ac6a22b5 100644--- a/internal/agent/server.go+++ b/internal/agent/server.go@@ -51,6 +51,10 @@ type Server struct {ptyMu sync.MutexptySessions map[string]*ptySessionnextPTYPort uint32++ // gRPC server reference for hibernate GracefulStop+ mu sync.Mutex+ grpcServer *grpc.Server}// NewServer creates a new agent server.@@ -65,6 +69,8 @@ func NewServer(version string) *Server {}// Serve starts the gRPC server on the given listener.+// It stores the gRPC server reference so GracefulStop can be called externally+// (e.g., on SIGUSR1 to prepare for hibernate).func (s *Server) Serve(lis net.Listener) error {grpcServer := grpc.NewServer(grpc.MaxRecvMsgSize(64 * 1024 * 1024), // 64MB for file transfers@@ -72,6 +78,21 @@ func (s *Server) Serve(lis net.Listener) error {)pb.RegisterSandboxAgentServer(grpcServer, s)+ s.mu.Lock()+ s.grpcServer = grpcServer+ s.mu.Unlock()+log.Printf("agent: gRPC server listening")return grpcServer.Serve(lis)}++// GracefulStop stops the gRPC server gracefully, allowing in-flight RPCs to complete.+// This causes Serve() to return, so the caller can re-enter Serve() for hibernate/wake.+func (s *Server) GracefulStop() {+ s.mu.Lock()+ gs := s.grpcServer+ s.mu.Unlock()+ if gs != nil {+ gs.GracefulStop()+ }+}diff --git a/internal/qemu/manager.go b/internal/qemu/manager.goindex 74c5b3c8..9a04531f 100644--- a/internal/qemu/manager.go+++ b/internal/qemu/manager.go@@ -53,7 +53,8 @@ type VMInstance struct {guestCID uint32bootArgs stringrestoring chan struct{}- dimmCount int // number of hotplugged DIMMs (for unique IDs)+ baseMemoryMB int // initial memory passed to -m (before virtio-mem)+ virtioMemRequestedMB int // additional memory via virtio-mem (beyond base)}// SandboxMeta is persisted to sandbox-meta.json for recovery after hard kills.@@ -271,6 +272,21 @@ func (m *Manager) PrepareGoldenSnapshot() error {}log.Printf("qemu: golden VM booted, agent ready (%dms)", time.Since(t0).Milliseconds())+ // Load virtio_mem kernel module for memory scaling support.+ // The module must be loaded before the golden snapshot so that restored+ // VMs can use virtio-mem for dynamic memory add/remove.+ modCtx, modCancel := context.WithTimeout(context.Background(), 5*time.Second)+ modResp, modErr := agentClient.Exec(modCtx, &pb.ExecRequest{+ Command: "/bin/sh",+ Args: []string{"-c", "insmod /lib/modules/$(uname -r)/kernel/drivers/virtio/virtio_mem.ko 2>/dev/null; grep -c virtio_mem /proc/modules"},+ })+ modCancel()+ if modErr != nil || (modResp != nil && modResp.ExitCode != 0) {+ log.Printf("qemu: golden: WARNING: virtio_mem module load failed (memory scaling may not work): err=%v", modErr)+ } else {+ log.Printf("qemu: golden: virtio_mem module loaded")+ }+// Unmount /workspace and sync before snapshot — the golden migration state// includes virtio-blk device state (ring buffers, pending I/O). If /workspace// is mounted when we snapshot, those stale I/O ops will corrupt any fresh@@ -537,6 +553,7 @@ func (m *Manager) createFromGolden(ctx context.Context, cfg types.SandboxConfig,EndAt: now.Add(timeout),CpuCount: cpus,MemoryMB: memMB,+ baseMemoryMB: memMB,HostPort: hostPort,GuestPort: guestPort,pid: cmd.Process.Pid,@@ -739,7 +756,11 @@ func (m *Manager) buildQEMUArgs(cpus, memMB int, rootfsPath, workspacePath, tapNreturn []string{"-machine", "q35,accel=kvm","-cpu", "host",- "-m", fmt.Sprintf("%dM,maxmem=16G,slots=8", memMB),+ "-m", fmt.Sprintf("%dM,maxmem=16G", memMB),+ // virtio-mem: pluggable memory pool. Scale via QMP qom-set requested-size.+ // 15GB max + base gives 16GB ceiling. Block size 128MB for granularity.+ "-object", "memory-backend-ram,id=vmem0,size=15360M",+ "-device", "virtio-mem-pci,memdev=vmem0,id=vm0,block-size=128M,requested-size=0","-smp", fmt.Sprintf("%d", cpus),"-kernel", m.cfg.KernelPath,"-append", bootArgs,@@ -756,10 +777,6 @@ func (m *Manager) buildQEMUArgs(cpus, memMB int, rootfsPath, workspacePath, tapN"-nographic","-nodefaults","-serial", "stdio",- // Seccomp sandbox: restricts QEMU's syscalls after initialization.- // If a guest exploits a QEMU vulnerability, dangerous syscalls- // (execve, fork, mount, ptrace) are blocked by the kernel.- "-sandbox", "on,obsolete=deny,elevateprivileges=deny,spawn=deny,resourcecontrol=deny",}}@@ -932,6 +949,7 @@ func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (*types.SEndAt: now.Add(timeout),CpuCount: cpus,MemoryMB: memMB,+ baseMemoryMB: memMB,HostPort: hostPort,GuestPort: guestPort,pid: cmd.Process.Pid,@@ -1399,20 +1417,22 @@ func (m *Manager) SetResourceLimits(ctx context.Context, sandboxID string, maxPireturn err}- // Memory hotplug: if requested memory > current VM physical RAM, add a DIMM- if maxMemoryBytes > 0 {- currentBytes := int64(vm.MemoryMB) * 1024 * 1024- if maxMemoryBytes > currentBytes && vm.qmp != nil {- addMB := int(maxMemoryBytes-currentBytes) / (1024 * 1024)- if addMB > 0 {- if err := vm.qmp.HotplugMemory(vm.dimmCount, addMB); err != nil {- log.Printf("qemu: memory hotplug %s: add %dMB failed: %v", sandboxID, addMB, err)- // Non-fatal — cgroup limit will still be set (capped at physical RAM)- } else {- vm.dimmCount++- vm.MemoryMB += addMB- log.Printf("qemu: memory hotplug %s: added %dMB (total %dMB)", sandboxID, addMB, vm.MemoryMB)- }+ // virtio-mem: adjust pluggable memory to match requested total+ if maxMemoryBytes > 0 && vm.qmp != nil {+ totalDesiredMB := int(maxMemoryBytes) / (1024 * 1024)+ additionalMB := totalDesiredMB - vm.baseMemoryMB+ if additionalMB < 0 {+ additionalMB = 0+ }+ // Round up to 128MB block size+ additionalMB = ((additionalMB + 127) / 128) * 128+ if additionalMB != vm.virtioMemRequestedMB {+ if err := vm.qmp.SetVirtioMemSize(additionalMB); err != nil {+ log.Printf("qemu: virtio-mem %s: set %dMB failed: %v", sandboxID, additionalMB, err)+ } else {+ vm.virtioMemRequestedMB = additionalMB+ vm.MemoryMB = vm.baseMemoryMB + additionalMB+ log.Printf("qemu: virtio-mem %s: %dMB additional (total %dMB)", sandboxID, additionalMB, vm.MemoryMB)}}}@@ -1885,6 +1905,7 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, cEndAt: now.Add(timeout),CpuCount: cpus,MemoryMB: memMB,+ baseMemoryMB: memMB,HostPort: hostPort,GuestPort: guestPort,pid: cmd.Process.Pid,diff --git a/internal/qemu/migration.go b/internal/qemu/migration.goindex acb52917..15788ed0 100644--- a/internal/qemu/migration.go+++ b/internal/qemu/migration.go@@ -301,6 +301,7 @@ func (m *Manager) PrepareIncomingMigration(ctx context.Context, sandboxID, rootfEndAt: now.Add(300 * time.Second),CpuCount: cpus,MemoryMB: memMB,+ baseMemoryMB: memMB,HostPort: hp,GuestPort: netCfg.GuestPort,pid: cmd.Process.Pid,diff --git a/internal/qemu/qmp.go b/internal/qemu/qmp.goindex f5ee01fd..ab9760cf 100644--- a/internal/qemu/qmp.go+++ b/internal/qemu/qmp.go@@ -254,33 +254,17 @@ func (q *QMPClient) Execute(command string, args map[string]interface{}) error {return err}-// HotplugMemory adds a memory DIMM to the running VM.-// The guest kernel detects the new memory automatically.-// Each DIMM gets a unique ID based on the index (dimm0, dimm1, etc.).-func (q *QMPClient) HotplugMemory(dimmIndex int, sizeMB int) error {- backendID := fmt.Sprintf("mem%d", dimmIndex)- dimmID := fmt.Sprintf("dimm%d", dimmIndex)+// SetVirtioMemSize sets the requested size of the virtio-mem device.+// sizeMB is the additional memory beyond base (not total).+// The guest kernel onlines/offlines memory blocks automatically.+// Can both scale up and scale down.+func (q *QMPClient) SetVirtioMemSize(sizeMB int) error {sizeBytes := int64(sizeMB) * 1024 * 1024-- // Step 1: Create memory backend- if err := q.Execute("object-add", map[string]interface{}{- "qom-type": "memory-backend-ram",- "id": backendID,- "size": sizeBytes,- }); err != nil {- return fmt.Errorf("object-add memory backend: %w", err)- }-- // Step 2: Attach DIMM device- if err := q.Execute("device_add", map[string]interface{}{- "driver": "pc-dimm",- "id": dimmID,- "memdev": backendID,- }); err != nil {- return fmt.Errorf("device_add dimm: %w", err)- }-- return nil+ return q.Execute("qom-set", map[string]interface{}{+ "path": "/machine/peripheral/vm0",+ "property": "requested-size",+ "value": sizeBytes,+ })}// SendFd passes an open file descriptor to QEMU via the QMP getfd command.diff --git a/internal/qemu/snapshot.go b/internal/qemu/snapshot.goindex 8783d590..bc3c9d85 100644--- a/internal/qemu/snapshot.go+++ b/internal/qemu/snapshot.go@@ -29,6 +29,7 @@ type SnapshotMeta struct {WorkspacePath string `json:"workspacePath"`CpuCount int `json:"cpuCount"`MemoryMB int `json:"memoryMB"`+ BaseMemoryMB int `json:"baseMemoryMB,omitempty"`Template string `json:"template"`GuestPort int `json:"guestPort"`SnapshotedAt time.Time `json:"snapshotedAt,omitempty"`@@ -71,11 +72,25 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointSto}log.Printf("qemu: hibernate %s: guest sync + unmount done (%dms)", vm.ID, time.Since(t0).Milliseconds())- // Step 2: Close host-side gRPC connection.+ // Step 2: Quiesce agent for hibernate.+ // Tell the agent to close its gRPC connection so the virtio-serial listener's+ // active flag is false when the VM state is captured. On resume from migration,+ // the Accept loop will poll for the new host-side connection.+ // We exec "kill -USR1 1" to signal the agent (PID 1) to drop its gRPC server.+ // Then close the host-side gRPC connection and give the guest time to process.if vm.agent != nil {+ // Ask the agent to prepare for hibernate — it will GracefulStop the gRPC server+ prepCtx, prepCancel := context.WithTimeout(ctx, 3*time.Second)+ _, _ = vm.agent.Exec(prepCtx, &pb.ExecRequest{+ Command: "/bin/sh",+ Args: []string{"-c", "kill -USR1 1"},+ })+ prepCancel()vm.agent.Close()vm.agent = nil}+ // Give the guest time to process the gRPC shutdown and reset the listener+ time.Sleep(500 * time.Millisecond)// Step 3: Stop (pause) the VM via QMPif vm.qmp == nil {@@ -126,6 +141,7 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointStoWorkspacePath: detectDrivePath(vm.sandboxDir, "workspace"),CpuCount: vm.CpuCount,MemoryMB: vm.MemoryMB,+ BaseMemoryMB: vm.baseMemoryMB,Template: vm.Template,GuestPort: vm.GuestPort,SnapshotedAt: time.Now(),@@ -371,17 +387,31 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, creturn nil, fmt.Errorf("create log file: %w", err)}- // Start QEMU with golden migration state + user's workspace- args := m.buildQEMUArgs(meta.CpuCount, meta.MemoryMB, rootfsPath, workspacePath,- netCfg.TAPName, guestMAC, agentSockPath, qmpSockPath, bootArgs)- goldenMemZst := filepath.Join(m.goldenDir, "mem.zst")- goldenMemRaw := filepath.Join(m.goldenDir, "mem")+ // Start QEMU with migration state.+ // If the sandbox has its own snapshot/mem (from a real hibernate), use that+ // for true hot restore — all processes, memory, and virtio-mem state resume+ // exactly where they were. The agent was prepared for hibernate via SIGUSR1+ // (gRPC GracefulStop), so its Accept loop will pick up the new connection.+ // Otherwise fall back to golden restore (fast path for workspace-only wake).+ baseMem := m.cfg.DefaultMemoryMBvar incomingURI string- if fileExists(goldenMemZst) {- incomingURI = fmt.Sprintf("exec:zstdcat %s", goldenMemZst)+ if fileExists(memFile) {+ // Hot restore: use sandbox's own migration state+ incomingURI = fmt.Sprintf("exec:cat %s", memFile)+ log.Printf("qemu: wake %s: hot restore from own snapshot (base=%dMB, total=%dMB)", sandboxID, baseMem, meta.MemoryMB)} else {- incomingURI = fmt.Sprintf("exec:cat %s", goldenMemRaw)+ // Golden restore: use golden snapshot with default memory+ goldenMemZst := filepath.Join(m.goldenDir, "mem.zst")+ goldenMemRaw := filepath.Join(m.goldenDir, "mem")+ if fileExists(goldenMemZst) {+ incomingURI = fmt.Sprintf("exec:zstdcat %s", goldenMemZst)+ } else {+ incomingURI = fmt.Sprintf("exec:cat %s", goldenMemRaw)+ }+ log.Printf("qemu: wake %s: golden restore (base=%dMB)", sandboxID, baseMem)}+ args := m.buildQEMUArgs(meta.CpuCount, baseMem, rootfsPath, workspacePath,+ netCfg.TAPName, guestMAC, agentSockPath, qmpSockPath, bootArgs)args = append(args, "-incoming", incomingURI)cmd := exec.Command(m.cfg.QEMUBin, args...)@@ -466,6 +496,7 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, cEndAt: now.Add(ttl),CpuCount: meta.CpuCount,MemoryMB: meta.MemoryMB,+ baseMemoryMB: baseMem,HostPort: hostPort,GuestPort: netCfg.GuestPort,pid: cmd.Process.Pid,@@ -626,6 +657,7 @@ func (m *Manager) coldBootLocal(ctx context.Context, sandboxID string, timeout iEndAt: now.Add(ttl),CpuCount: cpus,MemoryMB: memMB,+ baseMemoryMB: memMB,HostPort: hostPort,GuestPort: guestPort,pid: cmd.Process.Pid,