Skip to content

An open-source, faster Devin alternative

TypeScript

live migration virtio-serial

Brian Reardon285a144c8025
diff --git a/cmd/agent/listen_linux.go b/cmd/agent/listen_linux.go
index fd75daa3..9b56d10e 100644
--- a/cmd/agent/listen_linux.go
+++ b/cmd/agent/listen_linux.go
@@ -12,8 +12,150 @@ import (
"golang.org/x/sys/unix"
)
-// vsockListener implements net.Listener for AF_VSOCK sockets.
-// Go's net.FileListener doesn't support AF_VSOCK, so we must wrap the raw fd.
+// listenVsock creates the main agent listener.
+// Tries virtio-serial first (QEMU), then vsock (Firecracker), then Unix socket (testing).
+func listenVsock() (net.Listener, error) {
+ // Try virtio-serial first — survives QEMU live migration.
+ // The device path depends on the virtio device index (vportNpM where N is
+ // the virtio-serial controller index). Check common paths.
+ for _, path := range []string{"/dev/virtio-ports/agent", "/dev/vport0p1", "/dev/vport1p1", "/dev/vport2p1"} {
+ if _, err := os.Stat(path); err == nil {
+ lis, err := listenVirtioSerial(path)
+ if err == nil {
+ log.Printf("agent: listening on virtio-serial %s", path)
+ return lis, nil
+ }
+ log.Printf("agent: virtio-serial open %s failed: %v", path, err)
+ }
+ }
+
+ // Fall back to vsock (Firecracker path)
+ lis, err := listenVsockPort(agent.DefaultGRPCPort)
+ if err == nil {
+ hasVsock = true
+ return lis, nil
+ }
+
+ // Fall back to Unix domain socket (testing)
+ return listenUnix(err)
+}
+
+// hasVsock tracks whether we're inside a VM with AF_VSOCK support.
+var hasVsock bool
+
+// listenPortForPTY returns a listener for PTY data ports.
+// For virtio-serial, PTY data uses vsock if available, otherwise Unix sockets.
+func listenPortForPTY(port uint32) (net.Listener, error) {
+ if hasVsock {
+ return listenVsockPort(port)
+ }
+ // Fallback: Unix socket
+ sockPath := fmt.Sprintf("/tmp/pty-%d.sock", port)
+ os.Remove(sockPath)
+ lis, err := net.Listen("unix", sockPath)
+ if err != nil {
+ return nil, fmt.Errorf("pty unix listen port %d: %w", port, err)
+ }
+ log.Printf("agent: PTY data listening on %s", sockPath)
+ return lis, nil
+}
+
+// --- virtio-serial listener ---
+
+// virtioSerialListener wraps a virtio-serial device as a net.Listener.
+// The device is a bidirectional byte stream — one "connection" at a time.
+// When gRPC's Serve() loop calls Accept() after a connection drops (e.g.,
+// after golden snapshot restore), we return a new conn wrapping the same fd.
+type virtioSerialListener struct {
+ f *os.File
+ once sync.Once
+ closed chan struct{}
+ mu sync.Mutex
+ active bool // true when a connection is being served
+}
+
+func listenVirtioSerial(path string) (net.Listener, error) {
+ f, err := os.OpenFile(path, os.O_RDWR, 0)
+ if err != nil {
+ return nil, fmt.Errorf("open virtio-serial %s: %w", path, err)
+ }
+
+ return &virtioSerialListener{
+ f: f,
+ closed: make(chan struct{}),
+ }, nil
+}
+
+func (l *virtioSerialListener) Accept() (net.Conn, error) {
+ // Wait until no connection is active, then provide a new one.
+ // This handles: initial boot, reconnect after golden restore, etc.
+ for {
+ select {
+ case <-l.closed:
+ return nil, net.ErrClosed
+ default:
+ }
+
+ l.mu.Lock()
+ if !l.active {
+ l.active = true
+ l.mu.Unlock()
+ return &virtioSerialConn{
+ f: l.f,
+ onClose: func() {
+ l.mu.Lock()
+ l.active = false
+ l.mu.Unlock()
+ },
+ }, nil
+ }
+ l.mu.Unlock()
+ time.Sleep(100 * time.Millisecond)
+ }
+}
+
+func (l *virtioSerialListener) Close() error {
+ l.once.Do(func() { close(l.closed) })
+ return l.f.Close()
+}
+
+func (l *virtioSerialListener) Addr() net.Addr {
+ return virtioSerialAddr(l.f.Name())
+}
+
+type virtioSerialAddr string
+
+func (a virtioSerialAddr) Network() string { return "virtio-serial" }
+func (a virtioSerialAddr) String() string { return string(a) }
+
+// virtioSerialConn wraps an os.File as a net.Conn for gRPC.
+// onClose is called when gRPC drops the connection, signaling the listener
+// to accept a new one (e.g., after golden snapshot restore).
+type virtioSerialConn struct {
+ f *os.File
+ onClose func()
+ once sync.Once
+}
+
+func (c *virtioSerialConn) Read(b []byte) (int, error) { return c.f.Read(b) }
+func (c *virtioSerialConn) Write(b []byte) (int, error) { return c.f.Write(b) }
+func (c *virtioSerialConn) Close() error {
+ c.once.Do(func() {
+ if c.onClose != nil {
+ c.onClose()
+ }
+ })
+ // Don't close the file — the listener still owns it for future connections
+ return nil
+}
+func (c *virtioSerialConn) LocalAddr() net.Addr { return virtioSerialAddr("local") }
+func (c *virtioSerialConn) RemoteAddr() net.Addr { return virtioSerialAddr("remote") }
+func (c *virtioSerialConn) SetDeadline(t time.Time) error { return c.f.SetDeadline(t) }
+func (c *virtioSerialConn) SetReadDeadline(t time.Time) error { return c.f.SetReadDeadline(t) }
+func (c *virtioSerialConn) SetWriteDeadline(t time.Time) error { return c.f.SetWriteDeadline(t) }
+
+// --- vsock support (Firecracker backward compat) ---
+
type vsockListener struct {
fd int
port uint32
@@ -40,8 +182,6 @@ func (l *vsockListener) Accept() (net.Conn, error) {
}
return nil, fmt.Errorf("vsock accept: %w", err)
}
- // Wrap the accepted fd directly as a raw vsock connection.
- // net.FileConn doesn't support AF_VSOCK, so we use our own wrapper.
return newRawVsockConn(nfd), nil
}
}
@@ -59,39 +199,6 @@ func (l *vsockListener) Addr() net.Addr {
return vsockAddr{cid: unix.VMADDR_CID_ANY, port: l.port}
}
-// listenPortForPTY returns a ListenPortFunc suitable for PTY data ports.
-// Inside Firecracker it uses native AF_VSOCK; outside, it falls back to Unix sockets.
-func listenPortForPTY(port uint32) (net.Listener, error) {
- if hasVsock {
- return listenVsockPort(port)
- }
- // Fallback: Unix socket (for testing outside Firecracker)
- sockPath := fmt.Sprintf("/tmp/pty-%d.sock", port)
- os.Remove(sockPath)
- lis, err := net.Listen("unix", sockPath)
- if err != nil {
- return nil, fmt.Errorf("pty unix listen port %d: %w", port, err)
- }
- log.Printf("agent: PTY data listening on %s (vsock not available)", sockPath)
- return lis, nil
-}
-
-// hasVsock tracks whether we're inside a Firecracker VM with AF_VSOCK support.
-var hasVsock bool
-
-// listenVsock creates a vsock listener on port 1024.
-func listenVsock() (net.Listener, error) {
- lis, err := listenVsockPort(agent.DefaultGRPCPort)
- if err == nil {
- hasVsock = true
- return lis, nil
- }
-
- // Fallback to Unix domain socket (testing outside Firecracker)
- return listenUnix(err)
-}
-
-// listenVsockPort creates a vsock listener on the given port.
func listenVsockPort(port uint32) (net.Listener, error) {
fd, err := unix.Socket(unix.AF_VSOCK, unix.SOCK_STREAM|unix.SOCK_CLOEXEC, 0)
if err != nil {
@@ -133,12 +240,11 @@ func newRawVsockConn(fd int) *rawVsockConn {
return &rawVsockConn{file: os.NewFile(uintptr(fd), "vsock-raw")}
}
-func (c *rawVsockConn) Read(b []byte) (int, error) { return c.file.Read(b) }
-func (c *rawVsockConn) Write(b []byte) (int, error) { return c.file.Write(b) }
-func (c *rawVsockConn) Close() error { return c.file.Close() }
-
-func (c *rawVsockConn) LocalAddr() net.Addr { return vsockAddr{} }
-func (c *rawVsockConn) RemoteAddr() net.Addr { return vsockAddr{} }
-func (c *rawVsockConn) SetDeadline(_ time.Time) error { return nil }
-func (c *rawVsockConn) SetReadDeadline(_ time.Time) error { return nil }
-func (c *rawVsockConn) SetWriteDeadline(_ time.Time) error { return nil }
+func (c *rawVsockConn) Read(b []byte) (int, error) { return c.file.Read(b) }
+func (c *rawVsockConn) Write(b []byte) (int, error) { return c.file.Write(b) }
+func (c *rawVsockConn) Close() error { return c.file.Close() }
+func (c *rawVsockConn) LocalAddr() net.Addr { return vsockAddr{} }
+func (c *rawVsockConn) RemoteAddr() net.Addr { return vsockAddr{} }
+func (c *rawVsockConn) SetDeadline(_ time.Time) error { return nil }
+func (c *rawVsockConn) SetReadDeadline(_ time.Time) error { return nil }
+func (c *rawVsockConn) SetWriteDeadline(_ time.Time) error { return nil }
diff --git a/deploy/ec2/build-rootfs-docker.sh b/deploy/ec2/build-rootfs-docker.sh
index ecd77255..a70b638d 100755
--- a/deploy/ec2/build-rootfs-docker.sh
+++ b/deploy/ec2/build-rootfs-docker.sh
@@ -134,6 +134,9 @@ echo "nameserver 8.8.4.4" >> /etc/resolv.conf
hostname sandbox
+# Debug: check for virtio-serial device
+ls -la /dev/vport* /dev/virtio-ports/ 2>/dev/null || echo "init: no virtio-serial devices found"
+
exec /usr/local/bin/osb-agent
INIT_EOF
chmod +x "$TMPDIR/init"
diff --git a/internal/qemu/agent_client.go b/internal/qemu/agent_client.go
index 36219a68..ce31983b 100644
--- a/internal/qemu/agent_client.go
+++ b/internal/qemu/agent_client.go
@@ -321,15 +321,14 @@ func (c *AgentClient) ConnectPTYData(guestCID uint32, dataPort uint32) (net.Conn
return conn, nil
}
-// NewAgentClientTCP connects to the agent via TCP using the guest IP.
-// Used by QEMU backend — TCP over virtio-net survives QEMU migration.
-func NewAgentClientTCP(guestIP string) (*AgentClient, error) {
+// NewAgentClientSocket connects to the agent via a Unix socket (virtio-serial chardev).
+// Used by QEMU backend — virtio-serial survives QEMU live migration.
+func NewAgentClientSocket(socketPath string) (*AgentClient, error) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
- addr := fmt.Sprintf("%s:%d", guestIP, 1024)
conn, err := grpc.DialContext(ctx,
- addr,
+ "unix://"+socketPath,
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithBlock(),
grpc.WithConnectParams(grpc.ConnectParams{
@@ -346,7 +345,7 @@ func NewAgentClientTCP(guestIP string) (*AgentClient, error) {
),
)
if err != nil {
- return nil, fmt.Errorf("connect to agent at %s: %w", addr, err)
+ return nil, fmt.Errorf("connect to agent at %s: %w", socketPath, err)
}
return &AgentClient{
@@ -354,13 +353,3 @@ func NewAgentClientTCP(guestIP string) (*AgentClient, error) {
client: pb.NewSandboxAgentClient(conn),
}, nil
}
-
-// ConnectPTYDataTCP connects to a PTY data port via TCP.
-func ConnectPTYDataTCP(guestIP string, dataPort uint32) (net.Conn, error) {
- addr := fmt.Sprintf("%s:%d", guestIP, dataPort)
- conn, err := net.DialTimeout("tcp", addr, 5*time.Second)
- if err != nil {
- return nil, fmt.Errorf("connect to PTY data %s: %w", addr, err)
- }
- return conn, nil
-}
diff --git a/internal/qemu/manager.go b/internal/qemu/manager.go
index 9cac7639..5ab333f2 100644
--- a/internal/qemu/manager.go
+++ b/internal/qemu/manager.go
@@ -46,10 +46,11 @@ type VMInstance struct {
network *NetworkConfig
sandboxDir string
agent *AgentClient
- qmpSockPath string
- qmp *QMPClient
- guestMAC string
- guestCID uint32
+ qmpSockPath string
+ agentSockPath string
+ qmp *QMPClient
+ guestMAC string
+ guestCID uint32
bootArgs string
restoring chan struct{}
}
@@ -214,7 +215,9 @@ func (m *Manager) PrepareGoldenSnapshot() error {
)
qmpSockPath := filepath.Join(goldenDir, "qmp.sock")
+ agentSockPath := filepath.Join(goldenDir, "agent.sock")
os.Remove(qmpSockPath)
+ os.Remove(agentSockPath)
logPath := filepath.Join(goldenDir, "qemu.log")
logFile, err := os.Create(logPath)
@@ -223,7 +226,7 @@ func (m *Manager) PrepareGoldenSnapshot() error {
}
args := m.buildQEMUArgs(m.cfg.DefaultCPUs, m.cfg.DefaultMemoryMB,
- rootfsFile, workspaceFile, netCfg.TAPName, goldenMAC, goldenCID, qmpSockPath, bootArgs)
+ rootfsFile, workspaceFile, netCfg.TAPName, goldenMAC, agentSockPath, qmpSockPath, bootArgs)
cmd := exec.Command(m.cfg.QEMUBin, args...)
cmd.Stdout = logFile
@@ -242,8 +245,8 @@ func (m *Manager) PrepareGoldenSnapshot() error {
return fmt.Errorf("golden QMP connect: %w", err)
}
- // Wait for agent to be ready
- agentClient, err := m.waitForAgent(context.Background(), goldenCID, 30*time.Second)
+ // Wait for agent via virtio-serial Unix socket
+ agentClient, err := m.waitForAgentSocket(context.Background(), agentSockPath, 30*time.Second)
if err != nil {
qmpClient.Close()
cmd.Process.Kill()
@@ -433,6 +436,8 @@ func (m *Manager) createFromGolden(ctx context.Context, cfg types.SandboxConfig,
qmpSockPath := filepath.Join(sandboxDir, "qmp.sock")
os.Remove(qmpSockPath)
+ agentSockPath := filepath.Join(sandboxDir, "agent.sock")
+ os.Remove(agentSockPath)
logPath := filepath.Join(sandboxDir, "qemu.log")
logFile, err := os.Create(logPath)
@@ -452,7 +457,7 @@ func (m *Manager) createFromGolden(ctx context.Context, cfg types.SandboxConfig,
incomingURI = fmt.Sprintf("exec:cat %s", goldenMemRaw)
}
args := m.buildQEMUArgs(cpus, memMB, rootfsPath, workspacePath,
- netCfg.TAPName, guestMAC, guestCID, qmpSockPath, bootArgs)
+ netCfg.TAPName, guestMAC, agentSockPath, qmpSockPath, bootArgs)
args = append(args, "-incoming", incomingURI)
cmd := exec.Command(m.cfg.QEMUBin, args...)
@@ -504,38 +509,30 @@ func (m *Manager) createFromGolden(ctx context.Context, cfg types.SandboxConfig,
}
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,
- }
-
- // Connect to agent via vsock. Try new CID first, fall back to golden CID
- // (migration may preserve the golden CID in the virtio device).
+ 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,
+ agentSockPath: agentSockPath,
+ qmp: qmpClient,
+ guestMAC: guestMAC,
+ guestCID: guestCID,
+ bootArgs: bootArgs,
+ }
+
+ // Connect to agent via Unix socket
var agentClient *AgentClient
- agentClient, err = m.waitForAgent(context.Background(), guestCID, 3*time.Second)
- if err != nil {
- log.Printf("qemu: golden-create %s: CID=%d failed, trying golden CID=%d", id, guestCID, m.goldenCID)
- agentClient, err = m.waitForAgent(context.Background(), m.goldenCID, 5*time.Second)
- if err == nil {
- guestCID = m.goldenCID
- vm.guestCID = guestCID
- }
- }
+ agentClient, err = m.waitForAgentSocket(context.Background(), agentSockPath, 10*time.Second)
if err != nil {
log.Printf("qemu: golden-create %s: agent not ready, falling back to cold boot: %v", id, err)
qmpClient.Close()
@@ -697,7 +694,8 @@ func (m *Manager) allocateCID() uint32 {
}
// 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 {
+// agentSock is the Unix socket path for the virtio-serial agent channel.
+func (m *Manager) buildQEMUArgs(cpus, memMB int, rootfsPath, workspacePath, tapName, mac, agentSock, qmpSock, bootArgs string) []string {
// Detect drive format from file extension
rootfsFmt := "qcow2"
if strings.HasSuffix(rootfsPath, ".ext4") {
@@ -718,7 +716,11 @@ func (m *Manager) buildQEMUArgs(cpus, memMB int, rootfsPath, workspacePath, tapN
"-drive", fmt.Sprintf("file=%s,format=%s,if=virtio,cache=writethrough", workspacePath, wsFmt),
"-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,id=vsock0", cid),
+ // Agent communication via virtio-serial (survives QEMU migration,
+ // unlike vhost-vsock which uses a per-process kernel fd).
+ "-device", "virtio-serial-pci-non-transitional",
+ "-chardev", fmt.Sprintf("socket,id=agent,path=%s,server=on,wait=off", agentSock),
+ "-device", "virtserialport,chardev=agent,name=agent",
"-qmp", fmt.Sprintf("unix:%s,server,nowait", qmpSock),
"-nographic",
"-nodefaults",
@@ -843,6 +845,8 @@ func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (*types.S
qmpSockPath := filepath.Join(sandboxDir, "qmp.sock")
os.Remove(qmpSockPath)
+ agentSockPath := filepath.Join(sandboxDir, "agent.sock")
+ os.Remove(agentSockPath)
logPath := filepath.Join(sandboxDir, "qemu.log")
logFile, err := os.Create(logPath)
@@ -852,7 +856,7 @@ func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (*types.S
}
args := m.buildQEMUArgs(cpus, memMB, rootfsPath, workspacePath,
- netCfg.TAPName, guestMAC, guestCID, qmpSockPath, bootArgs)
+ netCfg.TAPName, guestMAC, agentSockPath, qmpSockPath, bootArgs)
cmd := exec.Command(m.cfg.QEMUBin, args...)
cmd.Stdout = logFile
@@ -881,28 +885,29 @@ func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (*types.S
}
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 vsock
- agentClient, err := m.waitForAgent(context.Background(), guestCID, 30*time.Second)
+ 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,
+ agentSockPath: agentSockPath,
+ qmp: qmpClient,
+ guestMAC: guestMAC,
+ guestCID: guestCID,
+ bootArgs: bootArgs,
+ }
+
+ // Wait for agent via Unix socket
+ agentClient, err := m.waitForAgentSocket(context.Background(), agentSockPath, 30*time.Second)
if err != nil {
log.Printf("qemu: agent not ready for %s, killing VM: %v", id, err)
qmpClient.Close()
@@ -995,9 +1000,9 @@ func (m *Manager) waitForAgent(ctx context.Context, guestCID uint32, timeout tim
return nil, fmt.Errorf("agent not ready after %v (%d attempts): %v", timeout, attempts, lastErr)
}
-// waitForAgentTCP polls the agent via TCP until it responds or times out.
-// Used by QEMU backend — TCP over virtio-net survives migration.
-func (m *Manager) waitForAgentTCP(ctx context.Context, guestIP string, timeout time.Duration) (*AgentClient, error) {
+// waitForAgentSocket polls the agent via Unix socket (virtio-serial chardev)
+// until it responds or times out.
+func (m *Manager) waitForAgentSocket(ctx context.Context, socketPath string, timeout time.Duration) (*AgentClient, error) {
t0 := time.Now()
deadline := t0.Add(timeout)
var lastErr error
@@ -1006,12 +1011,12 @@ func (m *Manager) waitForAgentTCP(ctx context.Context, guestIP string, timeout t
for time.Now().Before(deadline) {
attempts++
tAttempt := time.Now()
- client, err := NewAgentClientTCP(guestIP)
+ client, err := NewAgentClientSocket(socketPath)
if err != nil {
lastErr = err
if attempts <= 3 || attempts%10 == 0 {
- log.Printf("qemu: waitForAgentTCP: attempt %d dial %s failed (%dms): %v",
- attempts, guestIP, time.Since(tAttempt).Milliseconds(), err)
+ log.Printf("qemu: waitForAgentSocket: attempt %d dial %s failed (%dms): %v",
+ attempts, socketPath, time.Since(tAttempt).Milliseconds(), err)
}
time.Sleep(50 * time.Millisecond)
continue
@@ -1027,8 +1032,8 @@ func (m *Manager) waitForAgentTCP(ctx context.Context, guestIP string, timeout t
continue
}
- log.Printf("qemu: waitForAgentTCP: connected to %s on attempt %d (%dms total)",
- guestIP, attempts, time.Since(t0).Milliseconds())
+ log.Printf("qemu: waitForAgentSocket: connected to %s on attempt %d (%dms total)",
+ socketPath, attempts, time.Since(t0).Milliseconds())
return client, nil
}
@@ -1555,8 +1560,8 @@ func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpoi
return fmt.Errorf("cont after loadvm failed: %w", err)
}
- // Reconnect agent via TCP
- agent, err := m.waitForAgent(context.Background(), vm.guestCID, 10*time.Second)
+ // Reconnect agent via Unix socket
+ agent, err := m.waitForAgentSocket(context.Background(), vm.agentSockPath, 10*time.Second)
if err != nil {
return fmt.Errorf("agent reconnect after loadvm: %w", err)
}
@@ -1666,6 +1671,8 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, c
qmpSockPath := filepath.Join(sandboxDir, "qmp.sock")
os.Remove(qmpSockPath)
+ agentSockPath := filepath.Join(sandboxDir, "agent.sock")
+ os.Remove(agentSockPath)
logPath := filepath.Join(sandboxDir, "qemu.log")
logFile, err := os.Create(logPath)
@@ -1676,7 +1683,7 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, c
// Start QEMU paused — we'll loadvm then cont
args := m.buildQEMUArgs(cpus, memMB, rootfsPath, workspacePath,
- netCfg.TAPName, guestMAC, guestCID, qmpSockPath, bootArgs)
+ netCfg.TAPName, guestMAC, agentSockPath, qmpSockPath, bootArgs)
args = append(args, "-S") // start paused
cmd := exec.Command(m.cfg.QEMUBin, args...)
@@ -1715,9 +1722,9 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, c
}
log.Printf("qemu: ForkFromCheckpoint %s → %s: VM resumed (%dms)", checkpointID, id, time.Since(t0).Milliseconds())
- // Connect agent via TCP
+ // Connect agent via Unix socket
var agent *AgentClient
- agent, err = m.waitForAgent(context.Background(), guestCID, 10*time.Second)
+ agent, err = m.waitForAgentSocket(context.Background(), agentSockPath, 10*time.Second)
if err != nil {
qmpClient.Close()
cmd.Process.Kill()
@@ -1745,25 +1752,26 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, c
}
vm := &VMInstance{
- ID: id,
- Template: meta.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,
- agent: agent,
+ ID: id,
+ Template: meta.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,
+ agentSockPath: agentSockPath,
+ qmp: qmpClient,
+ guestMAC: guestMAC,
+ guestCID: guestCID,
+ bootArgs: bootArgs,
+ agent: agent,
}
m.mu.Lock()
diff --git a/internal/qemu/snapshot.go b/internal/qemu/snapshot.go
index 7006ee03..88892809 100644
--- a/internal/qemu/snapshot.go
+++ b/internal/qemu/snapshot.go
@@ -58,26 +58,23 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointSto
memFile := filepath.Join(snapshotDir, "mem")
- // Step 1: Sync filesystems, unmount workspace, then kill the agent.
- // Killing the agent (SIGTERM → PID 1) cleanly closes the vsock listener
- // from inside the guest. This ensures the host kernel's vhost-vsock module
- // properly unregisters the CID when QEMU exits, so the next QEMU process
- // can use vhost-vsock without stale state.
+ // Step 1: Sync filesystems and unmount workspace.
+ // With virtio-serial, we don't need to kill the agent — the device
+ // survives migration. Just sync and unmount so the workspace qcow2 is clean.
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 -TERM 1"},
+ Args: []string{"-c", "umount /workspace 2>/dev/null; sync"},
})
cancel()
}
- log.Printf("qemu: hibernate %s: guest shutdown done (%dms)", vm.ID, time.Since(t0).Milliseconds())
+ log.Printf("qemu: hibernate %s: guest sync + unmount done (%dms)", vm.ID, time.Since(t0).Milliseconds())
- // Step 2: Close host-side gRPC connection and wait for vsock to drain.
+ // Step 2: Close host-side gRPC connection.
if vm.agent != nil {
vm.agent.Close()
vm.agent = nil
- time.Sleep(500 * time.Millisecond)
}
// Step 3: Stop (pause) the VM via QMP
@@ -350,6 +347,8 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, c
qmpSockPath := filepath.Join(sandboxDir, "qmp.sock")
os.Remove(qmpSockPath)
+ agentSockPath := filepath.Join(sandboxDir, "agent.sock")
+ os.Remove(agentSockPath)
logPath := filepath.Join(sandboxDir, "qemu.log")
logFile, err := os.Create(logPath)
@@ -360,7 +359,7 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, c
// Start QEMU with golden migration state + user's workspace
args := m.buildQEMUArgs(meta.CpuCount, meta.MemoryMB, rootfsPath, workspacePath,
- netCfg.TAPName, guestMAC, guestCID, qmpSockPath, bootArgs)
+ netCfg.TAPName, guestMAC, agentSockPath, qmpSockPath, bootArgs)
goldenMemZst := filepath.Join(m.goldenDir, "mem.zst")
goldenMemRaw := filepath.Join(m.goldenDir, "mem")
var incomingURI string
@@ -404,15 +403,8 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, c
return nil, fmt.Errorf("QMP cont for wake: %w", err)
}
- // Connect agent via vsock. Try allocated CID, fall back to golden CID.
- agentClient, err := m.waitForAgent(context.Background(), guestCID, 3*time.Second)
- if err != nil {
- log.Printf("qemu: wake %s: CID=%d failed, trying golden CID=%d", sandboxID, guestCID, m.goldenCID)
- agentClient, err = m.waitForAgent(context.Background(), m.goldenCID, 5*time.Second)
- if err == nil {
- guestCID = m.goldenCID
- }
- }
+ // Connect agent via Unix socket
+ agentClient, err := m.waitForAgentSocket(context.Background(), agentSockPath, 10*time.Second)
if err != nil {
cmd.Process.Kill()
cmd.Wait()
@@ -447,24 +439,25 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, c
}
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,
+ 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,
+ agentSockPath: agentSockPath,
+ qmp: qmpClient,
+ guestMAC: guestMAC,
+ guestCID: guestCID,
+ bootArgs: bootArgs,
}
vm.agent = agentClient
@@ -558,6 +551,8 @@ func (m *Manager) coldBootLocal(ctx context.Context, sandboxID string, timeout i
qmpSockPath := filepath.Join(sandboxDir, "qmp.sock")
os.Remove(qmpSockPath)
+ agentSockPath := filepath.Join(sandboxDir, "agent.sock")
+ os.Remove(agentSockPath)
logPath := filepath.Join(sandboxDir, "qemu.log")
logFile, err := os.Create(logPath)
@@ -567,7 +562,7 @@ func (m *Manager) coldBootLocal(ctx context.Context, sandboxID string, timeout i
}
args := m.buildQEMUArgs(cpus, memMB, rootfsPath, workspacePath,
- netCfg.TAPName, guestMAC, guestCID, qmpSockPath, bootArgs)
+ netCfg.TAPName, guestMAC, agentSockPath, qmpSockPath, bootArgs)
cmd := exec.Command(m.cfg.QEMUBin, args...)
cmd.Stdout = logFile
@@ -594,27 +589,28 @@ func (m *Manager) coldBootLocal(ctx context.Context, sandboxID string, timeout i
}
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)
+ 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,
+ agentSockPath: agentSockPath,
+ qmp: qmpClient,
+ guestMAC: guestMAC,
+ guestCID: guestCID,
+ bootArgs: bootArgs,
+ }
+
+ agentClient, err := m.waitForAgentSocket(context.Background(), agentSockPath, 30*time.Second)
if err != nil {
cmd.Process.Kill()
cmd.Wait()