An open-source, faster Devin alternative
TypeScript
prestage upgrade fix
Brian Reardon41f6fd329b90
diff --git a/cmd/agent/main.go b/cmd/agent/main.goindex 968e7bbc..fbfa0498 100644--- a/cmd/agent/main.go+++ b/cmd/agent/main.go@@ -1,8 +1,8 @@-// osb-agent is the sandbox agent that runs inside each Firecracker microVM.-// It listens for gRPC connections over vsock and handles exec, file ops,-// PTY sessions, and stats collection.+// osb-agent is the sandbox agent that runs inside each VM.+// It listens for gRPC connections over virtio-serial (QEMU) or vsock (Firecracker)+// and handles exec, file ops, PTY sessions, and stats collection.//-// Build: CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -o osb-agent ./cmd/agent+// Build: CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-X main.Version=$(git rev-parse --short HEAD)" -o osb-agent ./cmd/agentpackage mainimport (@@ -14,7 +14,8 @@ import ("github.com/opensandbox/opensandbox/internal/agent")-const version = "0.1.0"+// Version is set at build time via -ldflags "-X main.Version=xxx".+var Version = "dev"func main() {log.SetFlags(log.Ltime | log.Lmicroseconds)@@ -23,7 +24,7 @@ func main() {// 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)+ log.Printf("osb-agent %s starting", Version)// Listen on vsock port 1024 (inside Firecracker) or Unix socket (testing).lis, err := listenVsock()@@ -31,7 +32,7 @@ func main() {log.Fatalf("agent: failed to listen: %v", err)}- srv := agent.NewServer(version)+ srv := agent.NewServer(Version)// Only set ListenPort for vsock-based backends (Firecracker).// For virtio-serial (QEMU), PTY I/O flows over gRPC PTYAttach instead.if _, isVirtioSerial := lis.(*virtioSerialListener); !isVirtioSerial {diff --git a/cmd/worker/main.go b/cmd/worker/main.goindex 2c696eea..ac0ac217 100644--- a/cmd/worker/main.go+++ b/cmd/worker/main.go@@ -26,6 +26,9 @@ import (agentpb "github.com/opensandbox/opensandbox/proto/agent")+// AgentVersion is the expected agent version, set at build time via -ldflags.+var AgentVersion = "dev"+func main() {cfg, err := config.Load()if err != nil {@@ -71,6 +74,8 @@ func main() {KernelPath: cfg.KernelPath,ImagesDir: cfg.ImagesDir,QEMUBin: cfg.QEMUBin,+ AgentBinaryPath: "/usr/local/bin/osb-agent",+ AgentVersion: AgentVersion,DefaultMemoryMB: cfg.DefaultSandboxMemoryMB,DefaultCPUs: cfg.DefaultSandboxCPUs,DefaultDiskMB: cfg.DefaultSandboxDiskMB,diff --git a/deploy/ec2/build-rootfs-docker.sh b/deploy/ec2/build-rootfs-docker.shindex e43317e0..d408b18c 100755--- a/deploy/ec2/build-rootfs-docker.sh+++ b/deploy/ec2/build-rootfs-docker.sh@@ -210,7 +210,7 @@ INJECT_EOF# Build with Dockerlog "Building container image..."-docker build -t "osb-rootfs-${IMAGE_NAME}:build" -f "$TMPDIR/Dockerfile" "$TMPDIR"+docker build --no-cache -t "osb-rootfs-${IMAGE_NAME}:build" -f "$TMPDIR/Dockerfile" "$TMPDIR"# Create container and export filesystemlog "Exporting filesystem..."diff --git a/internal/agent/server.go b/internal/agent/server.goindex ac6a22b5..ed50631f 100644--- a/internal/agent/server.go+++ b/internal/agent/server.go@@ -5,9 +5,13 @@package agentimport (+ "context"+ "fmt""log""net"+ "os""sync"+ "syscall""time"pb "github.com/opensandbox/opensandbox/proto/agent"@@ -96,3 +100,56 @@ func (s *Server) GracefulStop() {gs.GracefulStop()}}++// GetVersion returns the agent's build version.+func (s *Server) GetVersion(ctx context.Context, req *pb.GetVersionRequest) (*pb.GetVersionResponse, error) {+ return &pb.GetVersionResponse{Version: s.version}, nil+}++// Upgrade replaces the agent binary on disk and re-execs the process.+// The new binary must already be written to req.BinaryPath by the worker.+// syscall.Exec replaces the process in-place — same PID 1, same cgroup,+// user processes are unaffected. The gRPC connection drops and the worker reconnects.+func (s *Server) Upgrade(ctx context.Context, req *pb.UpgradeRequest) (*pb.UpgradeResponse, error) {+ src := req.BinaryPath+ dst := "/usr/local/bin/osb-agent"++ // Validate the new binary exists and is executable+ info, err := os.Stat(src)+ if err != nil {+ return nil, fmt.Errorf("new binary not found at %s: %w", src, err)+ }+ if info.Size() < 1024 {+ return nil, fmt.Errorf("new binary too small (%d bytes), likely corrupt", info.Size())+ }++ // Replace the running binary. Linux allows unlinking a running executable+ // (the kernel keeps the inode alive until the process exits), so we remove+ // first, then rename the new binary into place.+ os.Remove(dst) // unlink running binary (safe on Linux)+ if err := os.Rename(src, dst); err != nil {+ // Rename fails across filesystems — fall back to copy+ data, readErr := os.ReadFile(src)+ if readErr != nil {+ return nil, fmt.Errorf("read new binary: %w", readErr)+ }+ if writeErr := os.WriteFile(dst, data, 0755); writeErr != nil {+ return nil, fmt.Errorf("write new binary: %w", writeErr)+ }+ os.Remove(src)+ }+ os.Chmod(dst, 0755)++ log.Printf("agent: upgrade scheduled (%s → %s)", src, dst)++ // Schedule re-exec after we return the response+ go func() {+ time.Sleep(200 * time.Millisecond) // let gRPC response flush+ log.Printf("agent: re-execing %s", dst)+ syscall.Exec(dst, os.Args, os.Environ())+ // If Exec fails, we're still running the old binary — log and continue+ log.Printf("agent: WARNING: exec failed, continuing with old binary")+ }()++ return &pb.UpgradeResponse{Ok: true}, nil+}diff --git a/internal/qemu/agent_client.go b/internal/qemu/agent_client.goindex bcc7329c..8239b673 100644--- a/internal/qemu/agent_client.go+++ b/internal/qemu/agent_client.go@@ -259,6 +259,32 @@ func (c *AgentClient) SyncFS(ctx context.Context) error {return err}+// WriteFileBinary writes binary content to a path inside the VM.+func (c *AgentClient) WriteFileBinary(ctx context.Context, path string, content []byte, mode uint32) error {+ _, err := c.client.WriteFile(ctx, &pb.WriteFileRequest{+ Path: path,+ Content: content,+ Mode: mode,+ })+ return err+}++// GetVersion returns the agent's build version.+func (c *AgentClient) GetVersion(ctx context.Context) (string, error) {+ resp, err := c.client.GetVersion(ctx, &pb.GetVersionRequest{})+ if err != nil {+ return "", err+ }+ return resp.Version, nil+}++// Upgrade tells the agent to replace its binary and re-exec.+// The new binary must already be written to binaryPath inside the VM.+func (c *AgentClient) Upgrade(ctx context.Context, binaryPath string) error {+ _, err := c.client.Upgrade(ctx, &pb.UpgradeRequest{BinaryPath: binaryPath})+ 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{diff --git a/internal/qemu/manager.go b/internal/qemu/manager.goindex 915209f7..45d610f6 100644--- a/internal/qemu/manager.go+++ b/internal/qemu/manager.go@@ -7,12 +7,14 @@ import ("context""encoding/json""fmt"+ "io""log""os""os/exec""path/filepath""strings""sync"+ "syscall""time""github.com/google/uuid"@@ -53,8 +55,8 @@ type VMInstance struct {guestCID uint32bootArgs stringrestoring chan struct{}- baseMemoryMB int // initial memory passed to -m (before virtio-mem)- virtioMemRequestedMB int // additional memory via virtio-mem (beyond base)+ 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.@@ -92,6 +94,8 @@ type Config struct {KernelPath string // path to vmlinux kernelImagesDir string // path to base rootfs imagesQEMUBin string // path to qemu-system-x86_64 binary+ AgentBinaryPath string // path to osb-agent binary on host (for hot-upgrade)+ AgentVersion string // expected agent version (for hot-upgrade check)DefaultMemoryMB intDefaultCPUs intDefaultDiskMB int@@ -1607,6 +1611,9 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID}// Sync filesystem and quiesce agent before snapshot.+ // Don't unmount /workspace — open FDs prevent clean unmount, and forcing it+ // corrupts the ext4 journal. Just sync to flush dirty pages, then savevm+ // captures a consistent state.// SIGUSR1 resets the virtio-serial listener's active flag so that// restores from this checkpoint (loadvm or fork) have a clean agent// that immediately accepts the new host-side connection.@@ -1614,7 +1621,7 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointIDsyncCtx, cancel := context.WithTimeout(ctx, 10*time.Second)_, syncErr := vm.agent.Exec(syncCtx, &pb.ExecRequest{Command: "/bin/sh",- Args: []string{"-c", "umount /workspace 2>/dev/null; sync; kill -USR1 1"},+ Args: []string{"-c", "sync; kill -USR1 1"},})cancel()if syncErr != nil {@@ -1644,12 +1651,6 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID}if reconnErr == nil {vm.agent = agentClient- mountCtx, mountCancel := context.WithTimeout(context.Background(), 5*time.Second)- _, _ = agentClient.Exec(mountCtx, &pb.ExecRequest{- Command: "/bin/sh",- Args: []string{"-c", "echo 3 > /proc/sys/vm/drop_caches; mount /dev/vdb /workspace 2>/dev/null || true"},- })- mountCancel()}// Cache the drive files for ForkFromCheckpoint (which needs a separate QEMU process).@@ -1696,8 +1697,10 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointIDreturn rootfsKey, workspaceKey, nil}-// RestoreFromCheckpoint reverts a running sandbox to a checkpoint using QEMU's loadvm.-// The VM stays running — no process restart needed. ~100-200ms.+// RestoreFromCheckpoint reverts a sandbox to a checkpoint by killing the current+// QEMU process and starting a fresh one from the checkpoint's cached qcow2 drives.+// In-place loadvm corrupts the qcow2 COW layer because blocks written after the+// checkpoint aren't cleanly reverted. Fresh drives from the cache are always consistent.func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpointID string) error {vm, err := m.getVM(sandboxID)if err != nil {@@ -1706,57 +1709,184 @@ func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpoit0 := time.Now()- if vm.qmp == nil {- return fmt.Errorf("no QMP client for VM %s", sandboxID)- }-- snapshotName := "cp-" + checkpointID-- // Close agent before loadvm — the checkpoint was created with the agent- // in a quiesced state (SIGUSR1 sent during CreateCheckpoint), so after- // loadvm the restored agent will immediately accept a new connection.+ // Step 1: Kill the current VMif vm.agent != nil {vm.agent.Close()vm.agent = nil}+ if vm.qmp != nil {+ _ = vm.qmp.Quit()+ vm.qmp.Close()+ vm.qmp = nil+ }+ 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+ }+ }- // Stop the VM before loadvm (QEMU requires it)- if err := vm.qmp.Stop(); err != nil {- log.Printf("qemu: RestoreFromCheckpoint %s: stop failed: %v", sandboxID, err)+ // Step 2: Tear down old network+ if vm.network != nil {+ RemoveMetadataDNAT(vm.network.TAPName, vm.network.HostIP)+ RemoveDNAT(vm.network)+ DeleteTAP(vm.network.TAPName)+ m.subnets.Release(vm.network.TAPName)}- // loadvm reverts the entire VM state — memory, devices, and disk contents- if err := vm.qmp.LoadVM(snapshotName); err != nil {- // Resume the VM if loadvm fails- vm.qmp.Cont()- return fmt.Errorf("loadvm failed: %w", err)+ // Step 3: Copy fresh qcow2 drives from checkpoint cache+ m.checkpointCacheMu.RLock()+ cacheDir := m.checkpointCacheDir(checkpointID)+ cachedRootfs := filepath.Join(cacheDir, "rootfs.qcow2")+ cachedWorkspace := filepath.Join(cacheDir, "workspace.qcow2")+ if !fileExists(cachedRootfs) || !fileExists(cachedWorkspace) {+ m.checkpointCacheMu.RUnlock()+ return fmt.Errorf("checkpoint %s: qcow2 files not found in cache", checkpointID)}- // Resume after loadvm- if err := vm.qmp.Cont(); err != nil {- return fmt.Errorf("cont after loadvm failed: %w", err)+ snapshotName := "cp-" + checkpointID+ if data, err := os.ReadFile(filepath.Join(cacheDir, "snapshot-name")); err == nil {+ snapshotName = strings.TrimSpace(string(data))}- // Reconnect agent via Unix socket- agent, err := m.waitForAgentSocket(context.Background(), vm.agentSockPath, 10*time.Second)+ sandboxDir := vm.sandboxDir+ rootfsPath := filepath.Join(sandboxDir, "rootfs.qcow2")+ workspacePath := filepath.Join(sandboxDir, "workspace.qcow2")++ // Remove old drives and copy fresh ones+ os.Remove(rootfsPath)+ os.Remove(workspacePath)+ if err := copyFileReflink(cachedRootfs, rootfsPath); err != nil {+ m.checkpointCacheMu.RUnlock()+ return fmt.Errorf("copy rootfs from cache: %w", err)+ }+ if err := copyFileReflink(cachedWorkspace, workspacePath); err != nil {+ m.checkpointCacheMu.RUnlock()+ return fmt.Errorf("copy workspace from cache: %w", err)+ }+ m.checkpointCacheMu.RUnlock()++ // Pre-stage agent binary into rootfs qcow2 before QEMU boots.+ // This avoids in-VM binary transfer — the VM boots with the correct agent.+ m.prestageAgentBinary(sandboxID, rootfsPath)++ // Step 4: Allocate new network+ netCfg, err := m.subnets.Allocate()if err != nil {- return fmt.Errorf("agent reconnect after loadvm: %w", err)+ return fmt.Errorf("allocate subnet: %w", err)+ }+ if err := CreateTAP(netCfg); err != nil {+ m.subnets.Release(netCfg.TAPName)+ return fmt.Errorf("create TAP: %w", err)+ }+ hostPort, err := FindFreePort()+ if err != nil {+ DeleteTAP(netCfg.TAPName)+ m.subnets.Release(netCfg.TAPName)+ return fmt.Errorf("find free port: %w", err)+ }+ netCfg.HostPort = hostPort+ netCfg.GuestPort = vm.GuestPort+ if err := AddDNAT(netCfg); err != nil {+ DeleteTAP(netCfg.TAPName)+ m.subnets.Release(netCfg.TAPName)+ return fmt.Errorf("add DNAT: %w", err)+ }+ if err := AddMetadataDNAT(netCfg.TAPName, netCfg.HostIP); err != nil {+ log.Printf("qemu: RestoreFromCheckpoint %s: metadata DNAT failed: %v", sandboxID, err)}- vm.agent = agent- // Remount workspace + drop caches (loadvm reverted to checkpoint state)- restoreCtx, restoreCancel := context.WithTimeout(context.Background(), 5*time.Second)- _, _ = agent.Exec(restoreCtx, &pb.ExecRequest{- Command: "/bin/sh",- Args: []string{"-c", "echo 3 > /proc/sys/vm/drop_caches; mount /dev/vdb /workspace 2>/dev/null || true"},- })- restoreCancel()+ // Step 5: Start fresh QEMU paused+ 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,+ )- if err := syncGuestClock(context.Background(), agent); err != nil {+ qmpSockPath := filepath.Join(sandboxDir, "qmp.sock")+ agentSockPath := filepath.Join(sandboxDir, "agent.sock")+ os.Remove(qmpSockPath)+ os.Remove(agentSockPath)++ logFile, _ := os.Create(filepath.Join(sandboxDir, "qemu.log"))+ args := m.buildQEMUArgs(vm.CpuCount, vm.MemoryMB, rootfsPath, workspacePath,+ netCfg.TAPName, guestMAC, agentSockPath, qmpSockPath, bootArgs)+ args = append(args, "-S")++ cmd := exec.Command(m.cfg.QEMUBin, args...)+ cmd.Stdout = logFile+ cmd.Stderr = logFile+ if err := cmd.Start(); err != nil {+ if logFile != nil {+ logFile.Close()+ }+ m.cleanupVM(netCfg, "")+ return fmt.Errorf("start QEMU: %w", err)+ }+ if logFile != nil {+ logFile.Close()+ }++ // Step 6: QMP connect + loadvm + cont+ qmpClient, err := waitForQMP(qmpSockPath, 10*time.Second)+ if err != nil {+ cmd.Process.Kill()+ cmd.Wait()+ m.cleanupVM(netCfg, "")+ return fmt.Errorf("QMP connect: %w", err)+ }++ if err := qmpClient.LoadVM(snapshotName); err != nil {+ qmpClient.Close()+ cmd.Process.Kill()+ cmd.Wait()+ m.cleanupVM(netCfg, "")+ return fmt.Errorf("loadvm: %w", err)+ }++ if err := qmpClient.Cont(); err != nil {+ qmpClient.Close()+ cmd.Process.Kill()+ cmd.Wait()+ m.cleanupVM(netCfg, "")+ return fmt.Errorf("cont: %w", err)+ }++ // Step 7: Reconnect agent + patch network+ agentClient, err := m.waitForAgentSocket(context.Background(), agentSockPath, 10*time.Second)+ if err != nil {+ qmpClient.Close()+ cmd.Process.Kill()+ cmd.Wait()+ m.cleanupVM(netCfg, "")+ return fmt.Errorf("agent connect: %w", err)+ }++ if err := patchGuestNetwork(context.Background(), agentClient, netCfg); err != nil {+ log.Printf("qemu: RestoreFromCheckpoint %s: network patch failed: %v", sandboxID, err)+ }+ if err := syncGuestClock(context.Background(), agentClient); err != nil {log.Printf("qemu: RestoreFromCheckpoint %s: clock sync failed: %v", sandboxID, err)}- log.Printf("qemu: RestoreFromCheckpoint %s/%s: loadvm complete (%dms)", sandboxID, checkpointID, time.Since(t0).Milliseconds())+ // Step 8: Update VM instance+ vm.cmd = cmd+ vm.qmp = qmpClient+ vm.agent = agentClient+ vm.network = netCfg+ vm.HostPort = hostPort+ vm.qmpSockPath = qmpSockPath+ vm.agentSockPath = agentSockPath+ vm.guestMAC = guestMAC+ vm.bootArgs = bootArgs+ vm.pid = cmd.Process.Pid++ log.Printf("qemu: RestoreFromCheckpoint %s/%s: complete (%dms, port=%d, tap=%s)",+ sandboxID, checkpointID, time.Since(t0).Milliseconds(), hostPort, netCfg.TAPName)return nil}@@ -1935,14 +2065,10 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, creturn nil, fmt.Errorf("agent connect: %w", err)}- // Drop caches (checkpoint had different rootfs state) + mount workspace + patch network- postCtx, postCancel := context.WithTimeout(context.Background(), 10*time.Second)- _, _ = agent.Exec(postCtx, &pb.ExecRequest{- Command: "/bin/sh",- Args: []string{"-c", "echo 3 > /proc/sys/vm/drop_caches; mount /dev/vdb /workspace 2>/dev/null || true"},- })- postCancel()-+ // Patch network (fork gets new IPs) + sync clock+ if err := patchGuestNetwork(context.Background(), agent, netCfg); err != nil {+ log.Printf("qemu: ForkFromCheckpoint %s: network patch failed: %v", id, err)+ }if err := syncGuestClock(context.Background(), agent); err != nil {log.Printf("qemu: ForkFromCheckpoint %s: clock sync failed: %v", id, err)}@@ -2214,3 +2340,154 @@ func (m *Manager) RecoverLocalSandboxes() []LocalRecovery {}return recoveries}++// prestageAgentBinary replaces the agent binary inside a rootfs qcow2 image+// BEFORE QEMU boots. Uses qemu-nbd to mount the qcow2 on the host, copies+// the new binary, and unmounts. The VM then boots with the correct agent —+// no in-VM transfer, no gRPC overhead, no contention issues.+//+// This must be called before startQEMU, while the qcow2 is not in use.+// If the agent binary path or version is not configured, this is a no-op.+func (m *Manager) prestageAgentBinary(sandboxID, rootfsPath string) {+ if m.cfg.AgentVersion == "" || m.cfg.AgentVersion == "dev" || m.cfg.AgentBinaryPath == "" {+ return+ }+ if !fileExists(m.cfg.AgentBinaryPath) {+ return+ }++ t0 := time.Now()++ // Find a free /dev/nbdN device. We use a per-sandbox temp dir for the mount.+ nbdDev, err := findFreeNBD()+ if err != nil {+ log.Printf("qemu: prestage %s: no free nbd device: %v (skipping)", sandboxID, err)+ return+ }++ // Connect qcow2 to NBD device+ connectCmd := exec.Command("qemu-nbd", "--connect", nbdDev, "--format", "qcow2", rootfsPath)+ if out, err := connectCmd.CombinedOutput(); err != nil {+ log.Printf("qemu: prestage %s: qemu-nbd connect failed: %v (%s)", sandboxID, err, strings.TrimSpace(string(out)))+ return+ }+ // Always disconnect NBD when done+ defer func() {+ exec.Command("qemu-nbd", "--disconnect", nbdDev).Run()+ }()++ // Brief pause to let the kernel register the block device+ time.Sleep(200 * time.Millisecond)++ // Mount the rootfs partition+ mountDir := filepath.Join(os.TempDir(), "osb-prestage-"+sandboxID)+ os.MkdirAll(mountDir, 0755)+ defer os.RemoveAll(mountDir)++ mountCmd := exec.Command("mount", "-o", "rw", nbdDev, mountDir)+ if out, err := mountCmd.CombinedOutput(); err != nil {+ // Try partition 1 if the whole device didn't work+ mountCmd = exec.Command("mount", "-o", "rw", nbdDev+"p1", mountDir)+ if out2, err2 := mountCmd.CombinedOutput(); err2 != nil {+ log.Printf("qemu: prestage %s: mount failed: %v (%s / %s)", sandboxID, err, strings.TrimSpace(string(out)), strings.TrimSpace(string(out2)))+ return+ }+ }+ defer exec.Command("umount", mountDir).Run()++ // Check current agent version inside the image+ agentPath := filepath.Join(mountDir, "usr/local/bin/osb-agent")+ needsUpdate := true++ // Quick version check: run the existing agent with a version flag if possible,+ // or just compare file sizes as a heuristic. For reliability, always overwrite+ // if we can't confirm the version matches.+ hostInfo, err := os.Stat(m.cfg.AgentBinaryPath)+ if err == nil {+ guestInfo, gErr := os.Stat(agentPath)+ if gErr == nil && guestInfo.Size() == hostInfo.Size() {+ // Same size — likely same binary, skip copy+ needsUpdate = false+ }+ }++ if !needsUpdate {+ log.Printf("qemu: prestage %s: agent binary already up-to-date (skipping, %dms)", sandboxID, time.Since(t0).Milliseconds())+ return+ }++ // Copy the new agent binary+ if err := copyFile(m.cfg.AgentBinaryPath, agentPath); err != nil {+ log.Printf("qemu: prestage %s: copy agent failed: %v", sandboxID, err)+ return+ }+ os.Chmod(agentPath, 0755)++ log.Printf("qemu: prestage %s: agent binary updated in rootfs (%dms)", sandboxID, time.Since(t0).Milliseconds())+}++// findFreeNBD finds an unused /dev/nbdN device.+func findFreeNBD() (string, error) {+ // Ensure nbd module is loaded+ exec.Command("modprobe", "nbd", "max_part=8").Run()++ for i := 0; i < 16; i++ {+ dev := fmt.Sprintf("/dev/nbd%d", i)+ if _, err := os.Stat(dev); err != nil {+ continue+ }+ // Check if it's in use by reading the size — unused NBD devices report 0+ sizeFile := fmt.Sprintf("/sys/block/nbd%d/size", i)+ data, err := os.ReadFile(sizeFile)+ if err != nil {+ continue+ }+ if strings.TrimSpace(string(data)) == "0" {+ return dev, nil+ }+ }+ return "", fmt.Errorf("all /dev/nbd[0-15] devices in use")+}++// copyFile copies src to dst using io.Copy.+func copyFile(src, dst string) error {+ in, err := os.Open(src)+ if err != nil {+ return err+ }+ defer in.Close()++ out, err := os.Create(dst)+ if err != nil {+ return err+ }+ defer out.Close()++ if _, err := io.Copy(out, in); err != nil {+ return err+ }+ return out.Close()+}++// dropPageCache evicts a file's pages from the kernel page cache.+// After loadvm reverts qcow2 internal state, the host page cache may hold+// stale blocks. POSIX_FADV_DONTNEED tells the kernel to release them.+func dropPageCache(path string) {+ f, err := os.Open(path)+ if err != nil {+ return+ }+ defer f.Close()+ info, err := f.Stat()+ if err != nil {+ return+ }+ // POSIX_FADV_DONTNEED = 4 on Linux+ const FADV_DONTNEED = 4+ // SYS_FADVISE64 = 221 on x86_64+ const SYS_FADVISE64 = 221+ _, _, errno := syscall.Syscall6(SYS_FADVISE64, f.Fd(), 0, uintptr(info.Size()), FADV_DONTNEED, 0, 0)+ if errno != 0 {+ log.Printf("qemu: dropPageCache %s: fadvise failed: %v", path, errno)+ }+}diff --git a/internal/qemu/snapshot.go b/internal/qemu/snapshot.goindex c0bcf391..f2331d06 100644--- a/internal/qemu/snapshot.go+++ b/internal/qemu/snapshot.go@@ -57,16 +57,15 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointStoreturn nil, fmt.Errorf("mkdir snapshot dir: %w", err)}- // Step 1: Sync filesystems, unmount workspace, quiesce agent.- // Send SIGUSR1 to PID 1 (agent) which calls PrepareHibernate() to reset- // the virtio-serial listener's active flag. This ensures savevm captures- // the agent in a clean "waiting for connection" state so loadvm on wake- // gets instant reconnection instead of waiting ~4s for gRPC timeout.+ // Step 1: Sync filesystems and quiesce agent.+ // Don't unmount /workspace — open FDs prevent clean unmount and cause ext4 corruption.+ // Just sync to flush dirty pages. savevm captures a consistent snapshot.+ // SIGUSR1 resets the virtio-serial listener for instant reconnection on wake.if vm.agent != nil {shutdownCtx, cancel := context.WithTimeout(ctx, 10*time.Second)_, _ = vm.agent.Exec(shutdownCtx, &pb.ExecRequest{Command: "/bin/sh",- Args: []string{"-c", "umount /workspace 2>/dev/null; sync; kill -USR1 1"},+ Args: []string{"-c", "sync; kill -USR1 1"},})cancel()vm.agent.Close()@@ -110,6 +109,8 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointSto<-done}}+ // Brief pause to ensure qcow2 file locks are released after QEMU exit+ time.Sleep(200 * time.Millisecond)// Step 4: Write snapshot metadatameta := &SnapshotMeta{@@ -286,6 +287,9 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, creturn nil, fmt.Errorf("workspace not found at %s", workspacePath)}+ // Pre-stage agent binary into rootfs before QEMU boots.+ m.prestageAgentBinary(sandboxID, rootfsPath)+// Step 3: Set up networknetCfg, err := m.subnets.Allocate()if err != nil {@@ -360,7 +364,7 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, clogFile.Close()// Step 5: Connect QMP, loadvm, cont — same as RestoreFromCheckpoint- qmpClient, err := waitForQMP(qmpSockPath, 10*time.Second)+ qmpClient, err := waitForQMP(qmpSockPath, 30*time.Second)if err != nil {cmd.Process.Kill()cmd.Wait()@@ -454,7 +458,7 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, cm.onSandboxReady(sandboxID, netCfg.GuestIP, vm.Template, vm.StartedAt)}- log.Printf("qemu: woke VM %s (cold boot, port=%d, tap=%s)",+ log.Printf("qemu: woke VM %s (port=%d, tap=%s)",sandboxID, hostPort, netCfg.TAPName)return vmToSandbox(vm), nil}@@ -490,6 +494,9 @@ func (m *Manager) coldBootLocal(ctx context.Context, sandboxID string, timeout ilog.Printf("qemu: cold-boot-local %s: rootfs recreated from template %q", sandboxID, meta.Template)}+ // Pre-stage agent binary into rootfs before QEMU boots.+ m.prestageAgentBinary(sandboxID, rootfsPath)+netCfg, err := m.subnets.Allocate()if err != nil {return nil, fmt.Errorf("allocate subnet: %w", err)diff --git a/proto/agent/agent.pb.go b/proto/agent/agent.pb.goindex 6d17cf52..3270ecf8 100644--- a/proto/agent/agent.pb.go+++ b/proto/agent/agent.pb.go@@ -2485,6 +2485,174 @@ func (*SetResourceLimitsResponse) Descriptor() ([]byte, []int) {return file_proto_agent_agent_proto_rawDescGZIP(), []int{46}}+type GetVersionRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *GetVersionRequest) Reset() {+ *x = GetVersionRequest{}+ mi := &file_proto_agent_agent_proto_msgTypes[47]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *GetVersionRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*GetVersionRequest) ProtoMessage() {}++func (x *GetVersionRequest) ProtoReflect() protoreflect.Message {+ mi := &file_proto_agent_agent_proto_msgTypes[47]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use GetVersionRequest.ProtoReflect.Descriptor instead.+func (*GetVersionRequest) Descriptor() ([]byte, []int) {+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{47}+}++type GetVersionResponse struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Version string `protobuf:"bytes,1,opt,name=version,proto3" json:"version,omitempty"` // build version (git SHA or build timestamp)+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *GetVersionResponse) Reset() {+ *x = GetVersionResponse{}+ mi := &file_proto_agent_agent_proto_msgTypes[48]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *GetVersionResponse) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*GetVersionResponse) ProtoMessage() {}++func (x *GetVersionResponse) ProtoReflect() protoreflect.Message {+ mi := &file_proto_agent_agent_proto_msgTypes[48]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use GetVersionResponse.ProtoReflect.Descriptor instead.+func (*GetVersionResponse) Descriptor() ([]byte, []int) {+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{48}+}++func (x *GetVersionResponse) GetVersion() string {+ if x != nil {+ return x.Version+ }+ return ""+}++type UpgradeRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ BinaryPath string `protobuf:"bytes,1,opt,name=binary_path,json=binaryPath,proto3" json:"binary_path,omitempty"` // path to new agent binary inside the VM+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *UpgradeRequest) Reset() {+ *x = UpgradeRequest{}+ mi := &file_proto_agent_agent_proto_msgTypes[49]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *UpgradeRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*UpgradeRequest) ProtoMessage() {}++func (x *UpgradeRequest) ProtoReflect() protoreflect.Message {+ mi := &file_proto_agent_agent_proto_msgTypes[49]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use UpgradeRequest.ProtoReflect.Descriptor instead.+func (*UpgradeRequest) Descriptor() ([]byte, []int) {+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{49}+}++func (x *UpgradeRequest) GetBinaryPath() string {+ if x != nil {+ return x.BinaryPath+ }+ return ""+}++type UpgradeResponse struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Ok bool `protobuf:"varint,1,opt,name=ok,proto3" json:"ok,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *UpgradeResponse) Reset() {+ *x = UpgradeResponse{}+ mi := &file_proto_agent_agent_proto_msgTypes[50]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *UpgradeResponse) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*UpgradeResponse) ProtoMessage() {}++func (x *UpgradeResponse) ProtoReflect() protoreflect.Message {+ mi := &file_proto_agent_agent_proto_msgTypes[50]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use UpgradeResponse.ProtoReflect.Descriptor instead.+func (*UpgradeResponse) Descriptor() ([]byte, []int) {+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{50}+}++func (x *UpgradeResponse) GetOk() bool {+ if x != nil {+ return x.Ok+ }+ return false+}+var File_proto_agent_agent_proto protoreflect.FileDescriptorconst file_proto_agent_agent_proto_rawDesc = "" +@@ -2653,7 +2821,15 @@ const file_proto_agent_agent_proto_rawDesc = "" +"\fcpu_max_usec\x18\x03 \x01(\x03R\n" +"cpuMaxUsec\x12&\n" +"\x0fcpu_period_usec\x18\x04 \x01(\x03R\rcpuPeriodUsec\"\x1b\n" +- "\x19SetResourceLimitsResponse2\xac\v\n" ++ "\x19SetResourceLimitsResponse\"\x13\n" ++ "\x11GetVersionRequest\".\n" ++ "\x12GetVersionResponse\x12\x18\n" ++ "\aversion\x18\x01 \x01(\tR\aversion\"1\n" ++ "\x0eUpgradeRequest\x12\x1f\n" ++ "\vbinary_path\x18\x01 \x01(\tR\n" ++ "binaryPath\"!\n" ++ "\x0fUpgradeResponse\x12\x0e\n" ++ "\x02ok\x18\x01 \x01(\bR\x02ok2\xa9\f\n" +"\fSandboxAgent\x12/\n" +"\x04Exec\x12\x12.agent.ExecRequest\x1a\x13.agent.ExecResponse\x12:\n" +"\n" +@@ -2678,7 +2854,10 @@ const file_proto_agent_agent_proto_rawDesc = "" +"\aSetEnvs\x12\x15.agent.SetEnvsRequest\x1a\x16.agent.SetEnvsResponse\x12;\n" +"\bShutdown\x12\x16.agent.ShutdownRequest\x1a\x17.agent.ShutdownResponse\x125\n" +"\x06SyncFS\x12\x14.agent.SyncFSRequest\x1a\x15.agent.SyncFSResponse\x12V\n" +- "\x11SetResourceLimits\x12\x1f.agent.SetResourceLimitsRequest\x1a .agent.SetResourceLimitsResponseB0Z.github.com/opensandbox/opensandbox/proto/agentb\x06proto3"+ "\x11SetResourceLimits\x12\x1f.agent.SetResourceLimitsRequest\x1a .agent.SetResourceLimitsResponse\x12A\n" ++ "\n" ++ "GetVersion\x12\x18.agent.GetVersionRequest\x1a\x19.agent.GetVersionResponse\x128\n" ++ "\aUpgrade\x12\x15.agent.UpgradeRequest\x1a\x16.agent.UpgradeResponseB0Z.github.com/opensandbox/opensandbox/proto/agentb\x06proto3"var (file_proto_agent_agent_proto_rawDescOnce sync.Once@@ -2693,7 +2872,7 @@ func file_proto_agent_agent_proto_rawDescGZIP() []byte {}var file_proto_agent_agent_proto_enumTypes = make([]protoimpl.EnumInfo, 2)-var file_proto_agent_agent_proto_msgTypes = make([]protoimpl.MessageInfo, 50)+var file_proto_agent_agent_proto_msgTypes = make([]protoimpl.MessageInfo, 54)var file_proto_agent_agent_proto_goTypes = []any{(ExecOutputChunk_Stream)(0), // 0: agent.ExecOutputChunk.Stream(ExecSessionOutput_Type)(0), // 1: agent.ExecSessionOutput.Type@@ -2744,18 +2923,22 @@ var file_proto_agent_agent_proto_goTypes = []any{(*SyncFSResponse)(nil), // 46: agent.SyncFSResponse(*SetResourceLimitsRequest)(nil), // 47: agent.SetResourceLimitsRequest(*SetResourceLimitsResponse)(nil), // 48: agent.SetResourceLimitsResponse- nil, // 49: agent.ExecRequest.EnvsEntry- nil, // 50: agent.ExecSessionCreateRequest.EnvsEntry- nil, // 51: agent.SetEnvsRequest.EnvsEntry+ (*GetVersionRequest)(nil), // 49: agent.GetVersionRequest+ (*GetVersionResponse)(nil), // 50: agent.GetVersionResponse+ (*UpgradeRequest)(nil), // 51: agent.UpgradeRequest+ (*UpgradeResponse)(nil), // 52: agent.UpgradeResponse+ nil, // 53: agent.ExecRequest.EnvsEntry+ nil, // 54: agent.ExecSessionCreateRequest.EnvsEntry+ nil, // 55: agent.SetEnvsRequest.EnvsEntry}var file_proto_agent_agent_proto_depIdxs = []int32{- 49, // 0: agent.ExecRequest.envs:type_name -> agent.ExecRequest.EnvsEntry+ 53, // 0: agent.ExecRequest.envs:type_name -> agent.ExecRequest.EnvsEntry0, // 1: agent.ExecOutputChunk.stream:type_name -> agent.ExecOutputChunk.Stream10, // 2: agent.ListDirResponse.entries:type_name -> agent.DirEntry- 50, // 3: agent.ExecSessionCreateRequest.envs:type_name -> agent.ExecSessionCreateRequest.EnvsEntry+ 54, // 3: agent.ExecSessionCreateRequest.envs:type_name -> agent.ExecSessionCreateRequest.EnvsEntry1, // 4: agent.ExecSessionOutput.type:type_name -> agent.ExecSessionOutput.Type38, // 5: agent.ExecSessionListResponse.sessions:type_name -> agent.ExecSessionInfo- 51, // 6: agent.SetEnvsRequest.envs:type_name -> agent.SetEnvsRequest.EnvsEntry+ 55, // 6: agent.SetEnvsRequest.envs:type_name -> agent.SetEnvsRequest.EnvsEntry2, // 7: agent.SandboxAgent.Exec:input_type -> agent.ExecRequest2, // 8: agent.SandboxAgent.ExecStream:input_type -> agent.ExecRequest5, // 9: agent.SandboxAgent.ReadFile:input_type -> agent.ReadFileRequest@@ -2779,31 +2962,35 @@ var file_proto_agent_agent_proto_depIdxs = []int32{43, // 27: agent.SandboxAgent.Shutdown:input_type -> agent.ShutdownRequest45, // 28: agent.SandboxAgent.SyncFS:input_type -> agent.SyncFSRequest47, // 29: agent.SandboxAgent.SetResourceLimits:input_type -> agent.SetResourceLimitsRequest- 3, // 30: agent.SandboxAgent.Exec:output_type -> agent.ExecResponse- 4, // 31: agent.SandboxAgent.ExecStream:output_type -> agent.ExecOutputChunk- 6, // 32: agent.SandboxAgent.ReadFile:output_type -> agent.ReadFileResponse- 8, // 33: agent.SandboxAgent.WriteFile:output_type -> agent.WriteFileResponse- 11, // 34: agent.SandboxAgent.ListDir:output_type -> agent.ListDirResponse- 13, // 35: agent.SandboxAgent.MakeDir:output_type -> agent.MakeDirResponse- 15, // 36: agent.SandboxAgent.Remove:output_type -> agent.RemoveResponse- 17, // 37: agent.SandboxAgent.Exists:output_type -> agent.ExistsResponse- 19, // 38: agent.SandboxAgent.Stat:output_type -> agent.StatResponse- 21, // 39: agent.SandboxAgent.Stats:output_type -> agent.StatsResponse- 23, // 40: agent.SandboxAgent.Ping:output_type -> agent.PingResponse- 25, // 41: agent.SandboxAgent.PTYCreate:output_type -> agent.PTYCreateResponse- 27, // 42: agent.SandboxAgent.PTYResize:output_type -> agent.PTYResizeResponse- 29, // 43: agent.SandboxAgent.PTYKill:output_type -> agent.PTYKillResponse- 31, // 44: agent.SandboxAgent.PTYAttach:output_type -> agent.PTYOutput- 33, // 45: agent.SandboxAgent.ExecSessionCreate:output_type -> agent.ExecSessionCreateResponse- 35, // 46: agent.SandboxAgent.ExecSessionAttach:output_type -> agent.ExecSessionOutput- 37, // 47: agent.SandboxAgent.ExecSessionList:output_type -> agent.ExecSessionListResponse- 40, // 48: agent.SandboxAgent.ExecSessionKill:output_type -> agent.ExecSessionKillResponse- 42, // 49: agent.SandboxAgent.SetEnvs:output_type -> agent.SetEnvsResponse- 44, // 50: agent.SandboxAgent.Shutdown:output_type -> agent.ShutdownResponse- 46, // 51: agent.SandboxAgent.SyncFS:output_type -> agent.SyncFSResponse- 48, // 52: agent.SandboxAgent.SetResourceLimits:output_type -> agent.SetResourceLimitsResponse- 30, // [30:53] is the sub-list for method output_type- 7, // [7:30] is the sub-list for method input_type+ 49, // 30: agent.SandboxAgent.GetVersion:input_type -> agent.GetVersionRequest+ 51, // 31: agent.SandboxAgent.Upgrade:input_type -> agent.UpgradeRequest+ 3, // 32: agent.SandboxAgent.Exec:output_type -> agent.ExecResponse+ 4, // 33: agent.SandboxAgent.ExecStream:output_type -> agent.ExecOutputChunk+ 6, // 34: agent.SandboxAgent.ReadFile:output_type -> agent.ReadFileResponse+ 8, // 35: agent.SandboxAgent.WriteFile:output_type -> agent.WriteFileResponse+ 11, // 36: agent.SandboxAgent.ListDir:output_type -> agent.ListDirResponse+ 13, // 37: agent.SandboxAgent.MakeDir:output_type -> agent.MakeDirResponse+ 15, // 38: agent.SandboxAgent.Remove:output_type -> agent.RemoveResponse+ 17, // 39: agent.SandboxAgent.Exists:output_type -> agent.ExistsResponse+ 19, // 40: agent.SandboxAgent.Stat:output_type -> agent.StatResponse+ 21, // 41: agent.SandboxAgent.Stats:output_type -> agent.StatsResponse+ 23, // 42: agent.SandboxAgent.Ping:output_type -> agent.PingResponse+ 25, // 43: agent.SandboxAgent.PTYCreate:output_type -> agent.PTYCreateResponse+ 27, // 44: agent.SandboxAgent.PTYResize:output_type -> agent.PTYResizeResponse+ 29, // 45: agent.SandboxAgent.PTYKill:output_type -> agent.PTYKillResponse+ 31, // 46: agent.SandboxAgent.PTYAttach:output_type -> agent.PTYOutput+ 33, // 47: agent.SandboxAgent.ExecSessionCreate:output_type -> agent.ExecSessionCreateResponse+ 35, // 48: agent.SandboxAgent.ExecSessionAttach:output_type -> agent.ExecSessionOutput+ 37, // 49: agent.SandboxAgent.ExecSessionList:output_type -> agent.ExecSessionListResponse+ 40, // 50: agent.SandboxAgent.ExecSessionKill:output_type -> agent.ExecSessionKillResponse+ 42, // 51: agent.SandboxAgent.SetEnvs:output_type -> agent.SetEnvsResponse+ 44, // 52: agent.SandboxAgent.Shutdown:output_type -> agent.ShutdownResponse+ 46, // 53: agent.SandboxAgent.SyncFS:output_type -> agent.SyncFSResponse+ 48, // 54: agent.SandboxAgent.SetResourceLimits:output_type -> agent.SetResourceLimitsResponse+ 50, // 55: agent.SandboxAgent.GetVersion:output_type -> agent.GetVersionResponse+ 52, // 56: agent.SandboxAgent.Upgrade:output_type -> agent.UpgradeResponse+ 32, // [32:57] is the sub-list for method output_type+ 7, // [7:32] is the sub-list for method input_type7, // [7:7] is the sub-list for extension type_name7, // [7:7] is the sub-list for extension extendee0, // [0:7] is the sub-list for field type_name@@ -2820,7 +3007,7 @@ func file_proto_agent_agent_proto_init() {GoPackagePath: reflect.TypeOf(x{}).PkgPath(),RawDescriptor: unsafe.Slice(unsafe.StringData(file_proto_agent_agent_proto_rawDesc), len(file_proto_agent_agent_proto_rawDesc)),NumEnums: 2,- NumMessages: 50,+ NumMessages: 54,NumExtensions: 0,NumServices: 1,},diff --git a/proto/agent/agent.proto b/proto/agent/agent.protoindex 0b986d92..fa3c99d3 100644--- a/proto/agent/agent.proto+++ b/proto/agent/agent.proto@@ -58,6 +58,13 @@ service SandboxAgent {// SetResourceLimits adjusts sandbox cgroup limits at runtime.// Used for elastic scaling — raise/lower memory, CPU, pids without restart.rpc SetResourceLimits(SetResourceLimitsRequest) returns (SetResourceLimitsResponse);++ // GetVersion returns the agent's build version.+ rpc GetVersion(GetVersionRequest) returns (GetVersionResponse);++ // Upgrade replaces the agent binary and re-execs (same PID 1, no process loss).+ // The worker writes the new binary to binary_path before calling this.+ rpc Upgrade(UpgradeRequest) returns (UpgradeResponse);}// --- Exec ---@@ -299,3 +306,19 @@ message SetResourceLimitsRequest {}message SetResourceLimitsResponse {}++// --- Version + Upgrade ---++message GetVersionRequest {}++message GetVersionResponse {+ string version = 1; // build version (git SHA or build timestamp)+}++message UpgradeRequest {+ string binary_path = 1; // path to new agent binary inside the VM+}++message UpgradeResponse {+ bool ok = 1;+}diff --git a/proto/agent/agent_grpc.pb.go b/proto/agent/agent_grpc.pb.goindex dfaad397..c1026493 100644--- a/proto/agent/agent_grpc.pb.go+++ b/proto/agent/agent_grpc.pb.go@@ -42,6 +42,8 @@ const (SandboxAgent_Shutdown_FullMethodName = "/agent.SandboxAgent/Shutdown"SandboxAgent_SyncFS_FullMethodName = "/agent.SandboxAgent/SyncFS"SandboxAgent_SetResourceLimits_FullMethodName = "/agent.SandboxAgent/SetResourceLimits"+ SandboxAgent_GetVersion_FullMethodName = "/agent.SandboxAgent/GetVersion"+ SandboxAgent_Upgrade_FullMethodName = "/agent.SandboxAgent/Upgrade")// SandboxAgentClient is the client API for SandboxAgent service.@@ -91,6 +93,11 @@ type SandboxAgentClient interface {// SetResourceLimits adjusts sandbox cgroup limits at runtime.// Used for elastic scaling — raise/lower memory, CPU, pids without restart.SetResourceLimits(ctx context.Context, in *SetResourceLimitsRequest, opts ...grpc.CallOption) (*SetResourceLimitsResponse, error)+ // GetVersion returns the agent's build version.+ GetVersion(ctx context.Context, in *GetVersionRequest, opts ...grpc.CallOption) (*GetVersionResponse, error)+ // Upgrade replaces the agent binary and re-execs (same PID 1, no process loss).+ // The worker writes the new binary to binary_path before calling this.+ Upgrade(ctx context.Context, in *UpgradeRequest, opts ...grpc.CallOption) (*UpgradeResponse, error)}type sandboxAgentClient struct {@@ -346,6 +353,26 @@ func (c *sandboxAgentClient) SetResourceLimits(ctx context.Context, in *SetResoureturn out, nil}+func (c *sandboxAgentClient) GetVersion(ctx context.Context, in *GetVersionRequest, opts ...grpc.CallOption) (*GetVersionResponse, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(GetVersionResponse)+ err := c.cc.Invoke(ctx, SandboxAgent_GetVersion_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}++func (c *sandboxAgentClient) Upgrade(ctx context.Context, in *UpgradeRequest, opts ...grpc.CallOption) (*UpgradeResponse, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(UpgradeResponse)+ err := c.cc.Invoke(ctx, SandboxAgent_Upgrade_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}+// SandboxAgentServer is the server API for SandboxAgent service.// All implementations must embed UnimplementedSandboxAgentServer// for forward compatibility.@@ -393,6 +420,11 @@ type SandboxAgentServer interface {// SetResourceLimits adjusts sandbox cgroup limits at runtime.// Used for elastic scaling — raise/lower memory, CPU, pids without restart.SetResourceLimits(context.Context, *SetResourceLimitsRequest) (*SetResourceLimitsResponse, error)+ // GetVersion returns the agent's build version.+ GetVersion(context.Context, *GetVersionRequest) (*GetVersionResponse, error)+ // Upgrade replaces the agent binary and re-execs (same PID 1, no process loss).+ // The worker writes the new binary to binary_path before calling this.+ Upgrade(context.Context, *UpgradeRequest) (*UpgradeResponse, error)mustEmbedUnimplementedSandboxAgentServer()}@@ -472,6 +504,12 @@ func (UnimplementedSandboxAgentServer) SyncFS(context.Context, *SyncFSRequest) (func (UnimplementedSandboxAgentServer) SetResourceLimits(context.Context, *SetResourceLimitsRequest) (*SetResourceLimitsResponse, error) {return nil, status.Error(codes.Unimplemented, "method SetResourceLimits not implemented")}+func (UnimplementedSandboxAgentServer) GetVersion(context.Context, *GetVersionRequest) (*GetVersionResponse, error) {+ return nil, status.Error(codes.Unimplemented, "method GetVersion not implemented")+}+func (UnimplementedSandboxAgentServer) Upgrade(context.Context, *UpgradeRequest) (*UpgradeResponse, error) {+ return nil, status.Error(codes.Unimplemented, "method Upgrade not implemented")+}func (UnimplementedSandboxAgentServer) mustEmbedUnimplementedSandboxAgentServer() {}func (UnimplementedSandboxAgentServer) testEmbeddedByValue() {}@@ -878,6 +916,42 @@ func _SandboxAgent_SetResourceLimits_Handler(srv interface{}, ctx context.Contexreturn interceptor(ctx, in, info, handler)}+func _SandboxAgent_GetVersion_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(GetVersionRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(SandboxAgentServer).GetVersion(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: SandboxAgent_GetVersion_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(SandboxAgentServer).GetVersion(ctx, req.(*GetVersionRequest))+ }+ return interceptor(ctx, in, info, handler)+}++func _SandboxAgent_Upgrade_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(UpgradeRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(SandboxAgentServer).Upgrade(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: SandboxAgent_Upgrade_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(SandboxAgentServer).Upgrade(ctx, req.(*UpgradeRequest))+ }+ return interceptor(ctx, in, info, handler)+}+// SandboxAgent_ServiceDesc is the grpc.ServiceDesc for SandboxAgent service.// It's only intended for direct use with grpc.RegisterService,// and not to be introspected or modified (even as a copy)@@ -965,6 +1039,14 @@ var SandboxAgent_ServiceDesc = grpc.ServiceDesc{MethodName: "SetResourceLimits",Handler: _SandboxAgent_SetResourceLimits_Handler,},+ {+ MethodName: "GetVersion",+ Handler: _SandboxAgent_GetVersion_Handler,+ },+ {+ MethodName: "Upgrade",+ Handler: _SandboxAgent_Upgrade_Handler,+ },},Streams: []grpc.StreamDesc{{