Skip to content

An open-source, faster Devin alternative

TypeScript

fixes, and adjustments

Brian Reardon4c9f3c83124c
diff --git a/deploy/azure/setup-azure-host.sh b/deploy/azure/setup-azure-host.sh
index c441a944..867b0911 100755
--- a/deploy/azure/setup-azure-host.sh
+++ b/deploy/azure/setup-azure-host.sh
@@ -185,8 +185,8 @@ Restart=on-failure
RestartSec=5
LimitNOFILE=1000000
LimitNPROC=infinity
-KillMode=mixed
-TimeoutStopSec=180
+KillMode=process
+TimeoutStopSec=300
[Install]
WantedBy=multi-user.target
diff --git a/deploy/ec2/.qemu-dev-state-us-east-2 b/deploy/ec2/.qemu-dev-state-us-east-2
new file mode 100644
index 00000000..1cdec01a
--- /dev/null
+++ b/deploy/ec2/.qemu-dev-state-us-east-2
@@ -0,0 +1,2 @@
+INSTANCE_ID=i-024e1154693755dde
+PUBLIC_IP=3.148.184.81
diff --git a/deploy/ec2/build-rootfs-docker.sh b/deploy/ec2/build-rootfs-docker.sh
index 9f06025e..ecd77255 100755
--- a/deploy/ec2/build-rootfs-docker.sh
+++ b/deploy/ec2/build-rootfs-docker.sh
@@ -71,31 +71,20 @@ cat > "$TMPDIR/init" << 'INIT_EOF'
mount -t proc proc /proc
mount -t devtmpfs devtmpfs /dev
-# ── Overlay root: data disk as writable upper layer over the rootfs ──
-mkdir -p /mnt/data
-if mount /dev/vdb /mnt/data 2>/dev/null || mount /dev/vdb1 /mnt/data 2>/dev/null; then
- mkdir -p /mnt/data/upper /mnt/data/work /mnt/overlay
-
- umount /dev
- umount /proc
-
- mount -t overlay overlay -o lowerdir=/,upperdir=/mnt/data/upper,workdir=/mnt/data/work /mnt/overlay
-
- mkdir -p /mnt/overlay/mnt/data
- mount --move /mnt/data /mnt/overlay/mnt/data
-
- cd /mnt/overlay
- mkdir -p mnt/old_root
- pivot_root . mnt/old_root
-
- umount -l /mnt/old_root 2>/dev/null
- rmdir /mnt/old_root 2>/dev/null
+# Load kernel modules (needed for QEMU with modular kernel)
+if [ -d /lib/modules/vsock ]; then
+ for mod in /lib/modules/vsock/vsock.ko /lib/modules/vsock/vmw_vsock_virtio_transport_common.ko /lib/modules/vsock/vmw_vsock_virtio_transport.ko; do
+ [ -f "$mod" ] && insmod "$mod" 2>/dev/null || true
+ done
+ echo "init: kernel modules loaded"
+fi
- echo "init: overlay root active (data disk backing all writes)"
+# ── Mount workspace: data disk at /workspace (persistent user data) ──
+mkdir -p /workspace
+if mount /dev/vdb /workspace 2>/dev/null || mount /dev/vdb1 /workspace 2>/dev/null; then
+ echo "init: workspace mounted (/dev/vdb -> /workspace)"
else
- umount /dev
- umount /proc
- echo "init: warning: no data disk found, running on rootfs only"
+ echo "init: warning: no data disk found, /workspace is ephemeral"
fi
# ── Mount virtual filesystems (in the final root) ──
diff --git a/deploy/ec2/deploy-qemu-dev.sh b/deploy/ec2/deploy-qemu-dev.sh
new file mode 100755
index 00000000..c3b62b30
--- /dev/null
+++ b/deploy/ec2/deploy-qemu-dev.sh
@@ -0,0 +1,607 @@
+#!/usr/bin/env bash
+# deploy-qemu-dev.sh — Deploy QEMU-based dev environment on c5d.metal spot in AWS
+#
+# Uses existing VPC/SG/key infrastructure from the opensandbox AWS account.
+# Launches a c5d.metal spot instance with NVMe formatted as XFS (reflink for qcow2).
+# Reuses deploy/azure/setup-azure-host.sh for QEMU/KVM provisioning.
+#
+# Usage:
+# ./deploy/ec2/deploy-qemu-dev.sh [create|deploy|ssh|status|stop|start|destroy]
+#
+# Configuration (env vars):
+# AWS_REGION — AWS region (default: us-east-2)
+# AWS_PROFILE — AWS CLI profile (default: digger)
+# INSTANCE_TYPE — EC2 instance type (default: c5d.metal)
+# KEY_NAME — EC2 key pair name (default: opensandbox-digger)
+# SSH_KEY — Path to SSH private key (default: ~/.ssh/opensandbox-digger.pem)
+# SECURITY_GROUP — Security group ID (default: sg-01e14f56c4c50b6c5)
+# SUBNET_ID — Subnet ID (default: subnet-0cbc1cca8b2bfa8bc, us-east-2b)
+# API_KEY — API key for the server (default: test-dev-key)
+
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
+
+# --- Defaults ---
+AWS_REGION="${AWS_REGION:-us-east-2}"
+AWS_PROFILE="${AWS_PROFILE:-digger}"
+INSTANCE_TYPE="${INSTANCE_TYPE:-c5d.metal}"
+KEY_NAME="${KEY_NAME:-opensandbox-digger}"
+SSH_KEY="${SSH_KEY:-$HOME/.ssh/opensandbox-digger.pem}"
+SECURITY_GROUP="${SECURITY_GROUP:-sg-01e14f56c4c50b6c5}"
+SUBNET_ID="${SUBNET_ID:-subnet-0cbc1cca8b2bfa8bc}"
+API_KEY="${API_KEY:-test-dev-key}"
+PROJECT_TAG="opensandbox-qemu-dev"
+
+STATE_FILE="$SCRIPT_DIR/.qemu-dev-state-${AWS_REGION}"
+
+# --- Helpers ---
+log() { echo "$(date '+%H:%M:%S') [qemu-dev] $*"; }
+err() { echo "$(date '+%H:%M:%S') [qemu-dev] ERROR: $*" >&2; exit 1; }
+
+aws_cmd() { aws --profile "$AWS_PROFILE" --region "$AWS_REGION" "$@"; }
+
+save_state() {
+ local key="$1" value="$2"
+ if [ -f "$STATE_FILE" ] && grep -q "^${key}=" "$STATE_FILE" 2>/dev/null; then
+ sed -i.bak "s|^${key}=.*|${key}=${value}|" "$STATE_FILE"
+ rm -f "${STATE_FILE}.bak"
+ else
+ echo "${key}=${value}" >> "$STATE_FILE"
+ fi
+}
+
+load_state() {
+ local key="$1"
+ if [ -f "$STATE_FILE" ]; then
+ grep "^${key}=" "$STATE_FILE" 2>/dev/null | cut -d= -f2- || true
+ fi
+}
+
+ssh_cmd() {
+ local ip
+ ip=$(load_state PUBLIC_IP)
+ [ -n "$ip" ] || err "No instance IP found. Run 'create' first."
+ ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null \
+ -i "$SSH_KEY" "ubuntu@${ip}" "$@"
+}
+
+lookup_x86_ami() {
+ echo "Looking up latest Ubuntu 24.04 x86_64 AMI in ${AWS_REGION}..." >&2
+ local ami_id
+ ami_id=$(aws_cmd ec2 describe-images \
+ --owners 099720109477 \
+ --filters \
+ "Name=name,Values=ubuntu/images/hvm-ssd-gp3/ubuntu-noble-24.04-amd64-server-*" \
+ "Name=architecture,Values=x86_64" \
+ "Name=state,Values=available" \
+ --query 'Images | sort_by(@, &CreationDate) | [-1].ImageId' \
+ --output text)
+ if [ -z "$ami_id" ] || [ "$ami_id" = "None" ]; then
+ err "Could not find Ubuntu 24.04 x86_64 AMI in ${AWS_REGION}"
+ fi
+ echo "$ami_id"
+}
+
+# --- Create ---
+cmd_create() {
+ local existing_instance
+ existing_instance=$(load_state INSTANCE_ID)
+ if [ -n "$existing_instance" ]; then
+ local state
+ state=$(aws_cmd ec2 describe-instances \
+ --instance-ids "$existing_instance" \
+ --query 'Reservations[0].Instances[0].State.Name' \
+ --output text 2>/dev/null || echo "not-found")
+ if [ "$state" = "running" ] || [ "$state" = "pending" ]; then
+ log "Instance $existing_instance already exists (state: $state)"
+ cmd_status
+ return 0
+ fi
+ fi
+
+ # Get AMI
+ local ami_id
+ ami_id=$(lookup_x86_ami)
+ log "AMI: $ami_id"
+
+ # Launch on-demand instance
+ log "Launching ${INSTANCE_TYPE} on-demand instance..."
+ local instance_id
+ instance_id=$(aws_cmd ec2 run-instances \
+ --image-id "$ami_id" \
+ --instance-type "$INSTANCE_TYPE" \
+ --key-name "$KEY_NAME" \
+ --subnet-id "$SUBNET_ID" \
+ --security-group-ids "$SECURITY_GROUP" \
+ --block-device-mappings \
+ 'DeviceName=/dev/sda1,Ebs={VolumeSize=50,VolumeType=gp3,DeleteOnTermination=true}' \
+ --tag-specifications "ResourceType=instance,Tags=[{Key=Name,Value=${PROJECT_TAG}},{Key=Project,Value=opensandbox}]" \
+ --query 'Instances[0].InstanceId' --output text)
+ save_state INSTANCE_ID "$instance_id"
+ log "Instance: $instance_id (on-demand)"
+
+ # Wait for running
+ log "Waiting for instance to be running..."
+ aws_cmd ec2 wait instance-running --instance-ids "$instance_id"
+
+ local public_ip
+ public_ip=$(aws_cmd ec2 describe-instances \
+ --instance-ids "$instance_id" \
+ --query 'Reservations[0].Instances[0].PublicIpAddress' --output text)
+ save_state PUBLIC_IP "$public_ip"
+ log "Public IP: $public_ip"
+
+ # Wait for SSH (bare-metal takes a while)
+ log "Waiting for SSH (bare-metal boot takes a few minutes)..."
+ for i in $(seq 1 90); do
+ if ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 -o BatchMode=yes \
+ -i "$SSH_KEY" "ubuntu@$public_ip" "echo ready" &>/dev/null; then
+ log "SSH ready after ~$((i * 10))s"
+ break
+ fi
+ if [ "$i" -eq 90 ]; then
+ err "SSH not ready after 900s. Check instance console."
+ fi
+ sleep 10
+ done
+
+ # Format NVMe drives as XFS with reflink and mount at /data
+ log "Setting up NVMe storage (XFS with reflink)..."
+ ssh_cmd << 'SETUP_NVME'
+set -euo pipefail
+
+# Find all NVMe instance store drives (not the root EBS volume)
+NVME_DRIVES=()
+for dev in /dev/nvme{0,1,2,3,4,5,6,7}n1; do
+ [ -b "$dev" ] || continue
+ # Skip the root volume (has partitions or is mounted)
+ if lsblk -no MOUNTPOINT "$dev" 2>/dev/null | grep -q '/'; then
+ continue
+ fi
+ # Skip if any partition of this device is mounted
+ if lsblk -no MOUNTPOINT "${dev}"* 2>/dev/null | grep -q '/'; then
+ continue
+ fi
+ NVME_DRIVES+=("$dev")
+done
+
+echo "Found ${#NVME_DRIVES[@]} NVMe instance store drive(s): ${NVME_DRIVES[*]}"
+
+if [ ${#NVME_DRIVES[@]} -eq 0 ]; then
+ echo "WARNING: No NVMe instance store drives found, using root volume"
+ sudo mkdir -p /data
+ exit 0
+fi
+
+if [ ${#NVME_DRIVES[@]} -eq 1 ]; then
+ # Single drive — format directly
+ TARGET="${NVME_DRIVES[0]}"
+ echo "Formatting $TARGET as XFS with reflink..."
+ sudo mkfs.xfs -f -m reflink=1 "$TARGET"
+else
+ # Multiple drives — create mdadm RAID-0 stripe
+ echo "Creating RAID-0 across ${#NVME_DRIVES[@]} drives..."
+ sudo apt-get install -y -qq mdadm
+ sudo mdadm --create /dev/md0 --level=0 --raid-devices=${#NVME_DRIVES[@]} "${NVME_DRIVES[@]}" --force --run
+ sudo mdadm --detail --scan | sudo tee -a /etc/mdadm/mdadm.conf
+ echo "Formatting /dev/md0 as XFS with reflink..."
+ sudo mkfs.xfs -f -m reflink=1 /dev/md0
+ TARGET="/dev/md0"
+fi
+
+sudo mkdir -p /data
+sudo mount "$TARGET" /data
+
+# Add to fstab (use UUID for reliability)
+UUID=$(sudo blkid -s UUID -o value "$TARGET")
+echo "UUID=$UUID /data xfs defaults,nofail 0 2" | sudo tee -a /etc/fstab
+
+sudo mkdir -p /data/sandboxes /data/firecracker/images /data/checkpoints
+echo "NVMe mounted at /data (XFS with reflink)"
+df -h /data
+SETUP_NVME
+
+ # Sync code and run QEMU host setup
+ log "Syncing codebase..."
+ rsync -az --progress \
+ -e "ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -i $SSH_KEY" \
+ --exclude '.git' --exclude 'bin/' --exclude 'node_modules/' \
+ --exclude '.claude/' --exclude '*.ext4' \
+ "$PROJECT_ROOT/" "ubuntu@${public_ip}:~/opensandbox/"
+
+ log "Running QEMU host setup (setup-azure-host.sh)..."
+ ssh_cmd "cd ~/opensandbox && sudo bash deploy/azure/setup-azure-host.sh"
+
+ log ""
+ log "=== c5d.metal spot instance created ==="
+ log " Instance: $instance_id ($INSTANCE_TYPE, spot)"
+ log " IP: $public_ip"
+ log " SSH: $0 ssh"
+ log " Deploy: $0 deploy"
+ log ""
+ log "Next: run '$0 deploy' to build and start services"
+}
+
+# --- Deploy ---
+cmd_deploy() {
+ local public_ip
+ public_ip=$(load_state PUBLIC_IP)
+ [ -n "$public_ip" ] || err "No instance found. Run 'create' first."
+
+ # Verify reachable
+ if ! ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 -o BatchMode=yes \
+ -i "$SSH_KEY" "ubuntu@$public_ip" "echo ok" &>/dev/null; then
+ err "Cannot reach $public_ip via SSH. Instance may be terminated (spot) or stopped."
+ fi
+
+ local branch
+ branch=$(git -C "$PROJECT_ROOT" rev-parse --abbrev-ref HEAD)
+ log "Deploying branch '$branch' to $public_ip..."
+
+ # Sync code
+ log "Syncing code..."
+ rsync -az --progress \
+ -e "ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -i $SSH_KEY" \
+ --exclude '.git' --exclude 'bin/' --exclude 'node_modules/' \
+ --exclude '.claude/' --exclude '*.ext4' \
+ "$PROJECT_ROOT/" "ubuntu@${public_ip}:~/opensandbox/"
+
+ # Build binaries on instance
+ log "Building binaries on instance..."
+ 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/
+
+# Stop services before overwriting binaries (avoids "text file busy")
+sudo systemctl stop opensandbox-worker 2>/dev/null || true
+sudo systemctl stop opensandbox-server 2>/dev/null || true
+
+sudo cp bin/opensandbox-server /usr/local/bin/
+sudo cp bin/opensandbox-worker /usr/local/bin/
+sudo cp bin/osb-agent /usr/local/bin/
+sudo chmod +x /usr/local/bin/opensandbox-server /usr/local/bin/opensandbox-worker /usr/local/bin/osb-agent
+echo "Binaries installed."
+BUILD
+
+ # Build rootfs if needed
+ log "Building rootfs (if needed)..."
+ ssh_cmd << 'ROOTFS'
+set -euo pipefail
+export PATH="/usr/local/go/bin:$HOME/go/bin:$PATH"
+if [ ! -f /data/firecracker/images/default.ext4 ]; then
+ echo "Building rootfs image..."
+ cd ~/opensandbox
+ sudo -E bash deploy/ec2/build-rootfs-docker.sh /usr/local/bin/osb-agent /data/firecracker/images default
+else
+ echo "Rootfs image already exists (delete /data/firecracker/images/default.ext4 to rebuild)."
+fi
+
+# Patch rootfs with guest kernel modules (vsock, overlay) and insmod symlink
+GUEST_MODDIR="/opt/opensandbox/guest-modules"
+if [ -d "$GUEST_MODDIR" ] && [ -f /data/firecracker/images/default.ext4 ]; then
+ echo "Patching rootfs with guest kernel modules..."
+ MNTDIR=$(mktemp -d)
+ sudo mount -o loop /data/firecracker/images/default.ext4 "$MNTDIR"
+
+ # Copy modules
+ sudo mkdir -p "$MNTDIR/lib/modules/vsock"
+ sudo cp "$GUEST_MODDIR"/*.ko "$MNTDIR/lib/modules/vsock/" 2>/dev/null || true
+
+ # Create insmod symlink (busybox applet)
+ if [ -f "$MNTDIR/bin/busybox" ] && [ ! -e "$MNTDIR/sbin/insmod" ]; then
+ sudo ln -sf /bin/busybox "$MNTDIR/sbin/insmod"
+ fi
+
+ # Update init script: load modules early (before overlay mount)
+ if ! grep -q 'lib/modules/vsock' "$MNTDIR/sbin/init" 2>/dev/null; then
+ sudo sed -i '/^mount -t devtmpfs devtmpfs \/dev$/a\
+\
+# Load kernel modules (needed for QEMU with modular kernel)\
+if [ -d /lib/modules/vsock ]; then\
+ for mod in /lib/modules/vsock/overlay.ko /lib/modules/vsock/vsock.ko /lib/modules/vsock/vmw_vsock_virtio_transport_common.ko /lib/modules/vsock/vmw_vsock_virtio_transport.ko; do\
+ [ -f "$mod" ] \&\& insmod "$mod" 2>/dev/null || true\
+ done\
+ echo "init: kernel modules loaded"\
+fi' "$MNTDIR/sbin/init"
+ fi
+
+ sudo umount "$MNTDIR"
+ rmdir "$MNTDIR"
+ echo "Rootfs patched with kernel modules."
+fi
+ROOTFS
+
+ # Setup env files
+ log "Installing env files..."
+ local private_ip
+ private_ip=$(aws_cmd ec2 describe-instances \
+ --instance-ids "$(load_state INSTANCE_ID)" \
+ --query 'Reservations[0].Instances[0].PrivateIpAddress' --output text)
+ local sandbox_domain="${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_VM_BACKEND=qemu
+OPENSANDBOX_QEMU_BIN=qemu-system-x86_64
+OPENSANDBOX_DATA_DIR=/data/sandboxes
+OPENSANDBOX_KERNEL_PATH=/opt/opensandbox/vmlinux
+OPENSANDBOX_IMAGES_DIR=/data/firecracker/images
+OPENSANDBOX_GRPC_ADVERTISE=${private_ip}:9090
+OPENSANDBOX_HTTP_ADDR=http://${private_ip}:8081
+OPENSANDBOX_JWT_SECRET=dev-jwt-secret
+OPENSANDBOX_WORKER_ID=w-qemu-dev-1
+OPENSANDBOX_REGION=use2
+OPENSANDBOX_MAX_CAPACITY=10
+OPENSANDBOX_DATABASE_URL=postgres://opensandbox:opensandbox@localhost:5432/opensandbox?sslmode=disable
+OPENSANDBOX_REDIS_URL=redis://localhost:6379
+OPENSANDBOX_SANDBOX_DOMAIN=${sandbox_domain}
+OPENSANDBOX_PORT=8081
+OPENSANDBOX_DEFAULT_SANDBOX_MEMORY_MB=1024
+OPENSANDBOX_DEFAULT_SANDBOX_CPUS=2
+OPENSANDBOX_NATS_URL=
+OPENSANDBOX_S3_BUCKET=opensandbox-checkpoints
+OPENSANDBOX_S3_REGION=us-east-2
+OPENSANDBOX_S3_ACCESS_KEY_ID=${S3_ACCESS_KEY_ID}
+OPENSANDBOX_S3_SECRET_ACCESS_KEY=${S3_SECRET_ACCESS_KEY}
+EOF
+
+# Server env
+sudo tee /etc/opensandbox/server.env > /dev/null << EOF
+OPENSANDBOX_MODE=server
+OPENSANDBOX_API_KEY=\$(echo -n "${API_KEY}" | sha256sum | cut -d' ' -f1)
+OPENSANDBOX_JWT_SECRET=dev-jwt-secret
+OPENSANDBOX_HTTP_ADDR=http://0.0.0.0:8080
+OPENSANDBOX_DATABASE_URL=postgres://opensandbox:opensandbox@localhost:5432/opensandbox?sslmode=disable
+OPENSANDBOX_REDIS_URL=redis://localhost:6379
+OPENSANDBOX_SANDBOX_DOMAIN=${sandbox_domain}
+OPENSANDBOX_PORT=8080
+OPENSANDBOX_REGION=use2
+EOF
+ENVSETUP
+
+ # Start services + iptables
+ log "Starting services..."
+ ssh_cmd << 'RESTART'
+set -euo pipefail
+# iptables for VM networking (172.16.0.0/16 QEMU guest subnet)
+DEFAULT_IFACE=$(ip route show default | awk '/default/ {print $5}' | head -1)
+sudo iptables -t nat -C POSTROUTING -s 172.16.0.0/16 -o "$DEFAULT_IFACE" -j MASQUERADE 2>/dev/null || \
+ sudo iptables -t nat -A POSTROUTING -s 172.16.0.0/16 -o "$DEFAULT_IFACE" -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
+
+# Redirect port 80 -> 8080 so UI is accessible on standard HTTP port
+sudo iptables -t nat -C PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080 2>/dev/null || \
+ sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080
+
+sudo systemctl daemon-reload
+sudo systemctl restart opensandbox-server || true
+sleep 2
+sudo systemctl restart opensandbox-worker || true
+echo "Services started."
+RESTART
+
+ # Wait for server + seed database
+ 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
+
+ log "Seeding database..."
+ ssh_cmd << SEED
+set -euo pipefail
+export PGPASSWORD=opensandbox
+KEY_HASH=\$(echo -n "${API_KEY}" | sha256sum | cut -d' ' -f1)
+
+# Wait for migrations
+for i in \$(seq 1 15); do
+ psql -h localhost -U opensandbox -d opensandbox -q -c 'SELECT 1 FROM orgs LIMIT 0' 2>/dev/null && break
+ echo "Waiting for migrations..."
+ sleep 2
+done
+
+# Create org
+psql -h localhost -U opensandbox -d opensandbox -c "
+ INSERT INTO orgs (id, name, slug) VALUES ('00000000-0000-0000-0000-000000000001', 'Dev Org', 'dev')
+ ON CONFLICT DO NOTHING;
+" 2>/dev/null || echo "DB seed: orgs insert failed (may already exist)"
+
+# Create API key
+psql -h localhost -U opensandbox -d opensandbox -c "
+ INSERT INTO api_keys (id, org_id, key_hash, key_prefix, name)
+ VALUES ('00000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000001', '\${KEY_HASH}', '$(echo -n "${API_KEY}" | cut -c1-8)', 'dev-key')
+ ON CONFLICT DO NOTHING;
+" 2>/dev/null || echo "DB seed: api_keys insert failed (may already exist)"
+
+echo "DB seeded (org + API key)"
+SEED
+
+ log ""
+ log "=== Deployment complete ==="
+ log " Server: http://${public_ip}:8080"
+ log " Worker: http://${public_ip}:8081"
+ log " API key: ${API_KEY}"
+ log ""
+ log "Test:"
+ log " curl -X POST http://${public_ip}:8080/api/sandboxes -H 'X-API-Key: ${API_KEY}'"
+}
+
+# --- SSH ---
+cmd_ssh() {
+ local public_ip
+ public_ip=$(load_state PUBLIC_IP)
+ [ -n "$public_ip" ] || err "No instance found. Run 'create' first."
+
+ shift 2>/dev/null || true
+ if [ $# -gt 0 ] && [ "$1" = "--" ]; then
+ shift
+ ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null \
+ -i "$SSH_KEY" "ubuntu@$public_ip" "$@"
+ else
+ ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null \
+ -i "$SSH_KEY" "ubuntu@$public_ip"
+ fi
+}
+
+# --- Status ---
+cmd_status() {
+ local instance_id
+ instance_id=$(load_state INSTANCE_ID)
+ if [ -z "$instance_id" ]; then
+ log "No QEMU dev environment found. Run '$0 create' to set one up."
+ return 0
+ fi
+
+ local state public_ip
+ state=$(aws_cmd ec2 describe-instances \
+ --instance-ids "$instance_id" \
+ --query 'Reservations[0].Instances[0].State.Name' \
+ --output text 2>/dev/null || echo "not-found")
+
+ # Refresh IP if running
+ if [ "$state" = "running" ]; then
+ public_ip=$(aws_cmd ec2 describe-instances \
+ --instance-ids "$instance_id" \
+ --query 'Reservations[0].Instances[0].PublicIpAddress' --output text)
+ save_state PUBLIC_IP "$public_ip"
+ else
+ public_ip=$(load_state PUBLIC_IP)
+ fi
+
+ echo ""
+ echo " Instance: $instance_id"
+ echo " Type: $INSTANCE_TYPE"
+ echo " Region: $AWS_REGION"
+ echo " State: $state"
+ echo " Public IP: ${public_ip:-n/a}"
+ echo ""
+ if [ "$state" = "running" ]; then
+ echo " Server: http://${public_ip}:8080"
+ echo " Worker: http://${public_ip}:8081"
+ echo " SSH: $0 ssh"
+ echo " Logs: $0 ssh -- sudo journalctl -u opensandbox-worker -f"
+ fi
+ echo ""
+}
+
+# --- Stop (not applicable for spot, but keep for on-demand fallback) ---
+cmd_stop() {
+ local instance_id
+ instance_id=$(load_state INSTANCE_ID)
+ [ -n "$instance_id" ] || err "No instance found."
+
+ log "WARNING: Spot instances cannot be stopped (only terminated)."
+ log "To terminate, use: $0 destroy"
+ log ""
+ log "If this is an on-demand instance, stopping..."
+ aws_cmd ec2 stop-instances --instance-ids "$instance_id" || true
+}
+
+# --- Start ---
+cmd_start() {
+ local instance_id
+ instance_id=$(load_state INSTANCE_ID)
+ [ -n "$instance_id" ] || err "No instance found."
+
+ log "Starting instance $instance_id..."
+ aws_cmd ec2 start-instances --instance-ids "$instance_id"
+ aws_cmd ec2 wait instance-running --instance-ids "$instance_id"
+
+ local public_ip
+ public_ip=$(aws_cmd ec2 describe-instances \
+ --instance-ids "$instance_id" \
+ --query 'Reservations[0].Instances[0].PublicIpAddress' --output text)
+ save_state PUBLIC_IP "$public_ip"
+ log "Instance running. Public IP: $public_ip"
+}
+
+# --- Destroy ---
+cmd_destroy() {
+ local instance_id
+ instance_id=$(load_state INSTANCE_ID)
+ if [ -z "$instance_id" ]; then
+ log "No instance found."
+ return 0
+ fi
+
+ echo "This will TERMINATE instance $instance_id (all NVMe data will be lost)."
+ read -r -p "Are you sure? (y/N) " confirm
+ if [[ ! "$confirm" =~ ^[yY]$ ]]; then
+ echo "Cancelled."
+ return 0
+ fi
+
+ log "Terminating instance $instance_id..."
+ aws_cmd ec2 terminate-instances --instance-ids "$instance_id" > /dev/null
+ rm -f "$STATE_FILE"
+ log "Instance terminated. State file cleaned up."
+}
+
+# --- Stop old a1.metal ---
+cmd_stop_old() {
+ local old_instance_id="${1:-}"
+ if [ -z "$old_instance_id" ]; then
+ echo "Usage: $0 stop-old <instance-id>"
+ echo "Example: $0 stop-old i-0e0e5d9a883add97f"
+ exit 1
+ fi
+
+ log "Stopping old a1.metal instance $old_instance_id (EBS preserved)..."
+ aws_cmd ec2 stop-instances --instance-ids "$old_instance_id"
+ log "Instance stopping. EBS will be preserved (~\$8/mo)."
+}
+
+# --- Main ---
+CMD="${1:-help}"
+case "$CMD" in
+ create) cmd_create ;;
+ deploy) cmd_deploy ;;
+ ssh) shift; cmd_ssh "$@" ;;
+ status) cmd_status ;;
+ stop) cmd_stop ;;
+ start) cmd_start ;;
+ destroy) cmd_destroy ;;
+ stop-old) shift; cmd_stop_old "$@" ;;
+ *)
+ echo "Usage: $0 {create|deploy|ssh|status|stop|start|destroy|stop-old}"
+ echo ""
+ echo "Commands:"
+ echo " create Launch c5d.metal spot instance with QEMU setup"
+ echo " deploy Build and deploy code to instance"
+ echo " ssh SSH into instance (use -- for remote commands)"
+ echo " status Show instance status"
+ echo " stop Stop instance (on-demand only; spot cannot be stopped)"
+ echo " start Start a stopped instance"
+ echo " destroy Terminate instance (NVMe data lost)"
+ echo " stop-old Stop the old a1.metal ARM instance (preserves EBS)"
+ echo ""
+ echo "Environment:"
+ echo " AWS_PROFILE=$AWS_PROFILE AWS_REGION=$AWS_REGION"
+ echo " INSTANCE_TYPE=$INSTANCE_TYPE API_KEY=$API_KEY"
+ echo ""
+ echo "Quick start:"
+ echo " $0 create # Launch c5d.metal spot (~\$1.40/hr)"
+ echo " $0 deploy # Build + deploy QEMU backend"
+ echo " $0 ssh # SSH into instance"
+ ;;
+esac
diff --git a/internal/qemu/agent_client.go b/internal/qemu/agent_client.go
index 6ae5ac13..36219a68 100644
--- a/internal/qemu/agent_client.go
+++ b/internal/qemu/agent_client.go
@@ -122,9 +122,35 @@ func (c *rawVsockConn) Close() error {
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 }
+func (c *rawVsockConn) SetDeadline(t time.Time) error {
+ if err := c.SetReadDeadline(t); err != nil {
+ return err
+ }
+ return c.SetWriteDeadline(t)
+}
+
+func (c *rawVsockConn) SetReadDeadline(t time.Time) error {
+ return setSockTimeout(c.fd, unix.SO_RCVTIMEO, t)
+}
+
+func (c *rawVsockConn) SetWriteDeadline(t time.Time) error {
+ return setSockTimeout(c.fd, unix.SO_SNDTIMEO, t)
+}
+
+// setSockTimeout sets SO_RCVTIMEO or SO_SNDTIMEO on a raw fd.
+// A zero time clears the timeout (blocks indefinitely).
+func setSockTimeout(fd int, opt int, t time.Time) error {
+ var tv unix.Timeval
+ if !t.IsZero() {
+ d := time.Until(t)
+ if d <= 0 {
+ d = 1 * time.Microsecond // already expired — set minimal timeout
+ }
+ tv = unix.NsecToTimeval(int64(d))
+ }
+ // Zero tv clears the timeout
+ return unix.SetsockoptTimeval(fd, unix.SOL_SOCKET, opt, &tv)
+}
type vsockAddr struct{}
@@ -294,3 +320,47 @@ 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) {
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ addr := fmt.Sprintf("%s:%d", guestIP, 1024)
+ conn, err := grpc.DialContext(ctx,
+ addr,
+ 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.WithDefaultCallOptions(
+ grpc.MaxCallRecvMsgSize(64*1024*1024),
+ grpc.MaxCallSendMsgSize(64*1024*1024),
+ ),
+ )
+ if err != nil {
+ return nil, fmt.Errorf("connect to agent at %s: %w", addr, err)
+ }
+
+ return &AgentClient{
+ conn: conn,
+ 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 ab8b2370..9cac7639 100644
--- a/internal/qemu/manager.go
+++ b/internal/qemu/manager.go
@@ -86,8 +86,10 @@ type Manager struct {
uploadWg sync.WaitGroup
// Golden snapshot for fast VM creation
- goldenDir string // path to golden snapshot dir (empty = not available)
- goldenCID uint32 // CID used when the golden snapshot was created
+ goldenDir string // path to golden snapshot dir (empty = not available)
+ goldenCID uint32 // CID used when the golden snapshot was created
+ goldenGuestIP string // guest IP baked into the golden snapshot
+ goldenHostIP string // host IP of the golden subnet (for temp addr on TAP)
}
// NewManager creates a new QEMU-backed sandbox manager.
@@ -143,16 +145,22 @@ func NewManager(cfg Config) (*Manager, error) {
func (m *Manager) PrepareGoldenSnapshot() error {
goldenDir := filepath.Join(m.cfg.DataDir, "golden")
memFile := filepath.Join(goldenDir, "mem")
- rootfsFile := filepath.Join(goldenDir, "rootfs.ext4")
+ rootfsFile := filepath.Join(goldenDir, "rootfs.qcow2")
// If golden snapshot already exists, just use it
- if (fileExists(memFile) || fileExists(memFile+".zst")) && fileExists(rootfsFile) {
+ if (fileExists(memFile) || fileExists(memFile+".zst")) && (fileExists(rootfsFile) || fileExists(filepath.Join(goldenDir, "rootfs.ext4"))) {
m.goldenDir = goldenDir
- // Read saved golden CID
+ // Read saved golden CID + guest IP
if cidBytes, err := os.ReadFile(filepath.Join(goldenDir, "cid")); err == nil {
fmt.Sscanf(string(cidBytes), "%d", &m.goldenCID)
}
- log.Printf("qemu: golden snapshot already exists at %s (CID=%d)", goldenDir, m.goldenCID)
+ if ipBytes, err := os.ReadFile(filepath.Join(goldenDir, "guest_ip")); err == nil {
+ m.goldenGuestIP = string(ipBytes)
+ }
+ if ipBytes, err := os.ReadFile(filepath.Join(goldenDir, "host_ip")); err == nil {
+ m.goldenHostIP = string(ipBytes)
+ }
+ log.Printf("qemu: golden snapshot already exists at %s (CID=%d, guestIP=%s)", goldenDir, m.goldenCID, m.goldenGuestIP)
return nil
}
@@ -172,9 +180,10 @@ func (m *Manager) PrepareGoldenSnapshot() error {
return fmt.Errorf("prepare golden rootfs: %w", err)
}
- // Create a small workspace (won't be used, just needs to exist for QEMU args)
- workspaceFile := filepath.Join(goldenDir, "workspace.ext4")
- if err := CreateWorkspace(workspaceFile, 64); err != nil {
+ // Create workspace as qcow2 — must match DefaultDiskMB so the virtio-blk
+ // device geometry in the golden migration state matches sandbox workspaces.
+ workspaceFile := filepath.Join(goldenDir, "workspace.qcow2")
+ if err := CreateWorkspace(workspaceFile, m.cfg.DefaultDiskMB); err != nil {
return fmt.Errorf("create golden workspace: %w", err)
}
@@ -243,6 +252,22 @@ func (m *Manager) PrepareGoldenSnapshot() error {
}
log.Printf("qemu: golden VM booted, agent ready (%dms)", time.Since(t0).Milliseconds())
+ // 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
+ // workspace.qcow2 that createFromGolden boots with.
+ umountCtx, umountCancel := context.WithTimeout(context.Background(), 10*time.Second)
+ _, umountErr := agentClient.Exec(umountCtx, &pb.ExecRequest{
+ Command: "/bin/sh",
+ Args: []string{"-c", "umount /workspace 2>/dev/null; sync"},
+ })
+ umountCancel()
+ if umountErr != nil {
+ log.Printf("qemu: golden: umount /workspace failed (non-fatal): %v", umountErr)
+ } else {
+ log.Printf("qemu: golden: /workspace unmounted and synced")
+ }
+
// Close agent connection before migration. Use a timeout because gRPC's
// graceful close over vsock can hang if vhost-vsock doesn't drain cleanly.
closeDone := make(chan struct{})
@@ -307,9 +332,13 @@ func (m *Manager) PrepareGoldenSnapshot() error {
m.goldenDir = goldenDir
m.goldenCID = goldenCID
+ m.goldenGuestIP = netCfg.GuestIP
+ m.goldenHostIP = netCfg.HostIP
_ = os.WriteFile(filepath.Join(goldenDir, "cid"), []byte(fmt.Sprintf("%d", goldenCID)), 0644)
- log.Printf("qemu: golden snapshot ready (%dms total, mem=%s, CID=%d)",
- time.Since(t0).Milliseconds(), memFile, goldenCID)
+ _ = os.WriteFile(filepath.Join(goldenDir, "guest_ip"), []byte(netCfg.GuestIP), 0644)
+ _ = os.WriteFile(filepath.Join(goldenDir, "host_ip"), []byte(netCfg.HostIP), 0644)
+ log.Printf("qemu: golden snapshot ready (%dms total, mem=%s, CID=%d, guestIP=%s)",
+ time.Since(t0).Milliseconds(), memFile, goldenCID, netCfg.GuestIP)
return nil
}
@@ -329,15 +358,16 @@ func (m *Manager) createFromGolden(ctx context.Context, cfg types.SandboxConfig,
return nil, fmt.Errorf("mkdir sandbox dir: %w", err)
}
- // Copy golden rootfs (this is the base — each VM gets its own copy)
- rootfsPath := filepath.Join(sandboxDir, "rootfs.ext4")
- if err := copyFileReflink(filepath.Join(m.goldenDir, "rootfs.ext4"), rootfsPath); err != nil {
+ // Copy golden rootfs as qcow2 overlay (golden snapshot was taken with qcow2 drives)
+ rootfsPath := filepath.Join(sandboxDir, "rootfs.qcow2")
+ goldenRootfs := filepath.Join(m.goldenDir, "rootfs.qcow2")
+ if err := copyFileReflink(goldenRootfs, rootfsPath); err != nil {
os.RemoveAll(sandboxDir)
return nil, fmt.Errorf("copy golden rootfs: %w", err)
}
- // Create fresh workspace
- workspacePath := filepath.Join(sandboxDir, "workspace.ext4")
+ // Create fresh workspace as qcow2 (matching golden snapshot format)
+ workspacePath := filepath.Join(sandboxDir, "workspace.qcow2")
diskMB := m.cfg.DefaultDiskMB
if err := CreateWorkspace(workspacePath, diskMB); err != nil {
os.RemoveAll(sandboxDir)
@@ -494,16 +524,14 @@ func (m *Manager) createFromGolden(ctx context.Context, cfg types.SandboxConfig,
bootArgs: bootArgs,
}
- // After migration restore, the vsock CID from the snapshot (golden CID) may
- // override the CLI arg. Try both the new CID and the golden CID.
+ // Connect to agent via vsock. Try new CID first, fall back to golden CID
+ // (migration may preserve the golden CID in the virtio device).
var agentClient *AgentClient
- // Try new CID first (quick attempt)
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 {
- log.Printf("qemu: golden-create %s: connected via golden CID=%d (migration preserved CID)", id, m.goldenCID)
guestCID = m.goldenCID
vm.guestCID = guestCID
}
@@ -522,7 +550,18 @@ func (m *Manager) createFromGolden(ctx context.Context, cfg types.SandboxConfig,
// Patch network inside the guest — the snapshot had the golden VM's IP
if err := patchGuestNetwork(context.Background(), agentClient, netCfg); err != nil {
log.Printf("qemu: golden-create %s: network patch failed: %v", id, err)
- // Non-fatal for now — connectivity might still work via TAP
+ }
+
+ // Mount /workspace — the golden snapshot was taken with /workspace unmounted
+ // to keep the vdb device state clean for fresh workspace qcow2 files.
+ mountCtx, mountCancel := context.WithTimeout(context.Background(), 10*time.Second)
+ _, mountErr := agentClient.Exec(mountCtx, &pb.ExecRequest{
+ Command: "/bin/sh",
+ Args: []string{"-c", "mount /dev/vdb /workspace 2>/dev/null || true"},
+ })
+ mountCancel()
+ if mountErr != nil {
+ log.Printf("qemu: golden-create %s: mount /workspace failed: %v", id, mountErr)
}
log.Printf("qemu: golden-create %s: network patched (%dms)", id, time.Since(t0).Milliseconds())
@@ -659,6 +698,15 @@ 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 {
+ // Detect drive format from file extension
+ rootfsFmt := "qcow2"
+ if strings.HasSuffix(rootfsPath, ".ext4") {
+ rootfsFmt = "raw"
+ }
+ wsFmt := "qcow2"
+ if strings.HasSuffix(workspacePath, ".ext4") {
+ wsFmt = "raw"
+ }
return []string{
"-machine", "q35,accel=kvm",
"-cpu", "host",
@@ -666,8 +714,8 @@ func (m *Manager) buildQEMUArgs(cpus, memMB int, rootfsPath, workspacePath, tapN
"-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),
+ "-drive", fmt.Sprintf("file=%s,format=%s,if=virtio,cache=writethrough", rootfsPath, rootfsFmt),
+ "-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),
@@ -705,8 +753,8 @@ func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (*types.S
return nil, fmt.Errorf("mkdir sandbox dir: %w", err)
}
- rootfsPath := filepath.Join(sandboxDir, "rootfs.ext4")
- workspacePath := filepath.Join(sandboxDir, "workspace.ext4")
+ rootfsPath := filepath.Join(sandboxDir, "rootfs.qcow2")
+ workspacePath := filepath.Join(sandboxDir, "workspace.qcow2")
if cfg.TemplateRootfsKey != "" {
srcRootfs := strings.TrimPrefix(cfg.TemplateRootfsKey, "local://")
@@ -853,7 +901,7 @@ func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (*types.S
bootArgs: bootArgs,
}
- // Wait for agent via AF_VSOCK
+ // Wait for agent via 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)
@@ -947,6 +995,46 @@ 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) {
+ t0 := time.Now()
+ deadline := t0.Add(timeout)
+ var lastErr error
+ attempts := 0
+
+ for time.Now().Before(deadline) {
+ attempts++
+ tAttempt := time.Now()
+ client, err := NewAgentClientTCP(guestIP)
+ 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)
+ }
+ 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
+ time.Sleep(50 * time.Millisecond)
+ continue
+ }
+
+ log.Printf("qemu: waitForAgentTCP: connected to %s on attempt %d (%dms total)",
+ guestIP, 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()
@@ -1330,24 +1418,371 @@ func (m *Manager) TemplateCachePath(templateID, filename string) string {
return ""
}
-// CreateCheckpoint is not implemented in the QEMU backend.
+// checkpointCacheDir returns the local cache directory for a checkpoint.
+func (m *Manager) checkpointCacheDir(checkpointID string) string {
+ return filepath.Join(m.cfg.DataDir, "checkpoints", checkpointID)
+}
+
+// CheckpointCachePath returns the path to a specific file in the checkpoint cache.
+func (m *Manager) CheckpointCachePath(checkpointID, filename string) string {
+ p := filepath.Join(m.checkpointCacheDir(checkpointID), filename)
+ if fileExists(p) {
+ return p
+ }
+ return ""
+}
+
+// CreateCheckpoint creates an internal VM snapshot using QEMU's savevm.
+// The snapshot is stored inside the qcow2 drive files — no external migration file needed.
+// The VM pauses briefly for the snapshot, then resumes automatically.
func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID string, checkpointStore *storage.CheckpointStore, onReady func()) (rootfsKey, workspaceKey string, err error) {
- return "", "", ErrNotImplemented
+ vm, err := m.getVM(sandboxID)
+ if err != nil {
+ return "", "", err
+ }
+
+ t0 := time.Now()
+
+ if vm.qmp == nil {
+ return "", "", fmt.Errorf("no QMP client for VM %s", sandboxID)
+ }
+
+ // Sync filesystem before snapshot
+ 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: CreateCheckpoint %s/%s: sync failed: %v", sandboxID, checkpointID, syncErr)
+ }
+ }
+
+ // savevm creates an internal snapshot — memory + device state + disk deltas
+ // all stored inside the qcow2 files. The VM pauses during savevm and resumes after.
+ snapshotName := "cp-" + checkpointID
+ if err := vm.qmp.SaveVM(snapshotName); err != nil {
+ return "", "", fmt.Errorf("savevm failed: %w", err)
+ }
+ log.Printf("qemu: CreateCheckpoint %s/%s: savevm complete (%dms)", sandboxID, checkpointID, time.Since(t0).Milliseconds())
+
+ // Also cache the drive files for ForkFromCheckpoint (which needs a separate QEMU process)
+ cacheDir := m.checkpointCacheDir(checkpointID)
+ rootfsKey = fmt.Sprintf("checkpoints/%s/%s/rootfs.tar.zst", sandboxID, checkpointID)
+ workspaceKey = fmt.Sprintf("checkpoints/%s/%s/workspace.tar.zst", sandboxID, checkpointID)
+
+ go func() {
+ if err := os.MkdirAll(filepath.Join(cacheDir, "snapshot"), 0755); err != nil {
+ log.Printf("qemu: checkpoint %s: mkdir cache failed: %v", checkpointID, err)
+ if onReady != nil {
+ onReady()
+ }
+ return
+ }
+
+ // Copy qcow2 drives (they contain the snapshot data)
+ srcRootfs := filepath.Join(vm.sandboxDir, "rootfs.qcow2")
+ srcWorkspace := filepath.Join(vm.sandboxDir, "workspace.qcow2")
+ _ = copyFileReflink(srcRootfs, filepath.Join(cacheDir, "rootfs.qcow2"))
+ _ = copyFileReflink(srcWorkspace, filepath.Join(cacheDir, "workspace.qcow2"))
+
+ // Write metadata
+ meta := &SnapshotMeta{
+ SandboxID: vm.ID,
+ Network: vm.network,
+ GuestCID: vm.guestCID,
+ GuestMAC: vm.guestMAC,
+ BootArgs: vm.bootArgs,
+ CpuCount: vm.CpuCount,
+ MemoryMB: vm.MemoryMB,
+ Template: vm.Template,
+ GuestPort: vm.GuestPort,
+ SnapshotedAt: time.Now(),
+ }
+ metaJSON, _ := json.Marshal(meta)
+ _ = os.WriteFile(filepath.Join(cacheDir, "snapshot", "snapshot-meta.json"), metaJSON, 0644)
+ _ = os.WriteFile(filepath.Join(cacheDir, "snapshot-name"), []byte(snapshotName), 0644)
+
+ log.Printf("qemu: checkpoint %s: cache saved (%dms)", checkpointID, time.Since(t0).Milliseconds())
+ if onReady != nil {
+ onReady()
+ }
+ }()
+
+ return rootfsKey, workspaceKey, nil
}
-// RestoreFromCheckpoint is not implemented in the QEMU backend.
+// RestoreFromCheckpoint reverts a running sandbox to a checkpoint using QEMU's loadvm.
+// The VM stays running — no process restart needed. ~100-200ms.
func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpointID string) error {
- return ErrNotImplemented
+ vm, err := m.getVM(sandboxID)
+ if err != nil {
+ return err
+ }
+
+ t0 := time.Now()
+
+ if vm.qmp == nil {
+ return fmt.Errorf("no QMP client for VM %s", sandboxID)
+ }
+
+ snapshotName := "cp-" + checkpointID
+
+ // Close agent before loadvm (vsock state will revert)
+ if vm.agent != nil {
+ closeDone := make(chan struct{})
+ go func() { vm.agent.Close(); close(closeDone) }()
+ select {
+ case <-closeDone:
+ case <-time.After(2 * time.Second):
+ }
+ vm.agent = nil
+ }
+
+ // 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)
+ }
+
+ // 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)
+ }
+
+ // Resume after loadvm
+ if err := vm.qmp.Cont(); err != nil {
+ return fmt.Errorf("cont after loadvm failed: %w", err)
+ }
+
+ // Reconnect agent via TCP
+ agent, err := m.waitForAgent(context.Background(), vm.guestCID, 10*time.Second)
+ if err != nil {
+ return fmt.Errorf("agent reconnect after loadvm: %w", err)
+ }
+ vm.agent = agent
+
+ log.Printf("qemu: RestoreFromCheckpoint %s/%s: loadvm complete (%dms)", sandboxID, checkpointID, time.Since(t0).Milliseconds())
+ return nil
}
-// ForkFromCheckpoint is not implemented in the QEMU backend.
+// ForkFromCheckpoint creates a new sandbox from a checkpoint's saved state.
+// The new sandbox gets its own network, CID, and drives (reflinked from cache).
func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, cfg types.SandboxConfig) (*types.Sandbox, error) {
- return nil, ErrNotImplemented
-}
+ t0 := time.Now()
+ cacheDir := m.checkpointCacheDir(checkpointID)
+ metaPath := filepath.Join(cacheDir, "snapshot", "snapshot-meta.json")
-// CheckpointCachePath returns "" — not implemented.
-func (m *Manager) CheckpointCachePath(checkpointID, filename string) string {
- return ""
+ // qcow2 drives contain the savevm snapshot data
+ cachedRootfs := filepath.Join(cacheDir, "rootfs.qcow2")
+ cachedWorkspace := filepath.Join(cacheDir, "workspace.qcow2")
+ if !fileExists(cachedRootfs) || !fileExists(cachedWorkspace) {
+ return nil, fmt.Errorf("checkpoint %s: qcow2 files not found in cache", checkpointID)
+ }
+
+ // Read snapshot name
+ snapshotName := "cp-" + checkpointID
+ if data, err := os.ReadFile(filepath.Join(cacheDir, "snapshot-name")); err == nil {
+ snapshotName = strings.TrimSpace(string(data))
+ }
+
+ var meta SnapshotMeta
+ if data, err := os.ReadFile(metaPath); err == nil {
+ json.Unmarshal(data, &meta)
+ }
+
+ id := cfg.SandboxID
+ if id == "" {
+ id = "sb-" + uuid.New().String()[:8]
+ }
+ 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)
+ }
+
+ // Copy qcow2 drives (contain snapshot data)
+ rootfsPath := filepath.Join(sandboxDir, "rootfs.qcow2")
+ workspacePath := filepath.Join(sandboxDir, "workspace.qcow2")
+ if err := copyFileReflink(cachedRootfs, rootfsPath); err != nil {
+ os.RemoveAll(sandboxDir)
+ return nil, fmt.Errorf("copy rootfs: %w", err)
+ }
+ if err := copyFileReflink(cachedWorkspace, workspacePath); err != nil {
+ os.RemoveAll(sandboxDir)
+ return nil, fmt.Errorf("copy 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)
+ 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)
+ }
+
+ // Start QEMU paused — we'll loadvm then cont
+ args := m.buildQEMUArgs(cpus, memMB, rootfsPath, workspacePath,
+ netCfg.TAPName, guestMAC, guestCID, qmpSockPath, bootArgs)
+ args = append(args, "-S") // start paused
+
+ 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 for fork: %w", err)
+ }
+ logFile.Close()
+
+ 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)
+ }
+
+ // loadvm restores from the internal snapshot in the qcow2 drives
+ if err := qmpClient.LoadVM(snapshotName); err != nil {
+ qmpClient.Close()
+ cmd.Process.Kill()
+ cmd.Wait()
+ m.cleanupVM(netCfg, sandboxDir)
+ return nil, fmt.Errorf("loadvm: %w", err)
+ }
+
+ if err := qmpClient.Cont(); err != nil {
+ qmpClient.Close()
+ cmd.Process.Kill()
+ cmd.Wait()
+ m.cleanupVM(netCfg, sandboxDir)
+ return nil, fmt.Errorf("QMP cont: %w", err)
+ }
+ log.Printf("qemu: ForkFromCheckpoint %s → %s: VM resumed (%dms)", checkpointID, id, time.Since(t0).Milliseconds())
+
+ // Connect agent via TCP
+ var agent *AgentClient
+ agent, err = m.waitForAgent(context.Background(), guestCID, 10*time.Second)
+ if err != nil {
+ qmpClient.Close()
+ cmd.Process.Kill()
+ cmd.Wait()
+ m.cleanupVM(netCfg, sandboxDir)
+ return nil, fmt.Errorf("agent connect: %w", err)
+ }
+
+ // Patch network (snapshot had different IP)
+ if err := patchGuestNetwork(context.Background(), agent, netCfg); err != nil {
+ log.Printf("qemu: ForkFromCheckpoint %s: network patch failed: %v", id, err)
+ }
+
+ // Set env vars
+ if len(cfg.Envs) > 0 {
+ envCtx, envCancel := context.WithTimeout(context.Background(), 5*time.Second)
+ agent.SetEnvs(envCtx, cfg.Envs)
+ envCancel()
+ }
+
+ now := time.Now()
+ timeout := time.Duration(cfg.Timeout) * time.Second
+ if timeout <= 0 {
+ timeout = 300 * time.Second
+ }
+
+ 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,
+ }
+
+ m.mu.Lock()
+ m.vms[id] = vm
+ m.mu.Unlock()
+
+ log.Printf("qemu: ForkFromCheckpoint %s → %s: complete (%dms, port=%d, tap=%s)",
+ checkpointID, id, time.Since(t0).Milliseconds(), hostPort, netCfg.TAPName)
+
+ return &types.Sandbox{
+ ID: id,
+ Template: meta.Template,
+ Status: types.SandboxStatusRunning,
+ StartedAt: now,
+ EndAt: now.Add(timeout),
+ CpuCount: cpus,
+ MemoryMB: memMB,
+ HostPort: hostPort,
+ }, nil
}
// getVM retrieves a VM by ID.
diff --git a/internal/qemu/qmp.go b/internal/qemu/qmp.go
index 66df8156..f2be6fbb 100644
--- a/internal/qemu/qmp.go
+++ b/internal/qemu/qmp.go
@@ -215,6 +215,35 @@ func (q *QMPClient) WaitMigration(timeout time.Duration) error {
return fmt.Errorf("migration timed out after %v", timeout)
}
+// SaveVM creates an internal VM snapshot (memory + device state + disk deltas).
+// Requires all drives to be qcow2 format. The snapshot is stored inside the qcow2 files.
+func (q *QMPClient) SaveVM(name string) error {
+ _, err := q.execute(qmpCommand{
+ Execute: "human-monitor-command",
+ Arguments: map[string]string{"command-line": "savevm " + name},
+ }, 5*time.Minute)
+ return err
+}
+
+// LoadVM restores an internal VM snapshot. The VM reverts to the exact state
+// when SaveVM was called — memory, devices, and disk contents all revert.
+func (q *QMPClient) LoadVM(name string) error {
+ _, err := q.execute(qmpCommand{
+ Execute: "human-monitor-command",
+ Arguments: map[string]string{"command-line": "loadvm " + name},
+ }, 5*time.Minute)
+ return err
+}
+
+// DeleteVM deletes an internal VM snapshot.
+func (q *QMPClient) DeleteVM(name string) error {
+ _, err := q.execute(qmpCommand{
+ Execute: "human-monitor-command",
+ Arguments: map[string]string{"command-line": "delvm " + name},
+ }, 30*time.Second)
+ return err
+}
+
// Execute sends an arbitrary QMP command with the given arguments.
func (q *QMPClient) Execute(command string, args map[string]interface{}) error {
cmd := qmpCommand{Execute: command}
diff --git a/internal/qemu/rootfs.go b/internal/qemu/rootfs.go
index a23ea386..b6a6f16a 100644
--- a/internal/qemu/rootfs.go
+++ b/internal/qemu/rootfs.go
@@ -8,50 +8,119 @@ import (
"strings"
)
-// PrepareRootfs copies a base rootfs image to the sandbox directory.
-// Uses reflink (--reflink=auto) on XFS/btrfs for instant copy-on-write.
+// PrepareRootfs creates a qcow2 overlay backed by the base rootfs image.
+// This is instant — no data is copied. Writes go to the qcow2 overlay,
+// reads fall through to the raw backing file. Works on any filesystem.
func PrepareRootfs(baseImage, destPath string) error {
if err := os.MkdirAll(filepath.Dir(destPath), 0755); err != nil {
return fmt.Errorf("mkdir for rootfs: %w", err)
}
+ // Use absolute path for backing file
+ absBase, err := filepath.Abs(baseImage)
+ if err != nil {
+ return fmt.Errorf("abs path for base image: %w", err)
+ }
+
+ // qemu-img create -f qcow2 -b /abs/path/base.ext4 -F raw dest.qcow2
+ cmd := exec.Command("qemu-img", "create",
+ "-f", "qcow2",
+ "-b", absBase,
+ "-F", "raw",
+ destPath)
+ if out, err := cmd.CombinedOutput(); err != nil {
+ return fmt.Errorf("create qcow2 overlay: %w (%s)", err, strings.TrimSpace(string(out)))
+ }
+
+ return nil
+}
+
+// PrepareRootfsRaw copies a base rootfs image using reflink (for golden snapshot).
+func PrepareRootfsRaw(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
+}
+// CreateWorkspaceRaw creates a raw ext4 workspace (for golden snapshot path).
+func CreateWorkspaceRaw(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", 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
}
-// CreateWorkspace creates a sparse ext4 filesystem for the sandbox workspace.
+// CreateWorkspace creates a qcow2 workspace disk with an ext4 filesystem.
+// First creates a raw ext4 image, then converts to qcow2 for snapshot support.
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)
+ // Create raw ext4 first
+ rawPath := path + ".raw"
+ f, err := os.Create(rawPath)
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)
+ os.Remove(rawPath)
return fmt.Errorf("truncate workspace: %w", err)
}
f.Close()
- cmd := exec.Command("mkfs.ext4", "-q", "-F",
+ mkfsCmd := exec.Command("mkfs.ext4", "-q", "-F",
"-L", "workspace",
- "-O", "^has_journal",
- path)
- if out, err := cmd.CombinedOutput(); err != nil {
- os.Remove(path)
+ rawPath)
+ if out, err := mkfsCmd.CombinedOutput(); err != nil {
+ os.Remove(rawPath)
return fmt.Errorf("mkfs.ext4: %w (%s)", err, strings.TrimSpace(string(out)))
}
+ // Convert to qcow2
+ cmd := exec.Command("qemu-img", "convert",
+ "-f", "raw", "-O", "qcow2",
+ rawPath, path)
+ if out, err := cmd.CombinedOutput(); err != nil {
+ os.Remove(rawPath)
+ return fmt.Errorf("convert workspace to qcow2: %w (%s)", err, strings.TrimSpace(string(out)))
+ }
+ os.Remove(rawPath)
+
return nil
}
+// detectDrivePath returns the actual path for a drive file (rootfs or workspace),
+// preferring qcow2 if it exists, falling back to ext4.
+func detectDrivePath(sandboxDir, prefix string) string {
+ qcow2 := filepath.Join(sandboxDir, prefix+".qcow2")
+ if _, err := os.Stat(qcow2); err == nil {
+ return qcow2
+ }
+ return filepath.Join(sandboxDir, prefix+".ext4")
+}
+
// ResolveBaseImage finds the base rootfs image for a given template.
func ResolveBaseImage(imagesDir, template string) (string, error) {
if template == "" {
diff --git a/internal/qemu/snapshot.go b/internal/qemu/snapshot.go
index 5f9db886..7006ee03 100644
--- a/internal/qemu/snapshot.go
+++ b/internal/qemu/snapshot.go
@@ -58,20 +58,22 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointSto
memFile := filepath.Join(snapshotDir, "mem")
- // Step 1: Sync filesystems inside the VM
+ // 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.
if vm.agent != nil {
- syncCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
- _, syncErr := vm.agent.Exec(syncCtx, &pb.ExecRequest{
- Command: "sync",
+ 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"},
})
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())
+ log.Printf("qemu: hibernate %s: guest shutdown done (%dms)", vm.ID, time.Since(t0).Milliseconds())
- // Step 2: Close gRPC connection — vsock must be inactive before migration.
+ // Step 2: Close host-side gRPC connection and wait for vsock to drain.
if vm.agent != nil {
vm.agent.Close()
vm.agent = nil
@@ -123,8 +125,8 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointSto
GuestCID: vm.guestCID,
GuestMAC: vm.guestMAC,
BootArgs: vm.bootArgs,
- RootfsPath: filepath.Join(vm.sandboxDir, "rootfs.ext4"),
- WorkspacePath: filepath.Join(vm.sandboxDir, "workspace.ext4"),
+ RootfsPath: detectDrivePath(vm.sandboxDir, "rootfs"),
+ WorkspacePath: detectDrivePath(vm.sandboxDir, "workspace"),
CpuCount: vm.CpuCount,
MemoryMB: vm.MemoryMB,
Template: vm.Template,
@@ -160,6 +162,8 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointSto
// Step 9: Archive + upload to S3 in the background.
sandboxDir := vm.sandboxDir
sandboxID := vm.ID
+ // Determine workspace filename (qcow2 or ext4) for archiving
+ workspaceFile := filepath.Base(detectDrivePath(sandboxDir, "workspace"))
m.uploadWg.Add(1)
go func() {
defer m.uploadWg.Done()
@@ -169,7 +173,7 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointSto
if err := createArchive(archivePath, sandboxDir, []string{
"snapshot/mem",
"snapshot/snapshot-meta.json",
- "workspace.ext4",
+ workspaceFile,
}); err != nil {
log.Printf("qemu: async archive failed for %s: %v", sandboxID, err)
return
@@ -284,35 +288,22 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, c
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)
- }
- }
+ // Step 4: Ensure workspace exists
+ workspacePath := detectDrivePath(sandboxDir, "workspace")
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)
+ // Step 5: Golden restore — boot from golden snapshot with user's workspace.
+ // Agent uses TCP over virtio-net (survives migration), so we can restore
+ // from the golden migration state instead of cold booting.
+ if m.goldenDir == "" {
+ return nil, fmt.Errorf("golden snapshot not available for wake")
+ }
+
+ netCfg, err := m.subnets.Allocate()
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)
- }
+ return nil, fmt.Errorf("allocate subnet: %w", err)
}
if err := CreateTAP(netCfg); err != nil {
m.subnets.Release(netCfg.TAPName)
@@ -337,113 +328,18 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, c
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
+ // Fresh rootfs from golden (COW copy, instant)
+ rootfsPath := filepath.Join(sandboxDir, "rootfs.qcow2")
+ os.Remove(rootfsPath)
+ goldenRootfs := filepath.Join(m.goldenDir, "rootfs.qcow2")
+ if err := copyFileReflink(goldenRootfs, rootfsPath); err != nil {
+ m.cleanupVM(netCfg, "")
+ return nil, fmt.Errorf("copy golden rootfs for wake: %w", err)
}
- // Cold boot fallback: boot fresh VM with restored drives
- guestCID = m.allocateCID()
- guestMAC = generateMAC(sandboxID)
- bootArgs = fmt.Sprintf(
+ 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 "+
@@ -462,8 +358,18 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, c
return 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, guestCID, qmpSockPath, bootArgs)
+ goldenMemZst := filepath.Join(m.goldenDir, "mem.zst")
+ goldenMemRaw := filepath.Join(m.goldenDir, "mem")
+ var incomingURI string
+ if fileExists(goldenMemZst) {
+ incomingURI = fmt.Sprintf("exec:zstdcat %s", goldenMemZst)
+ } else {
+ incomingURI = fmt.Sprintf("exec:cat %s", goldenMemRaw)
+ }
+ args = append(args, "-incoming", incomingURI)
cmd := exec.Command(m.cfg.QEMUBin, args...)
cmd.Stdout = logFile
@@ -471,20 +377,68 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, c
if err := cmd.Start(); err != nil {
logFile.Close()
m.cleanupVM(netCfg, "")
- return nil, fmt.Errorf("start qemu cold boot: %w", err)
+ return nil, fmt.Errorf("start qemu for wake: %w", err)
}
logFile.Close()
+ // Connect QMP, wait for migration load, resume
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)
+ return nil, fmt.Errorf("QMP connect for wake: %w", err)
+ }
+ if err := m.waitForMigrationReady(qmpClient, 30*time.Second); err != nil {
+ qmpClient.Close()
+ cmd.Process.Kill()
+ cmd.Wait()
+ m.cleanupVM(netCfg, "")
+ return nil, fmt.Errorf("migration load for wake: %w", err)
+ }
+ if err := qmpClient.Cont(); err != nil {
+ qmpClient.Close()
+ cmd.Process.Kill()
+ cmd.Wait()
+ m.cleanupVM(netCfg, "")
+ 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
+ }
+ }
+ if err != nil {
+ cmd.Process.Kill()
+ cmd.Wait()
+ m.cleanupVM(netCfg, "")
+ return nil, fmt.Errorf("agent not ready after wake: %w", err)
}
- log.Printf("qemu: wake %s: cold boot complete (cross-worker migration, tap=%s)",
- sandboxID, netCfg.TAPName)
+ // Mount user's workspace (golden snapshot had /workspace unmounted)
+ mountCtx, mountCancel := context.WithTimeout(context.Background(), 10*time.Second)
+ _, _ = agentClient.Exec(mountCtx, &pb.ExecRequest{
+ Command: "/bin/sh",
+ Args: []string{"-c", "mount /dev/vdb /workspace 2>/dev/null || true"},
+ })
+ mountCancel()
+
+ // Patch network (golden had different IP)
+ if err := patchGuestNetwork(context.Background(), agentClient, netCfg); err != nil {
+ log.Printf("qemu: wake %s: network patch failed: %v", sandboxID, err)
+ }
+
+ if err := syncGuestClock(context.Background(), agentClient); err != nil {
+ log.Printf("qemu: wake %s: clock sync failed: %v", sandboxID, err)
+ }
+
+ log.Printf("qemu: wake %s: golden restore complete (port=%d, tap=%s)",
+ sandboxID, hostPort, netCfg.TAPName)
now := time.Now()
ttl := time.Duration(timeout) * time.Second
@@ -512,20 +466,8 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, c
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()
@@ -538,8 +480,8 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, c
// 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")
+ workspacePath := detectDrivePath(sandboxDir, "workspace")
+ rootfsPath := detectDrivePath(sandboxDir, "rootfs")
if !fileExists(workspacePath) {
return nil, fmt.Errorf("workspace not found at %s", workspacePath)
diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.go
index 9b2d1fd3..12f9da3c 100644
--- a/internal/worker/grpc_server.go
+++ b/internal/worker/grpc_server.go
@@ -505,10 +505,6 @@ func (s *GRPCServer) SaveAsTemplate(ctx context.Context, req *pb.SaveAsTemplateR
}
func (s *GRPCServer) CreateCheckpoint(ctx context.Context, req *pb.CreateCheckpointRequest) (*pb.CreateCheckpointResponse, error) {
- if s.checkpointStore == nil {
- return nil, fmt.Errorf("checkpoint store not configured on this worker")
- }
-
checkpointID := req.CheckpointId
if _, err := uuid.Parse(checkpointID); err != nil {
return nil, fmt.Errorf("invalid checkpoint ID: %w", err)
@@ -544,38 +540,8 @@ func (s *GRPCServer) RestoreCheckpoint(ctx context.Context, req *pb.RestoreCheck
return nil, fmt.Errorf("invalid checkpoint ID: %w", err)
}
- // Check local cache first; if not available, download from S3
- cachedRootfs := s.manager.CheckpointCachePath(checkpointID, "rootfs.ext4")
- cachedWorkspace := s.manager.CheckpointCachePath(checkpointID, "workspace.ext4")
- if cachedRootfs == "" || cachedWorkspace == "" {
- // Need to download from S3
- if s.checkpointStore == nil {
- return nil, fmt.Errorf("checkpoint not cached locally and no S3 store configured")
- }
- log.Printf("grpc: RestoreCheckpoint %s: not cached locally, downloading from S3", checkpointID)
- rootfsKey := fmt.Sprintf("checkpoints/%s/%s/rootfs.tar.zst", req.SandboxId, checkpointID)
- workspaceKey := fmt.Sprintf("checkpoints/%s/%s/workspace.sparse.zst", req.SandboxId, checkpointID)
-
- cacheDir := filepath.Join(s.manager.DataDir(), "checkpoints", checkpointID)
- if err := os.MkdirAll(cacheDir, 0755); err != nil {
- return nil, fmt.Errorf("create checkpoint cache dir: %w", err)
- }
-
- cachedRootfsPath := filepath.Join(cacheDir, "rootfs.ext4")
- cachedWorkspacePath := filepath.Join(cacheDir, "workspace.ext4")
-
- if err := downloadAndExtract(ctx, s.checkpointStore, rootfsKey, cacheDir, extractArchiveCmd); err != nil {
- os.RemoveAll(cacheDir)
- return nil, fmt.Errorf("download checkpoint rootfs: %w", err)
- }
- if err := downloadAndExtract(ctx, s.checkpointStore, workspaceKey, cachedWorkspacePath, extractSparseCmd); err != nil {
- os.RemoveAll(cacheDir)
- return nil, fmt.Errorf("download checkpoint workspace: %w", err)
- }
- log.Printf("grpc: RestoreCheckpoint %s: cached locally at %s", checkpointID, cacheDir)
- _ = cachedRootfsPath // used implicitly by manager.CheckpointCachePath after download
- }
-
+ // Try direct restore first (QEMU loadvm works on the running VM's qcow2 drives).
+ // Only fall back to file-based restore with S3 download if the direct approach fails.
if err := s.manager.RestoreFromCheckpoint(ctx, req.SandboxId, checkpointID); err != nil {
return nil, fmt.Errorf("restore from checkpoint failed: %w", err)
}