Skip to content

An open-source, faster Devin alternative

TypeScript

migratin to firecrackervm

Brian Reardon4bc9d20d9748
diff --git a/Makefile b/Makefile
index d410a1f2..29011c6e 100644
--- a/Makefile
+++ b/Makefile
@@ -3,14 +3,15 @@
# Build variables
BINARY_SERVER = opensandbox-server
BINARY_WORKER = opensandbox-worker
+BINARY_AGENT = osb-agent
BUILD_DIR = bin
## help: Show this help message
help:
@grep -E '^##' $(MAKEFILE_LIST) | sed 's/## //' | column -t -s ':'
-## build: Build server and worker binaries
-build: build-server build-worker
+## build: Build server, worker, and agent binaries
+build: build-server build-worker build-agent
## build-server: Build the control plane server
build-server:
@@ -24,6 +25,10 @@ build-worker:
build-worker-arm64:
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -o $(BUILD_DIR)/$(BINARY_WORKER)-arm64 ./cmd/worker
+## build-agent: Build the in-VM agent (static binary for Linux ARM64)
+build-agent:
+ CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -o $(BUILD_DIR)/$(BINARY_AGENT) ./cmd/agent
+
## build-server-arm64: Cross-compile server for Linux ARM64
build-server-arm64:
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -o $(BUILD_DIR)/$(BINARY_SERVER)-arm64 ./cmd/server
@@ -187,6 +192,25 @@ proto:
protoc --go_out=. --go_opt=paths=source_relative \
--go-grpc_out=. --go-grpc_opt=paths=source_relative \
proto/worker/worker.proto
+ protoc --go_out=. --go_opt=paths=source_relative \
+ --go-grpc_out=. --go-grpc_opt=paths=source_relative \
+ proto/agent/agent.proto
+
+## --- Firecracker ---
+
+## build-rootfs: Build base ext4 rootfs images for Firecracker VMs (requires root)
+build-rootfs:
+ sudo AGENT_BIN=$(BUILD_DIR)/$(BINARY_AGENT) IMAGES_DIR=$(BUILD_DIR)/images ./scripts/build-rootfs.sh all
+
+## download-kernel: Download the Firecracker-compatible ARM64 kernel
+download-kernel:
+ ./scripts/download-kernel.sh $(BUILD_DIR)/vmlinux-arm64
+
+## deploy-worker: Deploy worker + agent to EC2 instance (set WORKER_IP=<ip>)
+deploy-worker:
+ ./deploy/ec2/deploy-worker.sh
+
+## --- Docker ---
## docker-server: Build server Docker image
docker-server:
diff --git a/cmd/agent/listen_linux.go b/cmd/agent/listen_linux.go
new file mode 100644
index 00000000..fd75daa3
--- /dev/null
+++ b/cmd/agent/listen_linux.go
@@ -0,0 +1,144 @@
+package main
+
+import (
+ "fmt"
+ "log"
+ "net"
+ "os"
+ "sync"
+ "time"
+
+ "github.com/opensandbox/opensandbox/internal/agent"
+ "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.
+type vsockListener struct {
+ fd int
+ port uint32
+ once sync.Once
+ closed chan struct{}
+}
+
+type vsockAddr struct {
+ cid uint32
+ port uint32
+}
+
+func (a vsockAddr) Network() string { return "vsock" }
+func (a vsockAddr) String() string { return fmt.Sprintf("vsock(%d:%d)", a.cid, a.port) }
+
+func (l *vsockListener) Accept() (net.Conn, error) {
+ for {
+ nfd, _, err := unix.Accept(l.fd)
+ if err != nil {
+ select {
+ case <-l.closed:
+ return nil, net.ErrClosed
+ default:
+ }
+ 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
+ }
+}
+
+func (l *vsockListener) Close() error {
+ var err error
+ l.once.Do(func() {
+ close(l.closed)
+ err = unix.Close(l.fd)
+ })
+ return err
+}
+
+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 {
+ return nil, fmt.Errorf("vsock socket: %w", err)
+ }
+ sa := &unix.SockaddrVM{
+ CID: unix.VMADDR_CID_ANY,
+ Port: port,
+ }
+ if err := unix.Bind(fd, sa); err != nil {
+ unix.Close(fd)
+ return nil, fmt.Errorf("vsock bind port %d: %w", port, err)
+ }
+ if err := unix.Listen(fd, 128); err != nil {
+ unix.Close(fd)
+ return nil, fmt.Errorf("vsock listen port %d: %w", port, err)
+ }
+ log.Printf("agent: listening on vsock port %d", port)
+ return &vsockListener{fd: fd, closed: make(chan struct{}), port: port}, nil
+}
+
+func listenUnix(vsockErr error) (net.Listener, error) {
+ sockPath := "/tmp/osb-agent.sock"
+ os.Remove(sockPath)
+ lis, err := net.Listen("unix", sockPath)
+ if err != nil {
+ return nil, fmt.Errorf("unix listen: %w (vsock: %v)", err, vsockErr)
+ }
+ log.Printf("agent: listening on %s (vsock not available: %v)", sockPath, vsockErr)
+ return lis, nil
+}
+
+// rawVsockConn wraps a raw vsock fd as a net.Conn when net.FileConn fails.
+type rawVsockConn struct {
+ file *os.File
+}
+
+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 }
diff --git a/cmd/agent/listen_other.go b/cmd/agent/listen_other.go
new file mode 100644
index 00000000..813fac33
--- /dev/null
+++ b/cmd/agent/listen_other.go
@@ -0,0 +1,22 @@
+//go:build !linux
+
+package main
+
+import (
+ "log"
+ "net"
+ "os"
+)
+
+// listenVsock on non-Linux falls back to a Unix domain socket.
+// vsock is Linux-only, but we want the agent to build on macOS for testing.
+func listenVsock() (net.Listener, error) {
+ sockPath := "/tmp/osb-agent.sock"
+ os.Remove(sockPath)
+ lis, err := net.Listen("unix", sockPath)
+ if err != nil {
+ return nil, err
+ }
+ log.Printf("agent: listening on %s (non-Linux, vsock not available)", sockPath)
+ return lis, nil
+}
diff --git a/cmd/agent/main.go b/cmd/agent/main.go
new file mode 100644
index 00000000..9e26582f
--- /dev/null
+++ b/cmd/agent/main.go
@@ -0,0 +1,45 @@
+// osb-agent is the sandbox agent that runs inside each Firecracker microVM.
+// It listens for gRPC connections over vsock and handles exec, file ops,
+// PTY sessions, and stats collection.
+//
+// Build: CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -o osb-agent ./cmd/agent
+package main
+
+import (
+ "log"
+ "os"
+ "os/signal"
+ "syscall"
+
+ "github.com/opensandbox/opensandbox/internal/agent"
+)
+
+const version = "0.1.0"
+
+func main() {
+ log.SetFlags(log.Ltime | log.Lmicroseconds)
+ log.Printf("osb-agent %s starting", version)
+
+ // Listen on vsock port 1024 (inside Firecracker) or Unix socket (testing).
+ lis, err := listenVsock()
+ if err != nil {
+ log.Fatalf("agent: failed to listen: %v", err)
+ }
+
+ srv := agent.NewServer(version)
+ srv.ListenPort = listenPortForPTY
+
+ // Graceful shutdown
+ sigCh := make(chan os.Signal, 1)
+ signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGINT)
+ go func() {
+ sig := <-sigCh
+ log.Printf("agent: received %v, shutting down", sig)
+ lis.Close()
+ os.Exit(0)
+ }()
+
+ if err := srv.Serve(lis); err != nil {
+ log.Fatalf("agent: serve failed: %v", err)
+ }
+}
diff --git a/cmd/server/main.go b/cmd/server/main.go
index 26d08f43..a1e46ef0 100644
--- a/cmd/server/main.go
+++ b/cmd/server/main.go
@@ -33,7 +33,7 @@ func main() {
ctx := context.Background()
// Initialize Podman (optional in server mode — no container runtime needed)
- var mgr *sandbox.Manager
+ var mgr sandbox.Manager
var ptyMgr *sandbox.PTYManager
podmanClient, err := podman.NewClient()
if err != nil {
@@ -236,6 +236,15 @@ func main() {
log.Printf("opensandbox: EC2 autoscaler started (ami=%s, type=%s)", cfg.EC2AMI, cfg.EC2InstanceType)
}
+ // Initialize control plane subdomain proxy (server mode only).
+ // Routes *.workers.opensandbox.ai requests to the correct worker
+ // by looking up sandbox → worker mapping in PG + Redis registry.
+ if cfg.Mode == "server" && cfg.SandboxDomain != "" && opts.Store != nil && redisRegistry != nil {
+ cpProxy := proxy.NewControlPlaneProxy(cfg.SandboxDomain, opts.Store, redisRegistry)
+ opts.ControlPlaneProxy = cpProxy
+ log.Printf("opensandbox: control plane subdomain proxy configured (*.%s)", cfg.SandboxDomain)
+ }
+
// Create API server
server := api.NewServer(mgr, ptyMgr, cfg.APIKey, opts)
diff --git a/cmd/worker/main.go b/cmd/worker/main.go
index 034a611c..675ac34b 100644
--- a/cmd/worker/main.go
+++ b/cmd/worker/main.go
@@ -5,7 +5,6 @@ import (
"fmt"
"log"
"os"
- "os/exec"
"os/signal"
"path/filepath"
"syscall"
@@ -13,7 +12,7 @@ import (
"github.com/opensandbox/opensandbox/internal/auth"
"github.com/opensandbox/opensandbox/internal/config"
"github.com/opensandbox/opensandbox/internal/db"
- "github.com/opensandbox/opensandbox/internal/ecr"
+ fc "github.com/opensandbox/opensandbox/internal/firecracker"
"github.com/opensandbox/opensandbox/internal/metrics"
"github.com/opensandbox/opensandbox/internal/podman"
"github.com/opensandbox/opensandbox/internal/proxy"
@@ -21,6 +20,7 @@ import (
"github.com/opensandbox/opensandbox/internal/storage"
"github.com/opensandbox/opensandbox/internal/template"
"github.com/opensandbox/opensandbox/internal/worker"
+ "github.com/opensandbox/opensandbox/pkg/types"
)
func main() {
@@ -31,30 +31,70 @@ func main() {
log.Printf("opensandbox-worker: starting (id=%s, region=%s)...", cfg.WorkerID, cfg.Region)
- client, err := podman.NewClient()
- if err != nil {
- log.Fatalf("failed to initialize podman: %v", err)
+ ctx := context.Background()
+
+ // Initialize Firecracker-based sandbox manager
+ fcCfg := fc.Config{
+ DataDir: cfg.DataDir,
+ KernelPath: cfg.KernelPath,
+ ImagesDir: cfg.ImagesDir,
+ FirecrackerBin: cfg.FirecrackerBin,
+ DefaultMemoryMB: cfg.DefaultSandboxMemoryMB,
+ DefaultCPUs: cfg.DefaultSandboxCPUs,
+ DefaultDiskMB: cfg.DefaultSandboxDiskMB,
}
- ctx := context.Background()
- version, err := client.Version(ctx)
+ fcMgr, err := fc.NewManager(fcCfg)
if err != nil {
- log.Fatalf("failed to get podman version: %v", err)
+ log.Fatalf("failed to initialize Firecracker manager: %v", err)
}
- log.Printf("opensandbox-worker: using podman %s", version)
-
- // Initialize sandbox manager
- mgr := sandbox.NewManager(client,
- sandbox.WithDataDir(cfg.DataDir),
- sandbox.WithDefaultMemoryMB(cfg.DefaultSandboxMemoryMB),
- sandbox.WithDefaultCPUs(cfg.DefaultSandboxCPUs),
- sandbox.WithDefaultDiskMB(cfg.DefaultSandboxDiskMB),
- )
- defer mgr.Close()
-
- // Initialize PTY manager
- podmanPath, _ := exec.LookPath("podman")
- ptyMgr := sandbox.NewPTYManager(podmanPath, client.AuthFile())
+ defer fcMgr.Close()
+ log.Println("opensandbox-worker: Firecracker VM manager initialized")
+
+ // The Firecracker manager implements sandbox.Manager
+ var mgr sandbox.Manager = fcMgr
+
+ // Initialize PTY manager using Firecracker agent gRPC
+ ptyMgr := sandbox.NewAgentPTYManager(func(sandboxID string, req types.PTYCreateRequest) (*sandbox.PTYSessionHandle, error) {
+ agent, err := fcMgr.GetAgent(sandboxID)
+ if err != nil {
+ return nil, fmt.Errorf("get agent for %s: %w", sandboxID, err)
+ }
+ vsockPath, err := fcMgr.GetVsockPath(sandboxID)
+ if err != nil {
+ return nil, fmt.Errorf("get vsock path for %s: %w", sandboxID, err)
+ }
+
+ cols := int32(req.Cols)
+ if cols <= 0 {
+ cols = 80
+ }
+ rows := int32(req.Rows)
+ if rows <= 0 {
+ rows = 24
+ }
+
+ sessionID, dataPort, err := agent.PTYCreate(context.Background(), cols, rows, req.Shell)
+ if err != nil {
+ return nil, fmt.Errorf("create PTY in VM: %w", err)
+ }
+
+ // Connect to the PTY data stream via vsock
+ conn, err := agent.ConnectPTYData(vsockPath, dataPort)
+ if err != nil {
+ _ = agent.PTYKill(context.Background(), sessionID)
+ return nil, fmt.Errorf("connect PTY data: %w", err)
+ }
+
+ done := make(chan struct{})
+
+ return &sandbox.PTYSessionHandle{
+ ID: sessionID,
+ SandboxID: sandboxID,
+ PTY: conn,
+ Done: done,
+ }, nil
+ })
defer ptyMgr.CloseAll()
// Initialize per-sandbox SQLite manager
@@ -138,19 +178,20 @@ func main() {
defer metricsSrv.Close()
log.Println("opensandbox-worker: metrics server started on :9091")
- // Initialize ECR config + template builder for building custom templates
- var ecrCfg *ecr.Config
- if cfg.ECRRegistry != "" {
- ecrCfg = &ecr.Config{
- Registry: cfg.ECRRegistry,
- Repository: cfg.ECRRepository,
- Region: cfg.S3Region,
- AccessKey: cfg.S3AccessKeyID,
- SecretKey: cfg.S3SecretAccessKey,
+ // Initialize template builder (Podman as build tool → ext4 images)
+ var builder *template.Builder
+ podmanClient, podmanErr := podman.NewClient()
+ if podmanErr != nil {
+ log.Printf("opensandbox-worker: podman not available: %v (template building disabled)", podmanErr)
+ } else {
+ imagesDir := fcCfg.ImagesDir
+ agentPath := filepath.Join(filepath.Dir(os.Args[0]), "osb-agent")
+ if _, err := os.Stat(agentPath); err != nil {
+ agentPath = "/usr/local/bin/osb-agent"
}
- log.Printf("opensandbox-worker: ECR configured (registry=%s, repo=%s)", cfg.ECRRegistry, cfg.ECRRepository)
+ builder = template.NewBuilder(podmanClient, imagesDir, agentPath)
+ log.Printf("opensandbox-worker: template builder configured (images=%s, agent=%s)", imagesDir, agentPath)
}
- builder := template.NewBuilder(client, ecrCfg)
// Start gRPC server for control plane communication
grpcServer := worker.NewGRPCServer(mgr, ptyMgr, sandboxDBMgr, checkpointStore, sbRouter, builder)
@@ -179,28 +220,8 @@ func main() {
}
}()
- // Pre-pull common template images in background (non-blocking)
- go func() {
- images := []string{
- "docker.io/library/ubuntu:22.04",
- "docker.io/library/python:3.12-slim",
- "docker.io/library/node:20-slim",
- }
- for _, img := range images {
- exists, _ := client.ImageExists(ctx, img)
- if !exists {
- log.Printf("opensandbox-worker: pulling %s...", img)
- if err := client.PullImage(ctx, img); err != nil {
- log.Printf("opensandbox-worker: warning: failed to pull %s: %v", img, err)
- }
- }
- }
- log.Println("opensandbox-worker: template images ready")
- }()
-
// Start Redis heartbeat for control plane discovery
if cfg.RedisURL != "" {
- // Determine the gRPC address to advertise to the control plane.
grpcAdvertise := grpcAddr
if addr := os.Getenv("OPENSANDBOX_GRPC_ADVERTISE"); addr != "" {
grpcAdvertise = addr
@@ -210,7 +231,6 @@ func main() {
if err != nil {
log.Printf("opensandbox-worker: Redis heartbeat not available: %v", err)
} else {
- // Try to get EC2 instance ID from IMDS for scaler drain/terminate
if machineID := worker.GetEC2InstanceID(); machineID != "" {
hb.SetMachineID(machineID)
log.Printf("opensandbox-worker: EC2 instance ID: %s", machineID)
diff --git a/deploy/ec2/deploy-worker.sh b/deploy/ec2/deploy-worker.sh
index 82a90073..d67802b3 100755
--- a/deploy/ec2/deploy-worker.sh
+++ b/deploy/ec2/deploy-worker.sh
@@ -1,8 +1,15 @@
#!/usr/bin/env bash
set -euo pipefail
-# Deploy the opensandbox-worker binary to the EC2 instance.
+# Deploy the opensandbox-worker + osb-agent binaries to the EC2 instance.
# Run from the repo root: ./deploy/ec2/deploy-worker.sh
+#
+# This script:
+# 1. Cross-compiles worker and agent binaries for Linux ARM64
+# 2. Uploads them to the EC2 instance
+# 3. Installs and restarts the worker service
+#
+# Optional: Set DEPLOY_KERNEL=1 to also download and deploy the Firecracker kernel.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
@@ -14,22 +21,50 @@ SSH="ssh -i $SSH_KEY $SSH_USER@$WORKER_IP"
SCP="scp -i $SSH_KEY"
GOARCH="${GOARCH:-arm64}"
-echo "==> Building opensandbox-worker (linux/${GOARCH})..."
+DEPLOY_KERNEL="${DEPLOY_KERNEL:-0}"
+
cd "$REPO_ROOT"
-CGO_ENABLED=0 GOOS=linux GOARCH="$GOARCH" go build -o opensandbox-worker ./cmd/worker/
-echo " Built: opensandbox-worker ($(du -h opensandbox-worker | cut -f1), ${GOARCH})"
-echo "==> Uploading to $WORKER_IP..."
-$SCP opensandbox-worker "$SSH_USER@$WORKER_IP:/tmp/opensandbox-worker"
+echo "==> Building opensandbox-worker (linux/${GOARCH})..."
+CGO_ENABLED=0 GOOS=linux GOARCH="$GOARCH" go build -o bin/opensandbox-worker-deploy ./cmd/worker/
+echo " Built: opensandbox-worker ($(du -h bin/opensandbox-worker-deploy | cut -f1), ${GOARCH})"
+
+echo "==> Building osb-agent (linux/${GOARCH})..."
+CGO_ENABLED=0 GOOS=linux GOARCH="$GOARCH" go build -o bin/osb-agent-deploy ./cmd/agent/
+echo " Built: osb-agent ($(du -h bin/osb-agent-deploy | cut -f1), ${GOARCH})"
+
+echo "==> Uploading binaries to $WORKER_IP..."
+$SCP bin/opensandbox-worker-deploy "$SSH_USER@$WORKER_IP:/tmp/opensandbox-worker"
+$SCP bin/osb-agent-deploy "$SSH_USER@$WORKER_IP:/tmp/osb-agent"
-echo "==> Installing and restarting service..."
+echo "==> Installing binaries..."
$SSH "sudo mv /tmp/opensandbox-worker /usr/local/bin/opensandbox-worker && \
sudo chmod +x /usr/local/bin/opensandbox-worker && \
- sudo systemctl restart opensandbox-worker"
+ sudo mv /tmp/osb-agent /usr/local/bin/osb-agent && \
+ sudo chmod +x /usr/local/bin/osb-agent"
+
+# Optionally deploy kernel
+if [ "$DEPLOY_KERNEL" = "1" ]; then
+ echo "==> Downloading Firecracker kernel..."
+ FC_VERSION="${FC_VERSION:-v1.9.1}"
+ KERNEL_URL="https://github.com/firecracker-microvm/firecracker/releases/download/${FC_VERSION}/vmlinux-5.10.225.bin"
+
+ $SSH "sudo mkdir -p /data/firecracker && \
+ curl -fSL -o /tmp/vmlinux '$KERNEL_URL' && \
+ sudo mv /tmp/vmlinux /data/firecracker/vmlinux-arm64 && \
+ echo 'Kernel installed: \$(file /data/firecracker/vmlinux-arm64)'"
+fi
+
+echo "==> Restarting worker service..."
+$SSH "sudo systemctl restart opensandbox-worker"
echo "==> Waiting for worker to start..."
sleep 2
$SSH "sudo systemctl is-active opensandbox-worker"
echo "==> Deployed successfully!"
-rm -f "$REPO_ROOT/opensandbox-worker"
+echo " Worker: /usr/local/bin/opensandbox-worker"
+echo " Agent: /usr/local/bin/osb-agent"
+
+# Cleanup
+rm -f bin/opensandbox-worker-deploy bin/osb-agent-deploy
diff --git a/deploy/ec2/setup-instance.sh b/deploy/ec2/setup-instance.sh
index 8b1e637e..067f59fc 100755
--- a/deploy/ec2/setup-instance.sh
+++ b/deploy/ec2/setup-instance.sh
@@ -6,18 +6,19 @@ set -euo pipefail
# ssh -i key.pem ubuntu@<IP> 'bash -s' < deploy/ec2/setup-instance.sh
#
# Supports both x86_64 (amd64) and aarch64 (arm64/Graviton) instances.
+# Optimized for Firecracker microVMs on bare-metal Graviton (r7gd.metal).
#
# Prerequisites:
# - Ubuntu 24.04 LTS AMI
-# - t3.medium or larger (x86) / r7gd.medium or larger (arm64)
-# - Security group: 443 (HTTPS), 9090 (gRPC) open inbound
+# - r7gd.metal (ARM64) or c7i.metal (x86_64) for production
+# - Security group: 443 (HTTPS), 8080 (HTTP), 9090 (gRPC), 9091 (metrics) open inbound
# - SSH access
# Detect architecture
ARCH=$(uname -m)
case "$ARCH" in
- x86_64) GOARCH="amd64" ;;
- aarch64) GOARCH="arm64" ;;
+ x86_64) GOARCH="amd64"; FC_ARCH="x86_64" ;;
+ aarch64) GOARCH="arm64"; FC_ARCH="aarch64" ;;
*) echo "ERROR: Unsupported architecture: $ARCH"; exit 1 ;;
esac
echo "==> Detected architecture: $ARCH ($GOARCH)"
@@ -26,66 +27,45 @@ echo "==> Updating packages..."
sudo apt-get update && sudo apt-get upgrade -y
# -------------------------------------------------------------------
-# Podman (runtime will be configured after crun is built)
+# Firecracker microVM runtime
# -------------------------------------------------------------------
-echo "==> Installing Podman..."
-sudo apt-get install -y podman uidmap slirp4netns
-
-# -------------------------------------------------------------------
-# CRIU 4.2 (must be installed BEFORE crun so headers are available)
-# -------------------------------------------------------------------
-echo "==> Installing CRIU 4.2 from source..."
-sudo apt-get install -y \
- make gcc pkg-config git \
- libprotobuf-dev libprotobuf-c-dev protobuf-c-compiler protobuf-compiler \
- libcap-dev libnl-3-dev libnet1-dev libbsd-dev \
- python3-protobuf python3-yaml iproute2 \
- libdrm-dev libnftables-dev uuid-dev libaio-dev
+echo "==> Installing Firecracker..."
+FC_VERSION="v1.9.1"
+FC_RELEASE="firecracker-${FC_VERSION}-${FC_ARCH}"
+FC_URL="https://github.com/firecracker-microvm/firecracker/releases/download/${FC_VERSION}/${FC_RELEASE}.tgz"
cd /tmp
-rm -rf /tmp/criu
-git clone --branch v4.2 --depth 1 https://github.com/checkpoint-restore/criu.git
-cd criu
-make -j"$(nproc)"
-sudo make install-criu PREFIX=/usr/local
-sudo make install-lib PREFIX=/usr/local
-sudo ldconfig
-cd / && rm -rf /tmp/criu
-
-echo "==> Verifying CRIU..."
-criu --version
+curl -fSL -o firecracker.tgz "$FC_URL"
+tar xzf firecracker.tgz
+sudo cp "release-${FC_VERSION}-${FC_ARCH}/firecracker-${FC_VERSION}-${FC_ARCH}" /usr/local/bin/firecracker
+sudo chmod +x /usr/local/bin/firecracker
+rm -rf firecracker.tgz "release-${FC_VERSION}-${FC_ARCH}"
+cd /
+
+echo "==> Verifying Firecracker..."
+firecracker --version
+
+# Verify KVM access (required for Firecracker)
+if [ ! -e /dev/kvm ]; then
+ echo "WARNING: /dev/kvm not found. Firecracker requires bare-metal or nested virt."
+ echo " For bare-metal instances (r7gd.metal), /dev/kvm should exist."
+ echo " For regular instances, enable nested virtualization in the AMI."
+fi
+
+# Ensure KVM permissions
+sudo chmod 666 /dev/kvm 2>/dev/null || true
# -------------------------------------------------------------------
-# crun 1.26 (with CRIU support — requires CRIU headers from above)
+# Podman (kept as build tool for Dockerfile → ext4 conversion)
# -------------------------------------------------------------------
-echo "==> Installing crun from source (with CRIU support)..."
-sudo apt-get install -y \
- libsystemd-dev libseccomp-dev \
- libyajl-dev go-md2man autoconf automake libtool
-
-cd /tmp
-rm -rf /tmp/crun
-git clone --branch "1.26" --depth 1 https://github.com/containers/crun.git
-cd crun
-export PKG_CONFIG_PATH="/usr/local/lib/pkgconfig:${PKG_CONFIG_PATH:-}"
-./autogen.sh
-./configure --with-criu
-make -j"$(nproc)"
-sudo make install
-cd / && rm -rf /tmp/crun
-
-echo "==> Verifying crun has CRIU support..."
-crun --version | grep "+CRIU" || { echo "ERROR: crun built without CRIU"; exit 1; }
+echo "==> Installing Podman (for template building)..."
+sudo apt-get install -y podman uidmap slirp4netns
# -------------------------------------------------------------------
-# Configure Podman to use crun
+# System tools for ext4 image creation
# -------------------------------------------------------------------
-echo "==> Configuring Podman to use crun..."
-sudo mkdir -p /etc/containers
-sudo tee /etc/containers/containers.conf > /dev/null <<'EOF'
-[engine]
-runtime = "crun"
-EOF
+echo "==> Installing ext4 and rootfs tools..."
+sudo apt-get install -y e2fsprogs
# -------------------------------------------------------------------
# Redis
@@ -120,7 +100,7 @@ sudo cp /tmp/deploy-ec2/caddy.service /etc/systemd/system/caddy.service 2>/dev/n
echo " NOTE: Copy deploy/ec2/caddy.service to /etc/systemd/system/ manually"
# -------------------------------------------------------------------
-# NVMe instance storage (handled at boot by opensandbox-nvme.service)
+# NVMe instance storage (XFS with reflink for instant rootfs copies)
# -------------------------------------------------------------------
echo "==> Installing NVMe boot service..."
sudo apt-get install -y xfsprogs nvme-cli
@@ -128,7 +108,7 @@ sudo apt-get install -y xfsprogs nvme-cli
sudo tee /usr/local/bin/opensandbox-nvme-setup.sh > /dev/null << 'NVME'
#!/usr/bin/env bash
set -euo pipefail
-MOUNT_POINT="/data/sandboxes"
+MOUNT_POINT="/data"
mkdir -p "$MOUNT_POINT"
if mountpoint -q "$MOUNT_POINT"; then
echo "opensandbox-nvme: $MOUNT_POINT already mounted"
@@ -143,11 +123,16 @@ for dev in /dev/nvme1n1 /dev/nvme2n1 /dev/nvme3n1 /dev/nvme4n1; do
done
if [ -z "$NVME_DEV" ]; then
echo "opensandbox-nvme: no NVMe instance storage found, using root disk"
+ mkdir -p "$MOUNT_POINT/sandboxes" "$MOUNT_POINT/firecracker/images" "$MOUNT_POINT/checkpoints"
exit 0
fi
-echo "opensandbox-nvme: formatting $NVME_DEV as XFS with project quotas"
-mkfs.xfs -f "$NVME_DEV"
+echo "opensandbox-nvme: formatting $NVME_DEV as XFS with reflink + project quotas"
+mkfs.xfs -f -m reflink=1 "$NVME_DEV"
mount -o prjquota "$NVME_DEV" "$MOUNT_POINT"
+# Create directory structure
+mkdir -p "$MOUNT_POINT/sandboxes"
+mkdir -p "$MOUNT_POINT/firecracker/images"
+mkdir -p "$MOUNT_POINT/checkpoints"
echo "opensandbox-nvme: mounted $NVME_DEV at $MOUNT_POINT"
NVME
sudo chmod +x /usr/local/bin/opensandbox-nvme-setup.sh
@@ -168,6 +153,35 @@ ExecStart=/usr/local/bin/opensandbox-nvme-setup.sh
WantedBy=multi-user.target
SVC
+# -------------------------------------------------------------------
+# Firecracker kernel + base rootfs images
+# -------------------------------------------------------------------
+echo "==> Setting up Firecracker kernel and base images directory..."
+sudo mkdir -p /data/firecracker/images
+
+# Download kernel (will be populated by deploy script)
+echo " Kernel will be installed by deploy-worker.sh at /data/firecracker/vmlinux-arm64"
+echo " Base rootfs images will be installed at /data/firecracker/images/"
+
+# -------------------------------------------------------------------
+# IP forwarding + iptables for VM networking
+# -------------------------------------------------------------------
+echo "==> Configuring IP forwarding for Firecracker VMs..."
+sudo tee /etc/sysctl.d/99-opensandbox.conf > /dev/null << 'SYSCTL'
+# Enable IP forwarding for Firecracker VM networking
+net.ipv4.ip_forward = 1
+# Increase ARP cache for many TAP interfaces
+net.ipv4.neigh.default.gc_thresh1 = 1024
+net.ipv4.neigh.default.gc_thresh2 = 4096
+net.ipv4.neigh.default.gc_thresh3 = 8192
+# Increase max open files for many VMs
+fs.file-max = 1000000
+# Increase inotify limits
+fs.inotify.max_user_instances = 8192
+fs.inotify.max_user_watches = 524288
+SYSCTL
+sudo sysctl --system
+
# -------------------------------------------------------------------
# Dynamic worker identity (from EC2 IMDS at boot)
# -------------------------------------------------------------------
@@ -212,23 +226,18 @@ WantedBy=multi-user.target
SVC
# -------------------------------------------------------------------
-# Worker systemd unit
+# Worker systemd unit (Firecracker)
# -------------------------------------------------------------------
echo "==> Installing worker systemd unit..."
sudo tee /etc/systemd/system/opensandbox-worker.service > /dev/null << 'SVC'
[Unit]
-Description=OpenSandbox Worker
+Description=OpenSandbox Worker (Firecracker)
After=network-online.target opensandbox-nvme.service opensandbox-identity.service
Wants=network-online.target
Requires=opensandbox-nvme.service opensandbox-identity.service
[Service]
Type=simple
-ExecStartPre=/sbin/modprobe inet_diag
-ExecStartPre=/sbin/modprobe tcp_diag
-ExecStartPre=/sbin/modprobe udp_diag
-ExecStartPre=/sbin/modprobe unix_diag
-ExecStartPre=/sbin/modprobe netlink_diag
ExecStart=/usr/local/bin/opensandbox-worker
Restart=always
RestartSec=5
@@ -236,28 +245,22 @@ Environment=HOME=/root
Environment=OPENSANDBOX_MODE=worker
Environment=OPENSANDBOX_PORT=8080
Environment=OPENSANDBOX_REGION=use2
-Environment=OPENSANDBOX_DATA_DIR=/data/sandboxes
+Environment=OPENSANDBOX_DATA_DIR=/data
Environment=OPENSANDBOX_SANDBOX_DOMAIN=workers.opensandbox.ai
+Environment=OPENSANDBOX_FIRECRACKER_BIN=/usr/local/bin/firecracker
+Environment=OPENSANDBOX_KERNEL_PATH=/data/firecracker/vmlinux-arm64
+Environment=OPENSANDBOX_IMAGES_DIR=/data/firecracker/images
Environment=OPENSANDBOX_SECRETS_ARN=arn:aws:secretsmanager:us-east-2:739940681129:secret:opensandbox/worker-vtN2Ez
EnvironmentFile=/etc/opensandbox/worker-identity.env
+# Raise limits for many concurrent VMs
+LimitNOFILE=1000000
+LimitNPROC=65536
[Install]
WantedBy=multi-user.target
SVC
-sudo mkdir -p /etc/opensandbox /data/sandboxes
-
-# -------------------------------------------------------------------
-# Kernel modules for CRIU (loaded at boot)
-# -------------------------------------------------------------------
-echo "==> Configuring kernel modules for CRIU..."
-sudo tee /etc/modules-load.d/opensandbox.conf > /dev/null <<EOF
-inet_diag
-tcp_diag
-udp_diag
-unix_diag
-netlink_diag
-EOF
+sudo mkdir -p /etc/opensandbox /data/sandboxes /data/firecracker/images /data/checkpoints
# -------------------------------------------------------------------
# Enable services
@@ -280,9 +283,17 @@ echo ""
echo "============================================"
echo " Instance setup complete! ($ARCH)"
echo ""
+echo " Installed:"
+echo " - Firecracker $(firecracker --version | head -1)"
+echo " - Podman $(podman --version)"
+echo " - Redis"
+echo " - Caddy (with Route53 DNS)"
+echo ""
echo " Remaining steps:"
-echo " 1. Deploy the worker binary: ./deploy/ec2/deploy-worker.sh"
-echo " 2. Copy Caddyfile to /etc/caddy/Caddyfile"
-echo " 3. Start services: sudo systemctl start opensandbox-worker"
-echo " 4. Set up wildcard DNS: *.workers.opensandbox.ai -> this instance IP"
+echo " 1. Deploy worker + agent binaries: ./deploy/ec2/deploy-worker.sh"
+echo " 2. Download kernel: scp bin/vmlinux-arm64 to /data/firecracker/"
+echo " 3. Build base rootfs images: sudo ./scripts/build-rootfs.sh all"
+echo " 4. Copy Caddyfile to /etc/caddy/Caddyfile"
+echo " 5. Start services: sudo systemctl start opensandbox-worker"
+echo " 6. Set up wildcard DNS: *.workers.opensandbox.ai -> this instance IP"
echo "============================================"
diff --git a/deploy/firecracker/rootfs/Dockerfile.node b/deploy/firecracker/rootfs/Dockerfile.node
new file mode 100644
index 00000000..99826962
--- /dev/null
+++ b/deploy/firecracker/rootfs/Dockerfile.node
@@ -0,0 +1,50 @@
+# Node.js base rootfs for OpenSandbox Firecracker VMs
+# Build: scripts/build-rootfs.sh node
+FROM ubuntu:22.04
+
+# Prevent interactive prompts during package installation
+ENV DEBIAN_FRONTEND=noninteractive
+
+# Install essential system packages
+RUN apt-get update && apt-get install -y --no-install-recommends \
+ bash \
+ busybox \
+ ca-certificates \
+ curl \
+ git \
+ iproute2 \
+ iputils-ping \
+ jq \
+ less \
+ nano \
+ net-tools \
+ openssh-client \
+ procps \
+ sudo \
+ tar \
+ unzip \
+ vim-tiny \
+ wget \
+ zip \
+ # Build tools for native npm modules
+ build-essential \
+ python3 \
+ && rm -rf /var/lib/apt/lists/*
+
+# Install Node.js 20 LTS via NodeSource
+RUN curl -fsSL https://deb.nodesource.com/setup_20.x | bash - \
+ && apt-get install -y nodejs \
+ && rm -rf /var/lib/apt/lists/*
+
+# Install common global npm packages
+RUN npm install -g npm@latest
+
+# Create workspace directory
+RUN mkdir -p /workspace
+
+# Set default working directory
+WORKDIR /workspace
+
+# Default locale
+ENV LANG=C.UTF-8
+ENV LC_ALL=C.UTF-8
diff --git a/deploy/firecracker/rootfs/Dockerfile.python b/deploy/firecracker/rootfs/Dockerfile.python
new file mode 100644
index 00000000..a835b443
--- /dev/null
+++ b/deploy/firecracker/rootfs/Dockerfile.python
@@ -0,0 +1,50 @@
+# Python base rootfs for OpenSandbox Firecracker VMs
+# Build: scripts/build-rootfs.sh python
+FROM ubuntu:22.04
+
+# Prevent interactive prompts during package installation
+ENV DEBIAN_FRONTEND=noninteractive
+
+# Install essential system packages + Python
+RUN apt-get update && apt-get install -y --no-install-recommends \
+ bash \
+ busybox \
+ ca-certificates \
+ curl \
+ git \
+ iproute2 \
+ iputils-ping \
+ jq \
+ less \
+ nano \
+ net-tools \
+ openssh-client \
+ procps \
+ sudo \
+ tar \
+ unzip \
+ vim-tiny \
+ wget \
+ zip \
+ # Python
+ python3 \
+ python3-pip \
+ python3-venv \
+ python3-dev \
+ && rm -rf /var/lib/apt/lists/*
+
+# Create python3 → python symlink if needed
+RUN which python || ln -s /usr/bin/python3 /usr/bin/python
+
+# Upgrade pip
+RUN pip3 install --no-cache-dir --upgrade pip setuptools wheel
+
+# Create workspace directory
+RUN mkdir -p /workspace
+
+# Set default working directory
+WORKDIR /workspace
+
+# Default locale
+ENV LANG=C.UTF-8
+ENV LC_ALL=C.UTF-8
diff --git a/deploy/firecracker/rootfs/Dockerfile.ubuntu b/deploy/firecracker/rootfs/Dockerfile.ubuntu
new file mode 100644
index 00000000..d0ba47ac
--- /dev/null
+++ b/deploy/firecracker/rootfs/Dockerfile.ubuntu
@@ -0,0 +1,39 @@
+# Ubuntu base rootfs for OpenSandbox Firecracker VMs
+# Build: scripts/build-rootfs.sh ubuntu
+FROM ubuntu:22.04
+
+# Prevent interactive prompts during package installation
+ENV DEBIAN_FRONTEND=noninteractive
+
+# Install essential system packages
+RUN apt-get update && apt-get install -y --no-install-recommends \
+ bash \
+ busybox \
+ ca-certificates \
+ curl \
+ git \
+ iproute2 \
+ iputils-ping \
+ jq \
+ less \
+ nano \
+ net-tools \
+ openssh-client \
+ procps \
+ sudo \
+ tar \
+ unzip \
+ vim-tiny \
+ wget \
+ zip \
+ && rm -rf /var/lib/apt/lists/*
+
+# Create workspace directory
+RUN mkdir -p /workspace
+
+# Set default working directory
+WORKDIR /workspace
+
+# Default locale
+ENV LANG=C.UTF-8
+ENV LC_ALL=C.UTF-8
diff --git a/internal/agent/exec.go b/internal/agent/exec.go
new file mode 100644
index 00000000..597f91d6
--- /dev/null
+++ b/internal/agent/exec.go
@@ -0,0 +1,169 @@
+package agent
+
+import (
+ "bytes"
+ "context"
+ "fmt"
+ "os/exec"
+ "syscall"
+ "time"
+
+ pb "github.com/opensandbox/opensandbox/proto/agent"
+)
+
+// Exec runs a command synchronously and returns stdout/stderr/exit code.
+func (s *Server) Exec(ctx context.Context, req *pb.ExecRequest) (*pb.ExecResponse, error) {
+ timeout := time.Duration(req.TimeoutSeconds) * time.Second
+ if timeout <= 0 {
+ timeout = 60 * time.Second
+ }
+
+ ctx, cancel := context.WithTimeout(ctx, timeout)
+ defer cancel()
+
+ cmd := exec.CommandContext(ctx, req.Command, req.Args...)
+
+ // Set working directory
+ if req.Cwd != "" {
+ cmd.Dir = req.Cwd
+ } else {
+ cmd.Dir = "/workspace"
+ }
+
+ // Set environment variables — always set HOME=/workspace so tools
+ // (npm, pip, etc.) use the NVMe-backed workspace for caches.
+ cmd.Env = append(cmd.Environ(), "HOME=/workspace")
+ if len(req.Envs) > 0 {
+ cmd.Env = append(cmd.Env, mapToEnv(req.Envs)...)
+ }
+
+ // Set process group so we can kill the entire tree
+ cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
+
+ var stdout, stderr bytes.Buffer
+ cmd.Stdout = &stdout
+ cmd.Stderr = &stderr
+
+ err := cmd.Run()
+
+ exitCode := 0
+ if err != nil {
+ if exitErr, ok := err.(*exec.ExitError); ok {
+ exitCode = exitErr.ExitCode()
+ } else if ctx.Err() == context.DeadlineExceeded {
+ return &pb.ExecResponse{
+ ExitCode: -1,
+ Stdout: stdout.String(),
+ Stderr: stderr.String() + "\nProcess timed out",
+ }, nil
+ } else {
+ return nil, fmt.Errorf("exec failed: %w", err)
+ }
+ }
+
+ return &pb.ExecResponse{
+ ExitCode: int32(exitCode),
+ Stdout: stdout.String(),
+ Stderr: stderr.String(),
+ }, nil
+}
+
+// ExecStream runs a command and streams stdout/stderr chunks.
+func (s *Server) ExecStream(req *pb.ExecRequest, stream pb.SandboxAgent_ExecStreamServer) error {
+ timeout := time.Duration(req.TimeoutSeconds) * time.Second
+ if timeout <= 0 {
+ timeout = 60 * time.Second
+ }
+
+ ctx, cancel := context.WithTimeout(stream.Context(), timeout)
+ defer cancel()
+
+ cmd := exec.CommandContext(ctx, req.Command, req.Args...)
+
+ if req.Cwd != "" {
+ cmd.Dir = req.Cwd
+ } else {
+ cmd.Dir = "/workspace"
+ }
+
+ cmd.Env = append(cmd.Environ(), "HOME=/workspace")
+ if len(req.Envs) > 0 {
+ cmd.Env = append(cmd.Env, mapToEnv(req.Envs)...)
+ }
+
+ cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
+
+ stdoutPipe, err := cmd.StdoutPipe()
+ if err != nil {
+ return fmt.Errorf("stdout pipe: %w", err)
+ }
+ stderrPipe, err := cmd.StderrPipe()
+ if err != nil {
+ return fmt.Errorf("stderr pipe: %w", err)
+ }
+
+ if err := cmd.Start(); err != nil {
+ return fmt.Errorf("start: %w", err)
+ }
+
+ // Stream stdout and stderr in parallel
+ errCh := make(chan error, 2)
+
+ go func() {
+ buf := make([]byte, 4096)
+ for {
+ n, err := stdoutPipe.Read(buf)
+ if n > 0 {
+ if sendErr := stream.Send(&pb.ExecOutputChunk{
+ Stream: pb.ExecOutputChunk_STDOUT,
+ Data: buf[:n],
+ }); sendErr != nil {
+ errCh <- sendErr
+ return
+ }
+ }
+ if err != nil {
+ errCh <- nil
+ return
+ }
+ }
+ }()
+
+ go func() {
+ buf := make([]byte, 4096)
+ for {
+ n, err := stderrPipe.Read(buf)
+ if n > 0 {
+ if sendErr := stream.Send(&pb.ExecOutputChunk{
+ Stream: pb.ExecOutputChunk_STDERR,
+ Data: buf[:n],
+ }); sendErr != nil {
+ errCh <- sendErr
+ return
+ }
+ }
+ if err != nil {
+ errCh <- nil
+ return
+ }
+ }
+ }()
+
+ // Wait for both pipes to close
+ <-errCh
+ <-errCh
+
+ // Wait for command to finish
+ _ = cmd.Wait()
+
+ return nil
+}
+
+// mapToEnv converts a map to KEY=VALUE slice.
+func mapToEnv(m map[string]string) []string {
+ env := make([]string, 0, len(m))
+ for k, v := range m {
+ env = append(env, k+"="+v)
+ }
+ return env
+}
diff --git a/internal/agent/filesystem.go b/internal/agent/filesystem.go
new file mode 100644
index 00000000..a3706137
--- /dev/null
+++ b/internal/agent/filesystem.go
@@ -0,0 +1,115 @@
+package agent
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "path/filepath"
+
+ pb "github.com/opensandbox/opensandbox/proto/agent"
+)
+
+// ReadFile reads a file from the VM filesystem.
+func (s *Server) ReadFile(ctx context.Context, req *pb.ReadFileRequest) (*pb.ReadFileResponse, error) {
+ path := resolvePath(req.Path)
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return nil, fmt.Errorf("read %s: %w", path, err)
+ }
+ return &pb.ReadFileResponse{Content: data}, nil
+}
+
+// WriteFile writes content to a file in the VM filesystem.
+func (s *Server) WriteFile(ctx context.Context, req *pb.WriteFileRequest) (*pb.WriteFileResponse, error) {
+ path := resolvePath(req.Path)
+
+ // Ensure parent directory exists
+ dir := filepath.Dir(path)
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ return nil, fmt.Errorf("mkdir %s: %w", dir, err)
+ }
+
+ mode := os.FileMode(req.Mode)
+ if mode == 0 {
+ mode = 0644
+ }
+
+ if err := os.WriteFile(path, req.Content, mode); err != nil {
+ return nil, fmt.Errorf("write %s: %w", path, err)
+ }
+ return &pb.WriteFileResponse{}, nil
+}
+
+// ListDir lists entries in a directory.
+func (s *Server) ListDir(ctx context.Context, req *pb.ListDirRequest) (*pb.ListDirResponse, error) {
+ path := resolvePath(req.Path)
+ entries, err := os.ReadDir(path)
+ if err != nil {
+ return nil, fmt.Errorf("readdir %s: %w", path, err)
+ }
+
+ result := make([]*pb.DirEntry, 0, len(entries))
+ for _, e := range entries {
+ info, err := e.Info()
+ if err != nil {
+ continue
+ }
+ result = append(result, &pb.DirEntry{
+ Name: e.Name(),
+ IsDir: e.IsDir(),
+ Size: info.Size(),
+ Path: filepath.Join(path, e.Name()),
+ })
+ }
+ return &pb.ListDirResponse{Entries: result}, nil
+}
+
+// MakeDir creates a directory (with parents).
+func (s *Server) MakeDir(ctx context.Context, req *pb.MakeDirRequest) (*pb.MakeDirResponse, error) {
+ path := resolvePath(req.Path)
+ if err := os.MkdirAll(path, 0755); err != nil {
+ return nil, fmt.Errorf("mkdir %s: %w", path, err)
+ }
+ return &pb.MakeDirResponse{}, nil
+}
+
+// Remove removes a file or directory (recursively).
+func (s *Server) Remove(ctx context.Context, req *pb.RemoveRequest) (*pb.RemoveResponse, error) {
+ path := resolvePath(req.Path)
+ if err := os.RemoveAll(path); err != nil {
+ return nil, fmt.Errorf("remove %s: %w", path, err)
+ }
+ return &pb.RemoveResponse{}, nil
+}
+
+// Exists checks if a path exists.
+func (s *Server) Exists(ctx context.Context, req *pb.ExistsRequest) (*pb.ExistsResponse, error) {
+ path := resolvePath(req.Path)
+ _, err := os.Stat(path)
+ return &pb.ExistsResponse{Exists: err == nil}, nil
+}
+
+// Stat returns file metadata.
+func (s *Server) Stat(ctx context.Context, req *pb.StatRequest) (*pb.StatResponse, error) {
+ path := resolvePath(req.Path)
+ info, err := os.Stat(path)
+ if err != nil {
+ return nil, fmt.Errorf("stat %s: %w", path, err)
+ }
+ return &pb.StatResponse{
+ Name: info.Name(),
+ IsDir: info.IsDir(),
+ Size: info.Size(),
+ Mode: info.Mode().String(),
+ ModTime: info.ModTime().UTC().Format("2006-01-02T15:04:05Z"),
+ Path: path,
+ }, nil
+}
+
+// resolvePath ensures paths are rooted in /workspace for relative paths.
+func resolvePath(path string) string {
+ if filepath.IsAbs(path) {
+ return filepath.Clean(path)
+ }
+ return filepath.Join("/workspace", path)
+}
diff --git a/internal/agent/pty.go b/internal/agent/pty.go
new file mode 100644
index 00000000..fdddfd90
--- /dev/null
+++ b/internal/agent/pty.go
@@ -0,0 +1,206 @@
+package agent
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "os"
+ "os/exec"
+ "sync"
+
+ "github.com/creack/pty"
+ "github.com/google/uuid"
+ pb "github.com/opensandbox/opensandbox/proto/agent"
+)
+
+// ptySession holds a live PTY session inside the VM.
+type ptySession struct {
+ id string
+ cmd *exec.Cmd
+ ptyFile *os.File
+ dataPort uint32
+ cancel context.CancelFunc
+}
+
+// PTYCreate starts a new PTY session and returns the vsock data port.
+// The caller connects to that vsock port for raw I/O.
+func (s *Server) PTYCreate(ctx context.Context, req *pb.PTYCreateRequest) (*pb.PTYCreateResponse, error) {
+ shell := req.Shell
+ if shell == "" {
+ // Try common shells
+ for _, sh := range []string{"/bin/bash", "/bin/sh"} {
+ if _, err := os.Stat(sh); err == nil {
+ shell = sh
+ break
+ }
+ }
+ if shell == "" {
+ return nil, fmt.Errorf("no shell found")
+ }
+ }
+
+ sessionID := uuid.New().String()[:8]
+
+ s.ptyMu.Lock()
+ port := s.nextPTYPort
+ s.nextPTYPort++
+ s.ptyMu.Unlock()
+
+ sessCtx, cancel := context.WithCancel(context.Background())
+
+ cmd := exec.CommandContext(sessCtx, shell)
+ cmd.Dir = "/workspace"
+ cmd.Env = append(os.Environ(),
+ "HOME=/workspace",
+ "TERM=xterm-256color",
+ fmt.Sprintf("COLUMNS=%d", req.Cols),
+ fmt.Sprintf("LINES=%d", req.Rows),
+ )
+
+ cols := uint16(req.Cols)
+ rows := uint16(req.Rows)
+ if cols == 0 {
+ cols = 80
+ }
+ if rows == 0 {
+ rows = 24
+ }
+
+ ptmx, err := pty.StartWithSize(cmd, &pty.Winsize{
+ Cols: cols,
+ Rows: rows,
+ })
+ if err != nil {
+ cancel()
+ return nil, fmt.Errorf("start pty: %w", err)
+ }
+
+ sess := &ptySession{
+ id: sessionID,
+ cmd: cmd,
+ ptyFile: ptmx,
+ dataPort: port,
+ cancel: cancel,
+ }
+
+ s.ptyMu.Lock()
+ s.ptySessions[sessionID] = sess
+ s.ptyMu.Unlock()
+
+ // Start vsock listener for PTY data on the allocated port.
+ // We must ensure the listener is ready before returning the port to the
+ // caller, otherwise the host may CONNECT before we're listening.
+ lisReady := make(chan error, 1)
+ go s.servePTYData(sess, sessCtx, lisReady)
+
+ if err := <-lisReady; err != nil {
+ cancel()
+ s.ptyMu.Lock()
+ delete(s.ptySessions, sessionID)
+ s.ptyMu.Unlock()
+ return nil, fmt.Errorf("pty data listen: %w", err)
+ }
+
+ return &pb.PTYCreateResponse{
+ SessionId: sessionID,
+ DataPort: port,
+ }, nil
+}
+
+// servePTYData listens on a vsock port and bridges I/O to/from the PTY.
+// Uses native AF_VSOCK so the host can connect via Firecracker's vsock UDS.
+// The ready channel signals when the listener is up (nil) or failed (error).
+func (s *Server) servePTYData(sess *ptySession, ctx context.Context, ready chan<- error) {
+ if s.ListenPort == nil {
+ ready <- fmt.Errorf("no ListenPort function set")
+ return
+ }
+
+ lis, err := s.ListenPort(sess.dataPort)
+ if err != nil {
+ ready <- fmt.Errorf("listen port %d: %w", sess.dataPort, err)
+ return
+ }
+ defer lis.Close()
+
+ // Signal that we're ready to accept connections
+ ready <- nil
+
+ // Accept at most one connection per PTY session
+ go func() {
+ <-ctx.Done()
+ lis.Close()
+ }()
+
+ conn, err := lis.Accept()
+ if err != nil {
+ return
+ }
+ defer conn.Close()
+
+ // Bidirectional copy: conn ↔ ptmx
+ var wg sync.WaitGroup
+ wg.Add(2)
+
+ // PTY → client
+ go func() {
+ defer wg.Done()
+ io.Copy(conn, sess.ptyFile)
+ }()
+
+ // Client → PTY
+ go func() {
+ defer wg.Done()
+ io.Copy(sess.ptyFile, conn)
+ }()
+
+ // Wait for command to exit
+ sess.cmd.Wait()
+ sess.ptyFile.Close()
+ wg.Wait()
+
+ // Clean up session
+ s.ptyMu.Lock()
+ delete(s.ptySessions, sess.id)
+ s.ptyMu.Unlock()
+}
+
+// PTYResize changes the terminal size for an active PTY session.
+func (s *Server) PTYResize(ctx context.Context, req *pb.PTYResizeRequest) (*pb.PTYResizeResponse, error) {
+ s.ptyMu.Lock()
+ sess, ok := s.ptySessions[req.SessionId]
+ s.ptyMu.Unlock()
+ if !ok {
+ return nil, fmt.Errorf("pty session %s not found", req.SessionId)
+ }
+
+ if err := pty.Setsize(sess.ptyFile, &pty.Winsize{
+ Cols: uint16(req.Cols),
+ Rows: uint16(req.Rows),
+ }); err != nil {
+ return nil, fmt.Errorf("resize: %w", err)
+ }
+ return &pb.PTYResizeResponse{}, nil
+}
+
+// PTYKill terminates a PTY session.
+func (s *Server) PTYKill(ctx context.Context, req *pb.PTYKillRequest) (*pb.PTYKillResponse, error) {
+ s.ptyMu.Lock()
+ sess, ok := s.ptySessions[req.SessionId]
+ if ok {
+ delete(s.ptySessions, sess.id)
+ }
+ s.ptyMu.Unlock()
+
+ if !ok {
+ return nil, fmt.Errorf("pty session %s not found", req.SessionId)
+ }
+
+ sess.cancel()
+ sess.ptyFile.Close()
+ if sess.cmd.Process != nil {
+ sess.cmd.Process.Kill()
+ }
+
+ return &pb.PTYKillResponse{}, nil
+}
diff --git a/internal/agent/server.go b/internal/agent/server.go
new file mode 100644
index 00000000..1456955c
--- /dev/null
+++ b/internal/agent/server.go
@@ -0,0 +1,67 @@
+// Package agent implements the in-VM sandbox agent that runs inside each
+// Firecracker microVM. It serves gRPC over vsock and handles exec, file ops,
+// PTY, and stats collection. This binary is statically compiled and injected
+// into the VM rootfs image.
+package agent
+
+import (
+ "log"
+ "net"
+ "sync"
+ "time"
+
+ pb "github.com/opensandbox/opensandbox/proto/agent"
+ "google.golang.org/grpc"
+)
+
+const (
+ // DefaultGRPCPort is the vsock port the agent listens on for gRPC.
+ DefaultGRPCPort = 1024
+ // PTYDataPortBase is the base vsock port for PTY data streams.
+ // Each PTY session gets PTYDataPortBase + N.
+ PTYDataPortBase = 2000
+)
+
+// ListenPortFunc creates a net.Listener for the given port.
+// The implementation is platform-specific (vsock inside Firecracker,
+// Unix socket for testing outside Firecracker).
+type ListenPortFunc func(port uint32) (net.Listener, error)
+
+// Server is the gRPC agent server that runs inside a Firecracker VM.
+type Server struct {
+ pb.UnimplementedSandboxAgentServer
+
+ startTime time.Time
+ version string
+
+ // ListenPort creates a listener for PTY data ports.
+ // Set by the main package based on the platform (vsock or unix).
+ ListenPort ListenPortFunc
+
+ // PTY sessions
+ ptyMu sync.Mutex
+ ptySessions map[string]*ptySession
+ nextPTYPort uint32
+}
+
+// NewServer creates a new agent server.
+func NewServer(version string) *Server {
+ return &Server{
+ startTime: time.Now(),
+ version: version,
+ ptySessions: make(map[string]*ptySession),
+ nextPTYPort: PTYDataPortBase,
+ }
+}
+
+// Serve starts the gRPC server on the given listener.
+func (s *Server) Serve(lis net.Listener) error {
+ grpcServer := grpc.NewServer(
+ grpc.MaxRecvMsgSize(64 * 1024 * 1024), // 64MB for file transfers
+ grpc.MaxSendMsgSize(64 * 1024 * 1024),
+ )
+ pb.RegisterSandboxAgentServer(grpcServer, s)
+
+ log.Printf("agent: gRPC server listening")
+ return grpcServer.Serve(lis)
+}
diff --git a/internal/agent/stats.go b/internal/agent/stats.go
new file mode 100644
index 00000000..71ace7c2
--- /dev/null
+++ b/internal/agent/stats.go
@@ -0,0 +1,195 @@
+package agent
+
+import (
+ "bufio"
+ "context"
+ "fmt"
+ "os"
+ "strconv"
+ "strings"
+ "time"
+
+ pb "github.com/opensandbox/opensandbox/proto/agent"
+)
+
+// Ping responds with the agent version and uptime.
+func (s *Server) Ping(ctx context.Context, req *pb.PingRequest) (*pb.PingResponse, error) {
+ return &pb.PingResponse{
+ Version: s.version,
+ UptimeSeconds: int64(time.Since(s.startTime).Seconds()),
+ }, nil
+}
+
+// Shutdown syncs disks and signals for clean shutdown.
+func (s *Server) Shutdown(ctx context.Context, req *pb.ShutdownRequest) (*pb.ShutdownResponse, error) {
+ // Sync all filesystems
+ _ = syncFS()
+
+ // Clean shutdown — the init process will handle the rest
+ go func() {
+ time.Sleep(100 * time.Millisecond)
+ os.Exit(0)
+ }()
+ return &pb.ShutdownResponse{}, nil
+}
+
+// Stats reads live resource usage from /proc.
+func (s *Server) Stats(ctx context.Context, req *pb.StatsRequest) (*pb.StatsResponse, error) {
+ resp := &pb.StatsResponse{}
+
+ // Memory from /proc/meminfo
+ memTotal, memAvail := readMemInfo()
+ resp.MemLimit = memTotal
+ resp.MemUsage = memTotal - memAvail
+
+ // CPU from /proc/stat (instantaneous — two samples)
+ resp.CpuPercent = readCPUPercent()
+
+ // PIDs from /proc
+ resp.Pids = int32(countPIDs())
+
+ // Network from /proc/net/dev
+ resp.NetInput, resp.NetOutput = readNetStats()
+
+ return resp, nil
+}
+
+// readMemInfo parses /proc/meminfo for MemTotal and MemAvailable.
+func readMemInfo() (total, available uint64) {
+ f, err := os.Open("/proc/meminfo")
+ if err != nil {
+ return 0, 0
+ }
+ defer f.Close()
+
+ scanner := bufio.NewScanner(f)
+ for scanner.Scan() {
+ line := scanner.Text()
+ if strings.HasPrefix(line, "MemTotal:") {
+ total = parseMemLine(line) * 1024 // kB → bytes
+ } else if strings.HasPrefix(line, "MemAvailable:") {
+ available = parseMemLine(line) * 1024
+ }
+ }
+ return total, available
+}
+
+// parseMemLine extracts the numeric value from "MemTotal: 123456 kB".
+func parseMemLine(line string) uint64 {
+ fields := strings.Fields(line)
+ if len(fields) < 2 {
+ return 0
+ }
+ v, _ := strconv.ParseUint(fields[1], 10, 64)
+ return v
+}
+
+// readCPUPercent takes two snapshots of /proc/stat 100ms apart and
+// computes the CPU usage percentage.
+func readCPUPercent() float64 {
+ idle1, total1 := readCPUSample()
+ time.Sleep(100 * time.Millisecond)
+ idle2, total2 := readCPUSample()
+
+ totalDelta := float64(total2 - total1)
+ idleDelta := float64(idle2 - idle1)
+
+ if totalDelta == 0 {
+ return 0
+ }
+ return (1.0 - idleDelta/totalDelta) * 100.0
+}
+
+// readCPUSample reads the aggregate CPU line from /proc/stat.
+func readCPUSample() (idle, total uint64) {
+ data, err := os.ReadFile("/proc/stat")
+ if err != nil {
+ return 0, 0
+ }
+ // First line: "cpu user nice system idle iowait irq softirq steal ..."
+ line := strings.SplitN(string(data), "\n", 2)[0]
+ fields := strings.Fields(line)
+ if len(fields) < 5 || fields[0] != "cpu" {
+ return 0, 0
+ }
+
+ for i := 1; i < len(fields); i++ {
+ v, _ := strconv.ParseUint(fields[i], 10, 64)
+ total += v
+ if i == 4 { // idle is the 4th value after "cpu"
+ idle = v
+ }
+ }
+ return idle, total
+}
+
+// countPIDs counts /proc/[0-9]* directories.
+func countPIDs() int {
+ entries, err := os.ReadDir("/proc")
+ if err != nil {
+ return 0
+ }
+ count := 0
+ for _, e := range entries {
+ if e.IsDir() && len(e.Name()) > 0 && e.Name()[0] >= '0' && e.Name()[0] <= '9' {
+ count++
+ }
+ }
+ return count
+}
+
+// readNetStats sums rx/tx bytes across all interfaces (excluding lo).
+func readNetStats() (rxBytes, txBytes uint64) {
+ f, err := os.Open("/proc/net/dev")
+ if err != nil {
+ return 0, 0
+ }
+ defer f.Close()
+
+ scanner := bufio.NewScanner(f)
+ lineNum := 0
+ for scanner.Scan() {
+ lineNum++
+ if lineNum <= 2 {
+ continue // skip headers
+ }
+ line := scanner.Text()
+ parts := strings.SplitN(line, ":", 2)
+ if len(parts) != 2 {
+ continue
+ }
+ iface := strings.TrimSpace(parts[0])
+ if iface == "lo" {
+ continue
+ }
+ fields := strings.Fields(parts[1])
+ if len(fields) < 10 {
+ continue
+ }
+ rx, _ := strconv.ParseUint(fields[0], 10, 64)
+ tx, _ := strconv.ParseUint(fields[8], 10, 64)
+ rxBytes += rx
+ txBytes += tx
+ }
+ return rxBytes, txBytes
+}
+
+// SyncFS flushes all filesystem buffers without exiting the agent.
+func (s *Server) SyncFS(ctx context.Context, req *pb.SyncFSRequest) (*pb.SyncFSResponse, error) {
+ if err := syncFS(); err != nil {
+ return nil, err
+ }
+ return &pb.SyncFSResponse{}, nil
+}
+
+// syncFS calls sync(2) to flush all filesystems.
+func syncFS() error {
+ f, err := os.Open("/")
+ if err != nil {
+ return fmt.Errorf("open /: %w", err)
+ }
+ defer f.Close()
+ // sync(2) — we use SyncFileRange isn't available on all filesystems,
+ // just use Sync on the root fd which triggers global sync
+ return f.Sync()
+}
diff --git a/internal/api/commands.go b/internal/api/commands.go
index 54fb7da9..6bba01e8 100644
--- a/internal/api/commands.go
+++ b/internal/api/commands.go
@@ -2,20 +2,27 @@ package api
import (
"context"
+ "log"
"net/http"
"time"
"github.com/labstack/echo/v4"
"github.com/opensandbox/opensandbox/pkg/types"
+ pb "github.com/opensandbox/opensandbox/proto/worker"
)
func (s *Server) runCommand(c echo.Context) error {
+ id := c.Param("id")
+
+ // Server mode: dispatch to worker via gRPC
+ if s.workerRegistry != nil {
+ return s.runCommandRemote(c, id)
+ }
+
if s.manager == nil {
return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)
}
- id := c.Param("id")
-
var cfg types.ProcessConfig
if err := c.Bind(&cfg); err != nil {
return c.JSON(http.StatusBadRequest, map[string]string{
@@ -68,3 +75,70 @@ func (s *Server) runCommand(c echo.Context) error {
return c.JSON(http.StatusOK, result)
}
+
+func (s *Server) runCommandRemote(c echo.Context, sandboxID string) error {
+ if s.store == nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{
+ "error": "database not configured",
+ })
+ }
+
+ var cfg types.ProcessConfig
+ if err := c.Bind(&cfg); err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{
+ "error": "invalid request body: " + err.Error(),
+ })
+ }
+
+ if cfg.Command == "" {
+ return c.JSON(http.StatusBadRequest, map[string]string{
+ "error": "cmd is required",
+ })
+ }
+
+ // Look up which worker has this sandbox
+ session, err := s.store.GetSandboxSession(c.Request().Context(), sandboxID)
+ if err != nil {
+ return c.JSON(http.StatusNotFound, map[string]string{
+ "error": "sandbox not found",
+ })
+ }
+
+ client, err := s.workerRegistry.GetWorkerClient(session.WorkerID)
+ if err != nil {
+ log.Printf("commands: worker %s unreachable for exec: %v", session.WorkerID, err)
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{
+ "error": "worker unreachable",
+ })
+ }
+
+ timeout := 30 * time.Second
+ if cfg.Timeout > 0 {
+ timeout = time.Duration(cfg.Timeout) * time.Second
+ }
+ grpcCtx, cancel := context.WithTimeout(c.Request().Context(), timeout)
+ defer cancel()
+
+ resp, err := client.ExecCommand(grpcCtx, &pb.ExecCommandRequest{
+ SandboxId: sandboxID,
+ Command: cfg.Command,
+ Args: cfg.Args,
+ Envs: cfg.Env,
+ Cwd: cfg.Cwd,
+ Timeout: int32(cfg.Timeout),
+ })
+ if err != nil {
+ log.Printf("commands: gRPC exec failed for %s: %v", sandboxID, err)
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": err.Error(),
+ })
+ }
+
+ result := &types.ProcessResult{
+ ExitCode: int(resp.ExitCode),
+ Stdout: resp.Stdout,
+ Stderr: resp.Stderr,
+ }
+
+ return c.JSON(http.StatusOK, result)
+}
diff --git a/internal/api/router.go b/internal/api/router.go
index b7a46f70..e874f51d 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -26,7 +26,7 @@ var errSandboxNotAvailable = map[string]string{
// Server holds the API server dependencies.
type Server struct {
echo *echo.Echo
- manager *sandbox.Manager
+ manager sandbox.Manager
router *sandbox.SandboxRouter // routes all sandbox interactions (state machine, auto-wake, rolling timeout)
ptyManager *sandbox.PTYManager
store *db.Store // nil in combined/dev mode without PG
@@ -54,6 +54,7 @@ type ServerOpts struct {
SandboxDBs *sandbox.SandboxDBManager
Router *sandbox.SandboxRouter // nil in server-only mode
SandboxProxy *proxy.SandboxProxy // nil if subdomain routing not configured
+ ControlPlaneProxy *proxy.ControlPlaneProxy // nil except in server mode (routes subdomains to workers)
SandboxDomain string // base domain for sandbox subdomains
WorkOSConfig *auth.WorkOSConfig // nil if WorkOS not configured
WorkerRegistry *controlplane.RedisWorkerRegistry // nil in combined/worker mode
@@ -62,7 +63,7 @@ type ServerOpts struct {
}
// NewServer creates a new API server with all routes configured.
-func NewServer(mgr *sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, opts *ServerOpts) *Server {
+func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, opts *ServerOpts) *Server {
e := echo.New()
e.HideBanner = true
e.HidePort = true
@@ -98,6 +99,9 @@ func NewServer(mgr *sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string,
if opts != nil && opts.SandboxProxy != nil {
e.Use(opts.SandboxProxy.Middleware())
}
+ if opts != nil && opts.ControlPlaneProxy != nil {
+ e.Use(opts.ControlPlaneProxy.Middleware())
+ }
// Health check (no auth)
e.GET("/health", func(c echo.Context) error {
@@ -140,6 +144,9 @@ func NewServer(mgr *sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string,
api.GET("/templates/:name", s.getTemplate)
api.DELETE("/templates/:name", s.deleteTemplate)
+ // Workers (server mode only — queries worker registry)
+ api.GET("/workers", s.listWorkers)
+
// Session history (requires PG)
api.GET("/sessions", s.listSessions)
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index 365ffb55..5df82137 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -748,6 +748,15 @@ func (s *Server) wakeSandboxRemote(c echo.Context, sandboxID string, req types.W
}
// listSessions returns session history from PostgreSQL.
+func (s *Server) listWorkers(c echo.Context) error {
+ if s.workerRegistry == nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{
+ "error": "worker registry not available (server mode only)",
+ })
+ }
+ return c.JSON(http.StatusOK, s.workerRegistry.GetAllWorkers())
+}
+
func (s *Server) listSessions(c echo.Context) error {
if s.store == nil {
return c.JSON(http.StatusServiceUnavailable, map[string]string{
diff --git a/internal/config/config.go b/internal/config/config.go
index fa6164bb..49f6d1d6 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -70,8 +70,13 @@ type Config struct {
DefaultSandboxCPUs int // default vCPUs per sandbox, default 1
DefaultSandboxDiskMB int // default disk quota per sandbox (MB), 0 = no quota
+ // Firecracker microVM configuration (worker mode)
+ FirecrackerBin string // Path to firecracker binary (default: "firecracker")
+ KernelPath string // Path to vmlinux kernel (default: $DataDir/firecracker/vmlinux-arm64)
+ ImagesDir string // Path to base rootfs images (default: $DataDir/firecracker/images/)
+
// AWS EC2 compute pool (server mode only — for auto-scaling worker machines)
- EC2AMI string // Custom AMI with Podman+CRIU pre-installed
+ EC2AMI string // Custom AMI with Firecracker pre-installed
EC2InstanceType string // e.g. "c7gd.metal", "r6gd.metal", "r7gd.metal"
EC2SubnetID string // VPC subnet for worker instances
EC2SecurityGroupID string // Security group (allow 8080, 9090, 9091)
@@ -141,6 +146,10 @@ func Load() (*Config, error) {
DefaultSandboxCPUs: envOrDefaultInt("OPENSANDBOX_DEFAULT_SANDBOX_CPUS", 1),
DefaultSandboxDiskMB: envOrDefaultInt("OPENSANDBOX_DEFAULT_SANDBOX_DISK_MB", 0),
+ FirecrackerBin: envOrDefault("OPENSANDBOX_FIRECRACKER_BIN", "firecracker"),
+ KernelPath: os.Getenv("OPENSANDBOX_KERNEL_PATH"), // default derived from DataDir
+ ImagesDir: os.Getenv("OPENSANDBOX_IMAGES_DIR"), // default derived from DataDir
+
EC2AMI: os.Getenv("OPENSANDBOX_EC2_AMI"),
EC2InstanceType: envOrDefault("OPENSANDBOX_EC2_INSTANCE_TYPE", "c7gd.metal"),
EC2SubnetID: os.Getenv("OPENSANDBOX_EC2_SUBNET_ID"),
diff --git a/internal/controlplane/scaler.go b/internal/controlplane/scaler.go
index b4736d1c..4cd53f0d 100644
--- a/internal/controlplane/scaler.go
+++ b/internal/controlplane/scaler.go
@@ -13,6 +13,8 @@ const (
scaleUpThreshold = 0.70 // Scale up when utilization > 70%
scaleDownThreshold = 0.30 // Scale down when utilization < 30%
minWorkersPerRegion = 1
+ maxWorkersPerRegion = 10 // Hard cap to prevent runaway launches
+ pendingWorkerTTL = 10 * time.Minute // How long to wait for a launched worker to register
)
// ScalerRegistry is the interface the Scaler uses to query worker state.
@@ -32,6 +34,12 @@ type ScalerConfig struct {
Interval time.Duration // how often to evaluate scaling (0 = default 30s)
}
+// pendingLaunch tracks an EC2 instance that was launched but hasn't registered yet.
+type pendingLaunch struct {
+ machineID string
+ launchedAt time.Time
+}
+
// Scaler manages autoscaling of workers via the compute Pool.
type Scaler struct {
pool compute.Pool
@@ -39,7 +47,8 @@ type Scaler struct {
image string
cooldown time.Duration
interval time.Duration
- lastScaleUp map[string]time.Time // region -> last scale-up time
+ lastScaleUp map[string]time.Time // region -> last scale-up time
+ pending map[string][]pendingLaunch // region -> pending (unregistered) launches
stop chan struct{}
wg sync.WaitGroup
}
@@ -61,6 +70,7 @@ func NewScaler(cfg ScalerConfig) *Scaler {
cooldown: cooldown,
interval: interval,
lastScaleUp: make(map[string]time.Time),
+ pending: make(map[string][]pendingLaunch),
stop: make(chan struct{}),
}
}
@@ -105,6 +115,9 @@ func (s *Scaler) evaluateRegion(ctx context.Context, region string) {
workers := s.registry.GetWorkersByRegion(region)
utilization := s.registry.RegionUtilization(region)
+ // Expire stale pending launches
+ s.expirePending(region)
+
if utilization > scaleUpThreshold {
// Check cooldown before scaling up
if last, ok := s.lastScaleUp[region]; ok && time.Since(last) < s.cooldown {
@@ -112,6 +125,22 @@ func (s *Scaler) evaluateRegion(ctx context.Context, region string) {
region, s.cooldown-time.Since(last))
return
}
+
+ // Don't scale up if there are already pending (unregistered) workers
+ pending := s.pending[region]
+ if len(pending) > 0 {
+ log.Printf("scaler: region %s needs scale-up but %d worker(s) still pending registration",
+ region, len(pending))
+ return
+ }
+
+ // Don't exceed max workers per region
+ totalWorkers := len(workers) + len(pending)
+ if totalWorkers >= maxWorkersPerRegion {
+ log.Printf("scaler: region %s at max workers (%d), skipping scale-up", region, totalWorkers)
+ return
+ }
+
log.Printf("scaler: region %s utilization %.1f%% > %.0f%%, scaling up", region, utilization*100, scaleUpThreshold*100)
s.scaleUp(ctx, region)
} else if utilization < scaleDownThreshold && len(workers) > minWorkersPerRegion {
@@ -133,7 +162,47 @@ func (s *Scaler) scaleUp(ctx context.Context, region string) {
}
s.lastScaleUp[region] = time.Now()
- log.Printf("scaler: created machine %s in %s (addr=%s)", machine.ID, region, machine.Addr)
+ s.pending[region] = append(s.pending[region], pendingLaunch{
+ machineID: machine.ID,
+ launchedAt: time.Now(),
+ })
+ log.Printf("scaler: created machine %s in %s (addr=%s), pending registration", machine.ID, region, machine.Addr)
+}
+
+// expirePending removes pending launches that have either registered or timed out.
+func (s *Scaler) expirePending(region string) {
+ pending := s.pending[region]
+ if len(pending) == 0 {
+ return
+ }
+
+ // Get currently registered worker machine IDs
+ registered := make(map[string]bool)
+ for _, w := range s.registry.GetWorkersByRegion(region) {
+ if w.MachineID != "" {
+ registered[w.MachineID] = true
+ }
+ }
+
+ var remaining []pendingLaunch
+ for _, p := range pending {
+ if registered[p.machineID] {
+ log.Printf("scaler: pending machine %s in %s has registered", p.machineID, region)
+ continue
+ }
+ if time.Since(p.launchedAt) > pendingWorkerTTL {
+ log.Printf("scaler: pending machine %s in %s timed out after %s, terminating",
+ p.machineID, region, pendingWorkerTTL)
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ if err := s.pool.DestroyMachine(ctx, p.machineID); err != nil {
+ log.Printf("scaler: failed to terminate stale machine %s: %v", p.machineID, err)
+ }
+ cancel()
+ continue
+ }
+ remaining = append(remaining, p)
+ }
+ s.pending[region] = remaining
}
func (s *Scaler) scaleDown(ctx context.Context, region string, workers []*WorkerInfo) {
diff --git a/internal/controlplane/server.go b/internal/controlplane/server.go
index be5623ae..597a05f1 100644
--- a/internal/controlplane/server.go
+++ b/internal/controlplane/server.go
@@ -123,7 +123,8 @@ func (s *Server) createSandbox(c echo.Context) error {
}
// Call gRPC CreateSandbox on the worker
- ctx, cancel := context.WithTimeout(c.Request().Context(), 10*time.Second)
+ // Firecracker VM boot + agent readiness can take up to ~35s
+ ctx, cancel := context.WithTimeout(c.Request().Context(), 60*time.Second)
defer cancel()
conn, err := grpc.NewClient(worker.GRPCAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
diff --git a/internal/firecracker/agent_client.go b/internal/firecracker/agent_client.go
new file mode 100644
index 00000000..28c39699
--- /dev/null
+++ b/internal/firecracker/agent_client.go
@@ -0,0 +1,231 @@
+package firecracker
+
+import (
+ "bufio"
+ "context"
+ "fmt"
+ "net"
+ "strings"
+ "time"
+
+ pb "github.com/opensandbox/opensandbox/proto/agent"
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/credentials/insecure"
+)
+
+// AgentClient is the host-side gRPC client that connects to the
+// osb-agent running inside a Firecracker VM via vsock.
+type AgentClient struct {
+ conn *grpc.ClientConn
+ client pb.SandboxAgentClient
+}
+
+// NewAgentClient connects to the agent via the Firecracker vsock UDS.
+// In --no-api mode, Firecracker creates a single UDS file (vsock.sock).
+// To reach a guest port, the host connects to the UDS and sends
+// "CONNECT <port>\n". Firecracker responds with "OK <buf_size>\n"
+// and the connection is then relayed to the guest.
+func NewAgentClient(vsockPath string) (*AgentClient, error) {
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ conn, err := grpc.DialContext(ctx,
+ // Use passthrough scheme — the custom dialer handles the actual connection
+ "passthrough:///vsock",
+ grpc.WithTransportCredentials(insecure.NewCredentials()),
+ grpc.WithBlock(),
+ grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) {
+ return dialVsock(ctx, vsockPath, 1024)
+ }),
+ 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", vsockPath, err)
+ }
+
+ return &AgentClient{
+ conn: conn,
+ client: pb.NewSandboxAgentClient(conn),
+ }, nil
+}
+
+// dialVsock connects to a guest port via Firecracker's vsock UDS protocol.
+// Protocol: connect to the UDS, send "CONNECT <port>\n", read "OK ...\n".
+func dialVsock(ctx context.Context, vsockPath string, port int) (net.Conn, error) {
+ deadline, ok := ctx.Deadline()
+ if !ok {
+ deadline = time.Now().Add(5 * time.Second)
+ }
+
+ d := net.Dialer{Deadline: deadline}
+ conn, err := d.DialContext(ctx, "unix", vsockPath)
+ if err != nil {
+ return nil, fmt.Errorf("dial vsock UDS %s: %w", vsockPath, err)
+ }
+
+ // Send CONNECT command
+ _ = conn.SetDeadline(deadline)
+ if _, err := fmt.Fprintf(conn, "CONNECT %d\n", port); err != nil {
+ conn.Close()
+ return nil, fmt.Errorf("send CONNECT %d: %w", port, err)
+ }
+
+ // Read response line (e.g., "OK 1073741824\n")
+ reader := bufio.NewReader(conn)
+ line, err := reader.ReadString('\n')
+ if err != nil {
+ conn.Close()
+ return nil, fmt.Errorf("read vsock response: %w", err)
+ }
+ line = strings.TrimSpace(line)
+ if !strings.HasPrefix(line, "OK") {
+ conn.Close()
+ return nil, fmt.Errorf("vsock CONNECT failed: %s", line)
+ }
+
+ // Clear deadline — gRPC manages its own timeouts
+ _ = conn.SetDeadline(time.Time{})
+
+ // Wrap to handle the buffered reader (there may be buffered data from the OK line)
+ return &vsockConn{Conn: conn, reader: reader}, nil
+}
+
+// vsockConn wraps a net.Conn with a bufio.Reader to handle buffered reads
+// from the CONNECT handshake.
+type vsockConn struct {
+ net.Conn
+ reader *bufio.Reader
+}
+
+func (c *vsockConn) Read(p []byte) (int, error) {
+ return c.reader.Read(p)
+}
+
+// Close closes the gRPC connection.
+func (c *AgentClient) Close() error {
+ if c.conn != nil {
+ return c.conn.Close()
+ }
+ return nil
+}
+
+// Ping verifies the agent is responsive.
+func (c *AgentClient) Ping(ctx context.Context) (*pb.PingResponse, error) {
+ return c.client.Ping(ctx, &pb.PingRequest{})
+}
+
+// Exec runs a command in the VM.
+func (c *AgentClient) Exec(ctx context.Context, req *pb.ExecRequest) (*pb.ExecResponse, error) {
+ return c.client.Exec(ctx, req)
+}
+
+// ReadFile reads a file from the VM.
+func (c *AgentClient) ReadFile(ctx context.Context, path string) ([]byte, error) {
+ resp, err := c.client.ReadFile(ctx, &pb.ReadFileRequest{Path: path})
+ if err != nil {
+ return nil, err
+ }
+ return resp.Content, nil
+}
+
+// WriteFile writes a file in the VM.
+func (c *AgentClient) WriteFile(ctx context.Context, path string, content []byte) error {
+ _, err := c.client.WriteFile(ctx, &pb.WriteFileRequest{Path: path, Content: content})
+ return err
+}
+
+// ListDir lists a directory in the VM.
+func (c *AgentClient) ListDir(ctx context.Context, path string) ([]*pb.DirEntry, error) {
+ resp, err := c.client.ListDir(ctx, &pb.ListDirRequest{Path: path})
+ if err != nil {
+ return nil, err
+ }
+ return resp.Entries, nil
+}
+
+// MakeDir creates a directory in the VM.
+func (c *AgentClient) MakeDir(ctx context.Context, path string) error {
+ _, err := c.client.MakeDir(ctx, &pb.MakeDirRequest{Path: path})
+ return err
+}
+
+// Remove removes a file/directory in the VM.
+func (c *AgentClient) Remove(ctx context.Context, path string) error {
+ _, err := c.client.Remove(ctx, &pb.RemoveRequest{Path: path})
+ return err
+}
+
+// Exists checks if a path exists in the VM.
+func (c *AgentClient) Exists(ctx context.Context, path string) (bool, error) {
+ resp, err := c.client.Exists(ctx, &pb.ExistsRequest{Path: path})
+ if err != nil {
+ return false, err
+ }
+ return resp.Exists, nil
+}
+
+// Stat returns file metadata from the VM.
+func (c *AgentClient) Stat(ctx context.Context, path string) (*pb.StatResponse, error) {
+ return c.client.Stat(ctx, &pb.StatRequest{Path: path})
+}
+
+// Stats returns resource usage from the VM.
+func (c *AgentClient) Stats(ctx context.Context) (*pb.StatsResponse, error) {
+ return c.client.Stats(ctx, &pb.StatsRequest{})
+}
+
+// Shutdown gracefully stops the agent.
+func (c *AgentClient) Shutdown(ctx context.Context) error {
+ _, err := c.client.Shutdown(ctx, &pb.ShutdownRequest{})
+ return err
+}
+
+// SyncFS flushes all filesystem buffers inside the VM without exiting the agent.
+func (c *AgentClient) SyncFS(ctx context.Context) error {
+ _, err := c.client.SyncFS(ctx, &pb.SyncFSRequest{})
+ return err
+}
+
+// PTYCreate creates a new PTY session in the VM.
+func (c *AgentClient) PTYCreate(ctx context.Context, cols, rows int32, shell string) (sessionID string, dataPort uint32, err error) {
+ resp, err := c.client.PTYCreate(ctx, &pb.PTYCreateRequest{
+ Cols: cols,
+ Rows: rows,
+ Shell: shell,
+ })
+ if err != nil {
+ return "", 0, err
+ }
+ return resp.SessionId, resp.DataPort, nil
+}
+
+// PTYResize resizes a PTY session.
+func (c *AgentClient) PTYResize(ctx context.Context, sessionID string, cols, rows int32) error {
+ _, err := c.client.PTYResize(ctx, &pb.PTYResizeRequest{
+ SessionId: sessionID,
+ Cols: cols,
+ Rows: rows,
+ })
+ return err
+}
+
+// PTYKill terminates a PTY session.
+func (c *AgentClient) PTYKill(ctx context.Context, sessionID string) error {
+ _, err := c.client.PTYKill(ctx, &pb.PTYKillRequest{SessionId: sessionID})
+ return err
+}
+
+// ConnectPTYData connects to the PTY data stream on the given vsock port.
+// Returns a raw TCP-like connection for bidirectional PTY I/O.
+func (c *AgentClient) ConnectPTYData(vsockPath string, dataPort uint32) (net.Conn, error) {
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ conn, err := dialVsock(ctx, vsockPath, int(dataPort))
+ if err != nil {
+ return nil, fmt.Errorf("connect to PTY data port %d: %w", dataPort, err)
+ }
+ return conn, nil
+}
diff --git a/internal/firecracker/api.go b/internal/firecracker/api.go
new file mode 100644
index 00000000..80768666
--- /dev/null
+++ b/internal/firecracker/api.go
@@ -0,0 +1,182 @@
+package firecracker
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "os"
+ "time"
+)
+
+// FirecrackerClient is a minimal HTTP client for the Firecracker API socket.
+type FirecrackerClient struct {
+ socketPath string
+ httpClient *http.Client
+}
+
+// NewFirecrackerClient creates a client that talks to a Firecracker instance
+// via its Unix domain API socket.
+func NewFirecrackerClient(socketPath string) *FirecrackerClient {
+ transport := &http.Transport{
+ DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
+ d := net.Dialer{}
+ return d.DialContext(ctx, "unix", socketPath)
+ },
+ }
+ return &FirecrackerClient{
+ socketPath: socketPath,
+ httpClient: &http.Client{Transport: transport, Timeout: 30 * time.Second},
+ }
+}
+
+// WaitForSocket polls until the API socket file exists on disk.
+func (c *FirecrackerClient) WaitForSocket(timeout time.Duration) error {
+ deadline := time.Now().Add(timeout)
+ for time.Now().Before(deadline) {
+ if _, err := os.Stat(c.socketPath); err == nil {
+ return nil
+ }
+ time.Sleep(50 * time.Millisecond)
+ }
+ return fmt.Errorf("firecracker API socket %s not ready after %v", c.socketPath, timeout)
+}
+
+// PutBootSource configures the kernel boot source.
+func (c *FirecrackerClient) PutBootSource(kernelPath, bootArgs string) error {
+ body := map[string]string{
+ "kernel_image_path": kernelPath,
+ "boot_args": bootArgs,
+ }
+ return c.put("/boot-source", body)
+}
+
+// PutDrive attaches a block device (drive) to the VM.
+func (c *FirecrackerClient) PutDrive(driveID, pathOnHost string, isRootDevice, isReadOnly bool) error {
+ body := map[string]interface{}{
+ "drive_id": driveID,
+ "path_on_host": pathOnHost,
+ "is_root_device": isRootDevice,
+ "is_read_only": isReadOnly,
+ }
+ return c.putWithID("/drives", driveID, body)
+}
+
+// PutNetworkInterface attaches a network interface.
+func (c *FirecrackerClient) PutNetworkInterface(ifaceID, guestMAC, hostDevName string) error {
+ body := map[string]interface{}{
+ "iface_id": ifaceID,
+ "guest_mac": guestMAC,
+ "host_dev_name": hostDevName,
+ }
+ return c.putWithID("/network-interfaces", ifaceID, body)
+}
+
+// PutVsock configures the vsock device.
+func (c *FirecrackerClient) PutVsock(guestCID uint32, udsPath string) error {
+ body := map[string]interface{}{
+ "guest_cid": guestCID,
+ "uds_path": udsPath,
+ }
+ return c.put("/vsock", body)
+}
+
+// PutMachineConfig sets vCPU count and memory size.
+func (c *FirecrackerClient) PutMachineConfig(vcpuCount, memSizeMib int) error {
+ body := map[string]interface{}{
+ "vcpu_count": vcpuCount,
+ "mem_size_mib": memSizeMib,
+ }
+ return c.put("/machine-config", body)
+}
+
+// StartInstance boots the configured VM.
+func (c *FirecrackerClient) StartInstance() error {
+ body := map[string]string{
+ "action_type": "InstanceStart",
+ }
+ return c.put("/actions", body)
+}
+
+// PauseVM pauses a running VM.
+func (c *FirecrackerClient) PauseVM() error {
+ body := map[string]string{
+ "state": "Paused",
+ }
+ return c.patch("/vm", body)
+}
+
+// ResumeVM resumes a paused VM.
+func (c *FirecrackerClient) ResumeVM() error {
+ body := map[string]string{
+ "state": "Resumed",
+ }
+ return c.patch("/vm", body)
+}
+
+// CreateSnapshot creates a full VM snapshot (memory + device state).
+// The VM must be paused before calling this.
+func (c *FirecrackerClient) CreateSnapshot(snapshotPath, memFilePath string) error {
+ body := map[string]string{
+ "snapshot_type": "Full",
+ "snapshot_path": snapshotPath,
+ "mem_file_path": memFilePath,
+ }
+ return c.put("/snapshot/create", body)
+}
+
+// LoadSnapshot restores a VM from a snapshot.
+// If resumeVM is true, the VM starts running immediately after load.
+func (c *FirecrackerClient) LoadSnapshot(snapshotPath, memFilePath string, resumeVM bool) error {
+ body := map[string]interface{}{
+ "snapshot_path": snapshotPath,
+ "mem_backend": map[string]string{
+ "backend_path": memFilePath,
+ "backend_type": "File",
+ },
+ "enable_diff_snapshots": false,
+ "resume_vm": resumeVM,
+ }
+ return c.put("/snapshot/load", body)
+}
+
+func (c *FirecrackerClient) put(path string, body interface{}) error {
+ return c.doRequest(http.MethodPut, path, body)
+}
+
+func (c *FirecrackerClient) putWithID(basePath, id string, body interface{}) error {
+ return c.doRequest(http.MethodPut, basePath+"/"+id, body)
+}
+
+func (c *FirecrackerClient) patch(path string, body interface{}) error {
+ return c.doRequest(http.MethodPatch, path, body)
+}
+
+func (c *FirecrackerClient) doRequest(method, path string, body interface{}) error {
+ jsonBody, err := json.Marshal(body)
+ if err != nil {
+ return fmt.Errorf("marshal request body: %w", err)
+ }
+
+ req, err := http.NewRequest(method, "http://localhost"+path, bytes.NewReader(jsonBody))
+ if err != nil {
+ return fmt.Errorf("create request: %w", err)
+ }
+ req.Header.Set("Content-Type", "application/json")
+
+ resp, err := c.httpClient.Do(req)
+ if err != nil {
+ return fmt.Errorf("firecracker API %s %s: %w", method, path, err)
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode >= 300 {
+ respBody, _ := io.ReadAll(resp.Body)
+ return fmt.Errorf("firecracker API %s %s returned %d: %s", method, path, resp.StatusCode, string(respBody))
+ }
+
+ return nil
+}
diff --git a/internal/firecracker/manager.go b/internal/firecracker/manager.go
new file mode 100644
index 00000000..c9d4d20d
--- /dev/null
+++ b/internal/firecracker/manager.go
@@ -0,0 +1,741 @@
+// Package firecracker implements sandbox.Manager using Firecracker microVMs.
+// Each sandbox is a lightweight VM with its own kernel, rootfs, and workspace,
+// communicating with the host via gRPC over vsock.
+package firecracker
+
+import (
+ "context"
+ "fmt"
+ "log"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "sync"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/opensandbox/opensandbox/internal/sandbox"
+ "github.com/opensandbox/opensandbox/internal/storage"
+ "github.com/opensandbox/opensandbox/pkg/types"
+ pb "github.com/opensandbox/opensandbox/proto/agent"
+)
+
+// Compile-time check that Manager implements sandbox.Manager.
+var _ sandbox.Manager = (*Manager)(nil)
+
+// VMInstance holds the state of a running Firecracker microVM.
+type VMInstance struct {
+ ID string
+ Template string
+ Status types.SandboxStatus
+ StartedAt time.Time
+ EndAt time.Time
+ CpuCount int
+ MemoryMB int
+ HostPort int
+ GuestPort int
+
+ // VM internals
+ pid int // Firecracker VMM process PID
+ cmd *exec.Cmd // Firecracker process
+ network *NetworkConfig
+ vsockPath string // path to vsock UDS on host
+ sandboxDir string // /data/sandboxes/{id}/
+ agent *AgentClient // gRPC client to in-VM agent
+ apiSockPath string // path to Firecracker API socket
+ fcClient *FirecrackerClient // API client for this VM's Firecracker process
+ guestMAC string // e.g., "AA:FC:00:00:2d:31"
+ guestCID uint32 // vsock CID
+ bootArgs string // kernel boot args
+}
+
+// Config holds configuration for the Firecracker Manager.
+type Config struct {
+ DataDir string // base data directory (e.g., /data)
+ KernelPath string // path to vmlinux (e.g., /data/firecracker/vmlinux-arm64)
+ ImagesDir string // path to base rootfs images (e.g., /data/firecracker/images/)
+ FirecrackerBin string // path to firecracker binary (default: "firecracker")
+ DefaultMemoryMB int // default RAM per VM (default: 512)
+ DefaultCPUs int // default vCPUs per VM (default: 1)
+ DefaultDiskMB int // default workspace size in MB (default: 20480 = 20GB)
+ DefaultPort int // default guest port to expose (default: 80)
+}
+
+// Manager implements sandbox.Manager using Firecracker microVMs.
+type Manager struct {
+ cfg Config
+ subnets *SubnetAllocator
+
+ mu sync.RWMutex
+ vms map[string]*VMInstance
+ nextCID uint32 // next guest CID to assign (starts at 3, 0-2 are reserved)
+}
+
+// NewManager creates a new Firecracker-backed sandbox manager.
+func NewManager(cfg Config) (*Manager, error) {
+ if cfg.DataDir == "" {
+ return nil, fmt.Errorf("DataDir is required")
+ }
+ if cfg.KernelPath == "" {
+ cfg.KernelPath = filepath.Join(cfg.DataDir, "firecracker", "vmlinux-arm64")
+ }
+ if cfg.ImagesDir == "" {
+ cfg.ImagesDir = filepath.Join(cfg.DataDir, "firecracker", "images")
+ }
+ if cfg.FirecrackerBin == "" {
+ cfg.FirecrackerBin = "firecracker"
+ }
+ if cfg.DefaultMemoryMB == 0 {
+ cfg.DefaultMemoryMB = 512
+ }
+ if cfg.DefaultCPUs == 0 {
+ cfg.DefaultCPUs = 1
+ }
+ if cfg.DefaultDiskMB == 0 {
+ cfg.DefaultDiskMB = 20480 // 20GB
+ }
+ if cfg.DefaultPort == 0 {
+ cfg.DefaultPort = 80
+ }
+
+ // Verify kernel exists
+ if _, err := os.Stat(cfg.KernelPath); err != nil {
+ return nil, fmt.Errorf("kernel not found at %s: %w", cfg.KernelPath, err)
+ }
+
+ // Verify firecracker binary
+ if _, err := exec.LookPath(cfg.FirecrackerBin); err != nil {
+ return nil, fmt.Errorf("firecracker binary not found: %w", err)
+ }
+
+ // Enable IP forwarding for VM networking
+ if err := EnableForwarding(); err != nil {
+ log.Printf("firecracker: warning: could not enable IP forwarding: %v", err)
+ }
+
+ return &Manager{
+ cfg: cfg,
+ subnets: NewSubnetAllocator(),
+ vms: make(map[string]*VMInstance),
+ nextCID: 3, // CIDs 0-2 are reserved (hypervisor=0, local=1, host=2)
+ }, nil
+}
+
+// allocateCID returns a unique guest CID for a new VM.
+func (m *Manager) allocateCID() uint32 {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ cid := m.nextCID
+ m.nextCID++
+ return cid
+}
+
+// Create launches a new Firecracker microVM.
+func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (*types.Sandbox, error) {
+ 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)
+ }
+
+ // Resolve base image
+ template := cfg.Template
+ if template == "" {
+ template = "ubuntu"
+ }
+ baseImage, err := ResolveBaseImage(m.cfg.ImagesDir, template)
+ if err != nil {
+ os.RemoveAll(sandboxDir)
+ return nil, fmt.Errorf("resolve base image: %w", err)
+ }
+
+ // Prepare rootfs (reflink copy)
+ rootfsPath := filepath.Join(sandboxDir, "rootfs.ext4")
+ if err := PrepareRootfs(baseImage, rootfsPath); err != nil {
+ os.RemoveAll(sandboxDir)
+ return nil, fmt.Errorf("prepare rootfs: %w", err)
+ }
+
+ // Create workspace
+ diskMB := m.cfg.DefaultDiskMB
+ workspacePath := filepath.Join(sandboxDir, "workspace.ext4")
+ if err := CreateWorkspace(workspacePath, diskMB); err != nil {
+ os.RemoveAll(sandboxDir)
+ return nil, fmt.Errorf("create workspace: %w", err)
+ }
+
+ // Allocate network
+ netCfg, err := m.subnets.Allocate()
+ if err != nil {
+ os.RemoveAll(sandboxDir)
+ return nil, fmt.Errorf("allocate subnet: %w", err)
+ }
+
+ // Create TAP device
+ if err := CreateTAP(netCfg); err != nil {
+ m.subnets.Release(netCfg.TAPName)
+ os.RemoveAll(sandboxDir)
+ return nil, fmt.Errorf("create TAP: %w", err)
+ }
+
+ // Find free host port for port forwarding
+ 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
+
+ // Add DNAT rule
+ 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)
+ }
+
+ // Configure vCPU and memory
+ cpus := cfg.CpuCount
+ if cpus <= 0 {
+ cpus = m.cfg.DefaultCPUs
+ }
+ memMB := cfg.MemoryMB
+ if memMB <= 0 {
+ memMB = m.cfg.DefaultMemoryMB
+ }
+
+ // Vsock UDS path and unique CID
+ vsockPath := filepath.Join(sandboxDir, "vsock.sock")
+ guestCID := m.allocateCID()
+
+ // Build kernel boot args
+ // The init script in the rootfs reads these to configure networking
+ bootArgs := fmt.Sprintf(
+ "keep_bootcon console=ttyS0 reboot=k panic=1 pci=off "+
+ "ip=%s::%s:%s::eth0:off "+
+ "init=/sbin/init "+
+ "osb.gateway=%s",
+ netCfg.GuestIP, netCfg.HostIP, netCfg.Mask, netCfg.HostIP,
+ )
+
+ // Generate a deterministic MAC from the sandbox ID
+ guestMAC := generateMAC(id)
+
+ // Start Firecracker with API socket (enables snapshot support)
+ apiSockPath := filepath.Join(sandboxDir, "firecracker.sock")
+ os.Remove(apiSockPath) // clean stale socket
+
+ logPath := filepath.Join(sandboxDir, "firecracker.log")
+ logFile, err := os.Create(logPath)
+ if err != nil {
+ m.cleanupVM(netCfg, sandboxDir)
+ return nil, fmt.Errorf("create log file: %w", err)
+ }
+
+ cmd := exec.Command(m.cfg.FirecrackerBin, "--api-sock", apiSockPath)
+ cmd.Stdout = logFile
+ cmd.Stderr = logFile
+
+ if err := cmd.Start(); err != nil {
+ logFile.Close()
+ m.cleanupVM(netCfg, sandboxDir)
+ return nil, fmt.Errorf("start firecracker: %w", err)
+ }
+ logFile.Close()
+
+ // Configure VM via API socket
+ fcClient := NewFirecrackerClient(apiSockPath)
+ if err := fcClient.WaitForSocket(5 * time.Second); err != nil {
+ cmd.Process.Kill()
+ cmd.Wait()
+ m.cleanupVM(netCfg, sandboxDir)
+ return nil, fmt.Errorf("wait for API socket: %w", err)
+ }
+
+ if err := fcClient.PutMachineConfig(cpus, memMB); err != nil {
+ cmd.Process.Kill()
+ cmd.Wait()
+ m.cleanupVM(netCfg, sandboxDir)
+ return nil, fmt.Errorf("put machine config: %w", err)
+ }
+ if err := fcClient.PutBootSource(m.cfg.KernelPath, bootArgs); err != nil {
+ cmd.Process.Kill()
+ cmd.Wait()
+ m.cleanupVM(netCfg, sandboxDir)
+ return nil, fmt.Errorf("put boot source: %w", err)
+ }
+ if err := fcClient.PutDrive("rootfs", rootfsPath, true, false); err != nil {
+ cmd.Process.Kill()
+ cmd.Wait()
+ m.cleanupVM(netCfg, sandboxDir)
+ return nil, fmt.Errorf("put rootfs drive: %w", err)
+ }
+ if err := fcClient.PutDrive("workspace", workspacePath, false, false); err != nil {
+ cmd.Process.Kill()
+ cmd.Wait()
+ m.cleanupVM(netCfg, sandboxDir)
+ return nil, fmt.Errorf("put workspace drive: %w", err)
+ }
+ if err := fcClient.PutNetworkInterface("eth0", guestMAC, netCfg.TAPName); err != nil {
+ cmd.Process.Kill()
+ cmd.Wait()
+ m.cleanupVM(netCfg, sandboxDir)
+ return nil, fmt.Errorf("put network interface: %w", err)
+ }
+ if err := fcClient.PutVsock(guestCID, vsockPath); err != nil {
+ cmd.Process.Kill()
+ cmd.Wait()
+ m.cleanupVM(netCfg, sandboxDir)
+ return nil, fmt.Errorf("put vsock: %w", err)
+ }
+ if err := fcClient.StartInstance(); err != nil {
+ cmd.Process.Kill()
+ cmd.Wait()
+ m.cleanupVM(netCfg, sandboxDir)
+ return nil, fmt.Errorf("start instance: %w", err)
+ }
+
+ now := time.Now()
+ timeout := time.Duration(cfg.Timeout) * time.Second
+ if timeout <= 0 {
+ timeout = 300 * time.Second
+ }
+
+ vm := &VMInstance{
+ ID: id,
+ Template: template,
+ Status: types.SandboxStatusRunning,
+ StartedAt: now,
+ EndAt: now.Add(timeout),
+ CpuCount: cpus,
+ MemoryMB: memMB,
+ HostPort: hostPort,
+ GuestPort: guestPort,
+ pid: cmd.Process.Pid,
+ cmd: cmd,
+ network: netCfg,
+ vsockPath: vsockPath,
+ sandboxDir: sandboxDir,
+ apiSockPath: apiSockPath,
+ fcClient: fcClient,
+ guestMAC: guestMAC,
+ guestCID: guestCID,
+ bootArgs: bootArgs,
+ }
+
+ // Wait for agent to become available (use background context so gRPC deadline doesn't kill us)
+ agentClient, err := m.waitForAgent(context.Background(), vsockPath, 30*time.Second)
+ if err != nil {
+ log.Printf("firecracker: agent not ready for %s, killing VM: %v", id, err)
+ cmd.Process.Kill()
+ cmd.Wait()
+ m.cleanupVM(netCfg, sandboxDir)
+ return nil, fmt.Errorf("agent not ready: %w", err)
+ }
+ vm.agent = agentClient
+
+ // Register VM
+ m.mu.Lock()
+ m.vms[id] = vm
+ m.mu.Unlock()
+
+ log.Printf("firecracker: created VM %s (template=%s, cpu=%d, mem=%dMB, port=%d→%d, tap=%s, mac=%s)",
+ id, template, cpus, memMB, hostPort, guestPort, netCfg.TAPName, guestMAC)
+
+ return &types.Sandbox{
+ ID: id,
+ Template: template,
+ Status: types.SandboxStatusRunning,
+ StartedAt: now,
+ EndAt: now.Add(timeout),
+ CpuCount: cpus,
+ MemoryMB: memMB,
+ HostPort: hostPort,
+ }, nil
+}
+
+// waitForAgent polls the agent via gRPC until it responds or times out.
+func (m *Manager) waitForAgent(ctx context.Context, vsockPath string, timeout time.Duration) (*AgentClient, error) {
+ deadline := time.Now().Add(timeout)
+ var lastErr error
+
+ for time.Now().Before(deadline) {
+ client, err := NewAgentClient(vsockPath)
+ if err != nil {
+ lastErr = err
+ time.Sleep(200 * 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(200 * time.Millisecond)
+ continue
+ }
+
+ return client, nil
+ }
+
+ return nil, fmt.Errorf("agent not ready after %v: %v", timeout, lastErr)
+}
+
+// Get returns sandbox info by ID.
+func (m *Manager) Get(ctx context.Context, id string) (*types.Sandbox, error) {
+ m.mu.RLock()
+ vm, ok := m.vms[id]
+ m.mu.RUnlock()
+ if !ok {
+ return nil, fmt.Errorf("sandbox %s not found", id)
+ }
+
+ return vmToSandbox(vm), nil
+}
+
+// Kill stops a VM and cleans up all resources.
+func (m *Manager) Kill(ctx context.Context, id string) error {
+ m.mu.Lock()
+ vm, ok := m.vms[id]
+ if ok {
+ delete(m.vms, id)
+ }
+ m.mu.Unlock()
+ if !ok {
+ return fmt.Errorf("sandbox %s not found", id)
+ }
+
+ return m.destroyVM(vm)
+}
+
+// destroyVM stops a VM and cleans up all resources.
+func (m *Manager) destroyVM(vm *VMInstance) error {
+ // Try graceful shutdown via agent
+ if vm.agent != nil {
+ shutCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
+ _ = vm.agent.Shutdown(shutCtx)
+ cancel()
+ vm.agent.Close()
+ }
+
+ // Kill Firecracker process
+ if vm.cmd != nil && vm.cmd.Process != nil {
+ vm.cmd.Process.Kill()
+ vm.cmd.Wait()
+ }
+
+ // Clean up network
+ if vm.network != nil {
+ RemoveDNAT(vm.network)
+ DeleteTAP(vm.network.TAPName)
+ m.subnets.Release(vm.network.TAPName)
+ }
+
+ // Clean up API socket
+ if vm.apiSockPath != "" {
+ os.Remove(vm.apiSockPath)
+ }
+
+ // Remove sandbox directory
+ if vm.sandboxDir != "" {
+ os.RemoveAll(vm.sandboxDir)
+ }
+
+ log.Printf("firecracker: destroyed VM %s", vm.ID)
+ return nil
+}
+
+// cleanupVM cleans up resources on failed creation.
+func (m *Manager) cleanupVM(netCfg *NetworkConfig, sandboxDir string) {
+ if netCfg != nil {
+ RemoveDNAT(netCfg)
+ DeleteTAP(netCfg.TAPName)
+ m.subnets.Release(netCfg.TAPName)
+ }
+ if sandboxDir != "" {
+ os.RemoveAll(sandboxDir)
+ }
+}
+
+// List returns all running VMs.
+func (m *Manager) List(ctx context.Context) ([]types.Sandbox, error) {
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+
+ result := make([]types.Sandbox, 0, len(m.vms))
+ for _, vm := range m.vms {
+ result = append(result, *vmToSandbox(vm))
+ }
+ return result, nil
+}
+
+// Count returns the number of running VMs.
+func (m *Manager) Count(ctx context.Context) (int, error) {
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+ return len(m.vms), nil
+}
+
+// Close stops all VMs and cleans up.
+func (m *Manager) Close() {
+ m.mu.Lock()
+ vms := make([]*VMInstance, 0, len(m.vms))
+ for _, vm := range m.vms {
+ vms = append(vms, vm)
+ }
+ m.vms = make(map[string]*VMInstance)
+ m.mu.Unlock()
+
+ for _, vm := range vms {
+ m.destroyVM(vm)
+ }
+ log.Printf("firecracker: manager closed, %d VMs destroyed", len(vms))
+}
+
+// Exec runs a command in the VM via the agent.
+func (m *Manager) Exec(ctx context.Context, sandboxID string, cfg types.ProcessConfig) (*types.ProcessResult, error) {
+ vm, err := m.getVM(sandboxID)
+ if err != nil {
+ return nil, err
+ }
+
+ timeout := int32(cfg.Timeout)
+ if timeout <= 0 {
+ timeout = 60
+ }
+
+ // If no explicit args, wrap in shell for pipe/redirect/&&/|| support
+ command := cfg.Command
+ args := cfg.Args
+ if len(args) == 0 {
+ args = []string{"-c", command}
+ command = "/bin/sh"
+ }
+
+ resp, err := vm.agent.Exec(ctx, &pb.ExecRequest{
+ Command: command,
+ Args: args,
+ Envs: cfg.Env,
+ Cwd: cfg.Cwd,
+ TimeoutSeconds: timeout,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("exec in %s: %w", sandboxID, err)
+ }
+
+ return &types.ProcessResult{
+ ExitCode: int(resp.ExitCode),
+ Stdout: resp.Stdout,
+ Stderr: resp.Stderr,
+ }, nil
+}
+
+// ReadFile reads a file from the VM.
+func (m *Manager) ReadFile(ctx context.Context, sandboxID, path string) (string, error) {
+ vm, err := m.getVM(sandboxID)
+ if err != nil {
+ return "", err
+ }
+ data, err := vm.agent.ReadFile(ctx, path)
+ if err != nil {
+ return "", err
+ }
+ return string(data), nil
+}
+
+// WriteFile writes a file in the VM.
+func (m *Manager) WriteFile(ctx context.Context, sandboxID, path, content string) error {
+ vm, err := m.getVM(sandboxID)
+ if err != nil {
+ return err
+ }
+ return vm.agent.WriteFile(ctx, path, []byte(content))
+}
+
+// ListDir lists a directory in the VM.
+func (m *Manager) ListDir(ctx context.Context, sandboxID, path string) ([]types.EntryInfo, error) {
+ vm, err := m.getVM(sandboxID)
+ if err != nil {
+ return nil, err
+ }
+ entries, err := vm.agent.ListDir(ctx, path)
+ if err != nil {
+ return nil, err
+ }
+ result := make([]types.EntryInfo, len(entries))
+ for i, e := range entries {
+ result[i] = types.EntryInfo{
+ Name: e.Name,
+ IsDir: e.IsDir,
+ Size: e.Size,
+ Path: e.Path,
+ }
+ }
+ return result, nil
+}
+
+// MakeDir creates a directory in the VM.
+func (m *Manager) MakeDir(ctx context.Context, sandboxID, path string) error {
+ vm, err := m.getVM(sandboxID)
+ if err != nil {
+ return err
+ }
+ return vm.agent.MakeDir(ctx, path)
+}
+
+// Remove removes a file/directory in the VM.
+func (m *Manager) Remove(ctx context.Context, sandboxID, path string) error {
+ vm, err := m.getVM(sandboxID)
+ if err != nil {
+ return err
+ }
+ return vm.agent.Remove(ctx, path)
+}
+
+// Exists checks if a path exists in the VM.
+func (m *Manager) Exists(ctx context.Context, sandboxID, path string) (bool, error) {
+ vm, err := m.getVM(sandboxID)
+ if err != nil {
+ return false, err
+ }
+ return vm.agent.Exists(ctx, path)
+}
+
+// Stat returns file metadata from the VM.
+func (m *Manager) Stat(ctx context.Context, sandboxID, path string) (*types.FileInfo, error) {
+ vm, err := m.getVM(sandboxID)
+ if err != nil {
+ return nil, err
+ }
+ resp, err := vm.agent.Stat(ctx, path)
+ if err != nil {
+ return nil, err
+ }
+ return &types.FileInfo{
+ Name: resp.Name,
+ IsDir: resp.IsDir,
+ Size: resp.Size,
+ Mode: resp.Mode,
+ ModTime: resp.ModTime,
+ Path: resp.Path,
+ }, nil
+}
+
+// Stats returns live resource usage from the VM.
+func (m *Manager) Stats(ctx context.Context, sandboxID string) (*sandbox.SandboxStats, error) {
+ vm, err := m.getVM(sandboxID)
+ if err != nil {
+ return nil, err
+ }
+ resp, err := vm.agent.Stats(ctx)
+ if err != nil {
+ return nil, err
+ }
+ return &sandbox.SandboxStats{
+ CPUPercent: resp.CpuPercent,
+ MemUsage: resp.MemUsage,
+ MemLimit: resp.MemLimit,
+ NetInput: resp.NetInput,
+ NetOutput: resp.NetOutput,
+ PIDs: int(resp.Pids),
+ }, nil
+}
+
+// HostPort returns the mapped host port for a sandbox.
+func (m *Manager) HostPort(ctx context.Context, sandboxID string) (int, error) {
+ vm, err := m.getVM(sandboxID)
+ if err != nil {
+ return 0, err
+ }
+ return vm.HostPort, nil
+}
+
+// DataDir returns the base data directory.
+func (m *Manager) DataDir() string {
+ return m.cfg.DataDir
+}
+
+// ContainerName returns a human-readable name for the sandbox (for logging).
+func (m *Manager) ContainerName(id string) string {
+ return "fc-" + id
+}
+
+// Hibernate snapshots a VM and uploads to S3.
+func (m *Manager) Hibernate(ctx context.Context, sandboxID string, checkpointStore *storage.CheckpointStore) (*sandbox.HibernateResult, error) {
+ vm, err := m.getVM(sandboxID)
+ if err != nil {
+ return nil, err
+ }
+ return m.doHibernate(ctx, vm, checkpointStore)
+}
+
+// Wake restores a VM from a snapshot.
+func (m *Manager) Wake(ctx context.Context, sandboxID string, checkpointKey string, checkpointStore *storage.CheckpointStore, timeout int) (*types.Sandbox, error) {
+ return m.doWake(ctx, sandboxID, checkpointKey, checkpointStore, timeout)
+}
+
+// getVM retrieves a VM by ID (read-locked).
+func (m *Manager) getVM(id string) (*VMInstance, error) {
+ m.mu.RLock()
+ vm, ok := m.vms[id]
+ m.mu.RUnlock()
+ if !ok {
+ return nil, fmt.Errorf("sandbox %s not found", id)
+ }
+ return vm, nil
+}
+
+// vmToSandbox converts a VMInstance to a types.Sandbox.
+func vmToSandbox(vm *VMInstance) *types.Sandbox {
+ return &types.Sandbox{
+ ID: vm.ID,
+ Template: vm.Template,
+ Status: vm.Status,
+ StartedAt: vm.StartedAt,
+ EndAt: vm.EndAt,
+ CpuCount: vm.CpuCount,
+ MemoryMB: vm.MemoryMB,
+ HostPort: vm.HostPort,
+ }
+}
+
+// generateMAC creates a deterministic MAC address from a sandbox ID.
+// Format: AA:FC:00:00:XX:XX where XX:XX are derived from the ID.
+func generateMAC(id string) string {
+ var b4, b5 byte
+ if len(id) > 3 {
+ b4 = id[3]
+ }
+ if len(id) > 0 {
+ b5 = id[len(id)-1]
+ }
+ return fmt.Sprintf("AA:FC:00:00:%02x:%02x", b4, b5)
+}
+
+// GetVsockPath returns the vsock UDS path for a sandbox (used by PTY manager).
+func (m *Manager) GetVsockPath(sandboxID string) (string, error) {
+ vm, err := m.getVM(sandboxID)
+ if err != nil {
+ return "", err
+ }
+ return vm.vsockPath, nil
+}
+
+// GetAgent returns the agent client for a sandbox (used by PTY manager).
+func (m *Manager) GetAgent(sandboxID string) (*AgentClient, error) {
+ vm, err := m.getVM(sandboxID)
+ if err != nil {
+ return nil, err
+ }
+ return vm.agent, nil
+}
diff --git a/internal/firecracker/network.go b/internal/firecracker/network.go
new file mode 100644
index 00000000..5b417006
--- /dev/null
+++ b/internal/firecracker/network.go
@@ -0,0 +1,269 @@
+package firecracker
+
+import (
+ "fmt"
+ "net"
+ "os/exec"
+ "strings"
+ "sync"
+)
+
+// NetworkConfig holds the networking state for a single VM.
+type NetworkConfig struct {
+ TAPName string // e.g., "tap0"
+ HostIP string // e.g., "172.16.0.1"
+ GuestIP string // e.g., "172.16.0.2"
+ Mask string // e.g., "255.255.255.252"
+ CIDR int // /30
+
+ // Port forwarding
+ HostPort int // host port mapped to guest
+ GuestPort int // guest port (typically 80)
+ DNATRuleAdded bool
+}
+
+// SubnetAllocator manages /30 subnet allocation from a 172.16.0.0/16 pool.
+// Each VM gets a /30: host IP (.1) and guest IP (.2), with .0 as network and .3 as broadcast.
+type SubnetAllocator struct {
+ mu sync.Mutex
+ next uint32 // next /30 block index (0, 1, 2, ...)
+ used map[uint32]bool
+}
+
+// NewSubnetAllocator creates a new subnet allocator.
+func NewSubnetAllocator() *SubnetAllocator {
+ return &SubnetAllocator{
+ used: make(map[uint32]bool),
+ }
+}
+
+// Allocate returns a new /30 subnet for a VM.
+// Returns tapName, hostIP, guestIP, mask.
+func (a *SubnetAllocator) Allocate() (*NetworkConfig, error) {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+
+ // Find next free /30 block
+ block := a.next
+ for a.used[block] {
+ block++
+ if block > 16383 { // 172.16.0.0/16 has 16384 /30 blocks
+ return nil, fmt.Errorf("subnet pool exhausted")
+ }
+ }
+ a.used[block] = true
+ a.next = block + 1
+
+ // Calculate IPs: 172.16.{high}.{low*4}
+ // Each /30 block is 4 IPs: base+0 (network), base+1 (host), base+2 (guest), base+3 (broadcast)
+ base := block * 4
+ b2 := byte(base >> 8) // second octet offset
+ b3 := byte(base & 0xFF) // third octet base
+
+ // base+0 is network address, base+1 is host, base+2 is guest, base+3 is broadcast
+ hostIP := fmt.Sprintf("172.16.%d.%d", b2, b3+1)
+ guestIP := fmt.Sprintf("172.16.%d.%d", b2, b3+2)
+
+ tapName := fmt.Sprintf("fc-tap%d", block)
+
+ return &NetworkConfig{
+ TAPName: tapName,
+ HostIP: hostIP,
+ GuestIP: guestIP,
+ Mask: "255.255.255.252",
+ CIDR: 30,
+ }, nil
+}
+
+// AllocateSpecific reserves a specific TAP name/subnet block.
+// Used during snapshot restore where the TAP name is baked into the vmstate.
+func (a *SubnetAllocator) AllocateSpecific(tapName string) (*NetworkConfig, error) {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+
+ var block uint32
+ if _, err := fmt.Sscanf(tapName, "fc-tap%d", &block); err != nil {
+ return nil, fmt.Errorf("parse tap name %q: %w", tapName, err)
+ }
+ if a.used[block] {
+ return nil, fmt.Errorf("tap %s already in use", tapName)
+ }
+ a.used[block] = true
+
+ // Calculate IPs using same math as Allocate()
+ base := block * 4
+ b2 := byte(base >> 8)
+ b3 := byte(base & 0xFF)
+
+ return &NetworkConfig{
+ TAPName: tapName,
+ HostIP: fmt.Sprintf("172.16.%d.%d", b2, b3+1),
+ GuestIP: fmt.Sprintf("172.16.%d.%d", b2, b3+2),
+ Mask: "255.255.255.252",
+ CIDR: 30,
+ }, nil
+}
+
+// Release returns a /30 block to the pool.
+func (a *SubnetAllocator) Release(tapName string) {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+
+ // Extract block number from tap name
+ var block uint32
+ if _, err := fmt.Sscanf(tapName, "fc-tap%d", &block); err != nil {
+ return
+ }
+ delete(a.used, block)
+}
+
+// CreateTAP creates a TAP device and configures it with the host IP.
+func CreateTAP(cfg *NetworkConfig) error {
+ // Create TAP device
+ if err := run("ip", "tuntap", "add", "dev", cfg.TAPName, "mode", "tap"); err != nil {
+ return fmt.Errorf("create tap %s: %w", cfg.TAPName, err)
+ }
+
+ // Assign host IP
+ addr := fmt.Sprintf("%s/%d", cfg.HostIP, cfg.CIDR)
+ if err := run("ip", "addr", "add", addr, "dev", cfg.TAPName); err != nil {
+ DeleteTAP(cfg.TAPName)
+ return fmt.Errorf("assign ip to %s: %w", cfg.TAPName, err)
+ }
+
+ // Bring up
+ if err := run("ip", "link", "set", cfg.TAPName, "up"); err != nil {
+ DeleteTAP(cfg.TAPName)
+ return fmt.Errorf("bring up %s: %w", cfg.TAPName, err)
+ }
+
+ return nil
+}
+
+// DeleteTAP removes a TAP device.
+func DeleteTAP(tapName string) {
+ _ = run("ip", "link", "del", tapName)
+}
+
+// AddDNAT adds an iptables DNAT rule: hostPort → guestIP:guestPort.
+func AddDNAT(cfg *NetworkConfig) error {
+ if cfg.HostPort == 0 || cfg.GuestPort == 0 {
+ return nil
+ }
+ err := run("iptables", "-t", "nat", "-A", "PREROUTING",
+ "-p", "tcp", "--dport", fmt.Sprintf("%d", cfg.HostPort),
+ "-j", "DNAT", "--to-destination",
+ fmt.Sprintf("%s:%d", cfg.GuestIP, cfg.GuestPort))
+ if err != nil {
+ return fmt.Errorf("add DNAT: %w", err)
+ }
+
+ // Also add for locally-generated traffic (connections from the host itself)
+ err = run("iptables", "-t", "nat", "-A", "OUTPUT",
+ "-p", "tcp", "--dport", fmt.Sprintf("%d", cfg.HostPort),
+ "-j", "DNAT", "--to-destination",
+ fmt.Sprintf("%s:%d", cfg.GuestIP, cfg.GuestPort))
+ if err != nil {
+ // Non-fatal — PREROUTING is the important one
+ return nil
+ }
+
+ cfg.DNATRuleAdded = true
+ return nil
+}
+
+// RemoveDNAT removes the iptables DNAT rules.
+func RemoveDNAT(cfg *NetworkConfig) {
+ if !cfg.DNATRuleAdded {
+ return
+ }
+ _ = run("iptables", "-t", "nat", "-D", "PREROUTING",
+ "-p", "tcp", "--dport", fmt.Sprintf("%d", cfg.HostPort),
+ "-j", "DNAT", "--to-destination",
+ fmt.Sprintf("%s:%d", cfg.GuestIP, cfg.GuestPort))
+ _ = run("iptables", "-t", "nat", "-D", "OUTPUT",
+ "-p", "tcp", "--dport", fmt.Sprintf("%d", cfg.HostPort),
+ "-j", "DNAT", "--to-destination",
+ fmt.Sprintf("%s:%d", cfg.GuestIP, cfg.GuestPort))
+}
+
+// EnableForwarding enables IPv4 forwarding and masquerading for the VM subnet.
+// Call once at startup.
+func EnableForwarding() error {
+ // Enable IP forwarding
+ if err := run("sysctl", "-w", "net.ipv4.ip_forward=1"); err != nil {
+ return fmt.Errorf("enable ip_forward: %w", err)
+ }
+
+ // Allow routing packets with 127.0.0.0/8 source through non-loopback interfaces.
+ // Required for DNAT from localhost:PORT → guest VM IP to work.
+ if err := run("sysctl", "-w", "net.ipv4.conf.all.route_localnet=1"); err != nil {
+ return fmt.Errorf("enable route_localnet: %w", err)
+ }
+
+ // Add masquerade rule for VM subnet (idempotent — check if exists first)
+ out, _ := exec.Command("iptables", "-t", "nat", "-S", "POSTROUTING").CombinedOutput()
+ outRules := string(out)
+ if !strings.Contains(outRules, "172.16.0.0/16") {
+ // Detect the default outgoing interface
+ outIface := detectDefaultInterface()
+ if outIface != "" {
+ _ = run("iptables", "-t", "nat", "-A", "POSTROUTING",
+ "-s", "172.16.0.0/16", "-o", outIface,
+ "-j", "MASQUERADE")
+ } else {
+ // Fallback: masquerade on all interfaces except TAPs
+ _ = run("iptables", "-t", "nat", "-A", "POSTROUTING",
+ "-s", "172.16.0.0/16", "!", "-o", "fc-tap+",
+ "-j", "MASQUERADE")
+ }
+ }
+
+ // Masquerade for DNAT'd traffic from the host to VMs (e.g. localhost:PORT → guest:80).
+ // Without this, packets arrive at the guest with src=127.0.0.1, and replies go nowhere.
+ // This rewrites src to the host's TAP IP so the guest replies back through the TAP.
+ if !strings.Contains(outRules, "172.16.0.0/16 -j MASQUERADE") {
+ _ = run("iptables", "-t", "nat", "-A", "POSTROUTING",
+ "-d", "172.16.0.0/16",
+ "-j", "MASQUERADE")
+ }
+
+ return nil
+}
+
+// detectDefaultInterface returns the name of the default outgoing network interface.
+func detectDefaultInterface() string {
+ out, err := exec.Command("ip", "route", "show", "default").CombinedOutput()
+ if err != nil {
+ return ""
+ }
+ // Parse "default via X.X.X.X dev <iface> ..."
+ fields := strings.Fields(string(out))
+ for i, f := range fields {
+ if f == "dev" && i+1 < len(fields) {
+ return fields[i+1]
+ }
+ }
+ return ""
+}
+
+// FindFreePort finds a free TCP port on the host.
+func FindFreePort() (int, error) {
+ lis, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ return 0, err
+ }
+ port := lis.Addr().(*net.TCPAddr).Port
+ lis.Close()
+ return port, nil
+}
+
+// run executes a command and returns an error with stderr if it fails.
+func run(name string, args ...string) error {
+ cmd := exec.Command(name, args...)
+ out, err := cmd.CombinedOutput()
+ if err != nil {
+ return fmt.Errorf("%s %s: %w (%s)", name, strings.Join(args, " "), err, strings.TrimSpace(string(out)))
+ }
+ return nil
+}
diff --git a/internal/firecracker/rootfs.go b/internal/firecracker/rootfs.go
new file mode 100644
index 00000000..89f3f9ac
--- /dev/null
+++ b/internal/firecracker/rootfs.go
@@ -0,0 +1,87 @@
+package firecracker
+
+import (
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+)
+
+// RootfsConfig holds paths for VM filesystem images.
+type RootfsConfig struct {
+ ImagesDir string // directory containing base rootfs images (e.g., /data/firecracker/images/)
+}
+
+// PrepareRootfs copies a base rootfs image to the sandbox directory.
+// Uses reflink (--reflink=auto) on XFS/btrfs for instant copy-on-write.
+func PrepareRootfs(baseImage, destPath string) error {
+ // Ensure parent directory exists
+ if err := os.MkdirAll(filepath.Dir(destPath), 0755); err != nil {
+ return fmt.Errorf("mkdir for rootfs: %w", err)
+ }
+
+ // Try reflink copy first (instant on XFS with reflink support)
+ cmd := exec.Command("cp", "--reflink=auto", baseImage, destPath)
+ if out, err := cmd.CombinedOutput(); err != nil {
+ return fmt.Errorf("copy rootfs: %w (%s)", err, strings.TrimSpace(string(out)))
+ }
+
+ return nil
+}
+
+// CreateWorkspace creates a sparse ext4 filesystem for the sandbox workspace.
+// The file is sparse — it only uses disk space as data is written.
+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)
+ }
+
+ // Create sparse file
+ f, err := os.Create(path)
+ if err != nil {
+ return fmt.Errorf("create workspace file: %w", err)
+ }
+ // Truncate to desired size (sparse — no disk used yet)
+ if err := f.Truncate(int64(sizeMB) * 1024 * 1024); err != nil {
+ f.Close()
+ os.Remove(path)
+ return fmt.Errorf("truncate workspace: %w", err)
+ }
+ f.Close()
+
+ // Format as ext4
+ cmd := exec.Command("mkfs.ext4", "-q", "-F",
+ "-L", "workspace",
+ "-O", "^has_journal", // no journal for performance (we have S3 as source of truth)
+ path)
+ if out, err := cmd.CombinedOutput(); err != nil {
+ os.Remove(path)
+ return fmt.Errorf("mkfs.ext4: %w (%s)", err, strings.TrimSpace(string(out)))
+ }
+
+ return nil
+}
+
+// ResolveBaseImage finds the base rootfs image for a given template.
+// Templates map to image files: "ubuntu" → "ubuntu-base.ext4"
+func ResolveBaseImage(imagesDir, template string) (string, error) {
+ if template == "" {
+ template = "ubuntu"
+ }
+
+ // Check for exact match first
+ candidates := []string{
+ filepath.Join(imagesDir, template+".ext4"),
+ filepath.Join(imagesDir, template+"-base.ext4"),
+ filepath.Join(imagesDir, template),
+ }
+
+ for _, path := range candidates {
+ if _, err := os.Stat(path); err == nil {
+ return path, nil
+ }
+ }
+
+ return "", fmt.Errorf("base image not found for template %q in %s", template, imagesDir)
+}
diff --git a/internal/firecracker/snapshot.go b/internal/firecracker/snapshot.go
new file mode 100644
index 00000000..c4d5ef88
--- /dev/null
+++ b/internal/firecracker/snapshot.go
@@ -0,0 +1,511 @@
+package firecracker
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "log"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "github.com/opensandbox/opensandbox/internal/sandbox"
+ "github.com/opensandbox/opensandbox/internal/storage"
+ "github.com/opensandbox/opensandbox/pkg/types"
+)
+
+// SnapshotMeta holds metadata persisted alongside snapshot files.
+// This is needed to restore the exact same VM configuration on wake.
+type SnapshotMeta struct {
+ SandboxID string `json:"sandboxId"`
+ Network *NetworkConfig `json:"network"`
+ GuestCID uint32 `json:"guestCID"`
+ GuestMAC string `json:"guestMAC"`
+ BootArgs string `json:"bootArgs"`
+ RootfsPath string `json:"rootfsPath"`
+ WorkspacePath string `json:"workspacePath"`
+ VsockPath string `json:"vsockPath"`
+ CpuCount int `json:"cpuCount"`
+ MemoryMB int `json:"memoryMB"`
+ Template string `json:"template"`
+ GuestPort int `json:"guestPort"`
+}
+
+// doHibernate pauses a running VM, creates a full memory snapshot, and kicks off
+// an async S3 upload. Drives (rootfs + workspace) stay on local disk for fast
+// same-machine wake. Only mem + vmstate + metadata are archived and uploaded.
+//
+// The API returns as soon as the local snapshot is written — the S3 upload
+// happens in the background so hibernate latency is sub-second for the caller.
+//
+// Flow:
+// 1. SyncFS via agent (flush disk buffers — agent stays alive)
+// 2. Close gRPC connection (vsock must be inactive for snapshot)
+// 3. Pause VM via Firecracker API socket
+// 4. Create snapshot (mem_file + vmstate_file)
+// 5. Kill the paused Firecracker process
+// 6. Write snapshot-meta.json
+// 7. Clean up network
+// 8. (async) Archive snapshot files → tar.zst, upload to S3
+func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointStore *storage.CheckpointStore) (*sandbox.HibernateResult, error) {
+ t0 := time.Now()
+
+ snapshotDir := filepath.Join(vm.sandboxDir, "snapshot")
+ if err := os.MkdirAll(snapshotDir, 0755); err != nil {
+ return nil, fmt.Errorf("mkdir snapshot dir: %w", err)
+ }
+
+ memFile := filepath.Join(snapshotDir, "mem")
+ vmstateFile := filepath.Join(snapshotDir, "vmstate")
+
+ // Step 1: Sync filesystems inside the VM (agent stays alive for snapshot)
+ if vm.agent != nil {
+ syncCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
+ err := vm.agent.SyncFS(syncCtx)
+ cancel()
+ if err != nil {
+ log.Printf("firecracker: SyncFS warning for %s: %v", vm.ID, err)
+ }
+ }
+ log.Printf("firecracker: hibernate %s: syncfs done (%dms)", vm.ID, time.Since(t0).Milliseconds())
+
+ // Step 2: Close gRPC connection — vsock must be inactive before snapshot
+ if vm.agent != nil {
+ vm.agent.Close()
+ vm.agent = nil
+ }
+
+ // Step 3: Pause the VM
+ if vm.fcClient == nil {
+ return nil, fmt.Errorf("no API client for VM %s (not in API mode)", vm.ID)
+ }
+ if err := vm.fcClient.PauseVM(); err != nil {
+ return nil, fmt.Errorf("pause VM: %w", err)
+ }
+ log.Printf("firecracker: hibernate %s: paused (%dms)", vm.ID, time.Since(t0).Milliseconds())
+
+ // Step 4: Create memory snapshot
+ if err := vm.fcClient.CreateSnapshot(vmstateFile, memFile); err != nil {
+ return nil, fmt.Errorf("create snapshot: %w", err)
+ }
+ log.Printf("firecracker: hibernate %s: snapshot created (%dms)", vm.ID, time.Since(t0).Milliseconds())
+
+ // Step 5: Kill the paused Firecracker process
+ if vm.cmd != nil && vm.cmd.Process != nil {
+ vm.cmd.Process.Kill()
+ vm.cmd.Wait()
+ }
+
+ // Step 6: Write snapshot metadata
+ meta := &SnapshotMeta{
+ SandboxID: vm.ID,
+ Network: vm.network,
+ GuestCID: vm.guestCID,
+ GuestMAC: vm.guestMAC,
+ BootArgs: vm.bootArgs,
+ RootfsPath: filepath.Join(vm.sandboxDir, "rootfs.ext4"),
+ WorkspacePath: filepath.Join(vm.sandboxDir, "workspace.ext4"),
+ VsockPath: vm.vsockPath,
+ CpuCount: vm.CpuCount,
+ MemoryMB: vm.MemoryMB,
+ Template: vm.Template,
+ GuestPort: vm.GuestPort,
+ }
+ metaJSON, err := json.Marshal(meta)
+ if err != nil {
+ return nil, fmt.Errorf("marshal snapshot meta: %w", err)
+ }
+ metaPath := filepath.Join(snapshotDir, "snapshot-meta.json")
+ if err := os.WriteFile(metaPath, metaJSON, 0644); err != nil {
+ return nil, fmt.Errorf("write snapshot meta: %w", err)
+ }
+
+ // Step 7: Clean up network (keep snapshot files on disk for local wake)
+ if vm.network != nil {
+ RemoveDNAT(vm.network)
+ DeleteTAP(vm.network.TAPName)
+ m.subnets.Release(vm.network.TAPName)
+ }
+
+ // Clean up sockets — the vsock UDS must be removed so snapshot restore
+ // can re-bind to the same path without "Address in use" errors.
+ if vm.apiSockPath != "" {
+ os.Remove(vm.apiSockPath)
+ }
+ if vm.vsockPath != "" {
+ os.Remove(vm.vsockPath)
+ }
+
+ checkpointKey := fmt.Sprintf("checkpoints/%s/%d.tar.zst", vm.ID, time.Now().Unix())
+ localElapsed := time.Since(t0)
+ log.Printf("firecracker: hibernate %s: local snapshot complete (%dms), starting async S3 upload",
+ vm.ID, localElapsed.Milliseconds())
+
+ // Step 8: Archive + upload to S3 in the background.
+ // The archive includes mem + vmstate + metadata + workspace drive so that
+ // the sandbox can be restored on ANY worker (cross-worker migration).
+ // The rootfs is NOT archived — it's recreated from the template on wake.
+ sandboxDir := vm.sandboxDir
+ sandboxID := vm.ID
+ go func() {
+ t1 := time.Now()
+ archivePath := filepath.Join(sandboxDir, "checkpoint.tar.zst")
+
+ // Archive snapshot files + workspace drive.
+ // Use sandboxDir as base so workspace.ext4 is at the right relative path.
+ if err := createArchive(archivePath, sandboxDir, []string{
+ "snapshot/mem",
+ "snapshot/vmstate",
+ "snapshot/snapshot-meta.json",
+ "workspace.ext4",
+ }); err != nil {
+ log.Printf("firecracker: async archive failed for %s: %v", sandboxID, err)
+ return
+ }
+ archiveInfo, err := os.Stat(archivePath)
+ if err != nil {
+ log.Printf("firecracker: async archive stat failed for %s: %v", sandboxID, err)
+ return
+ }
+ log.Printf("firecracker: hibernate %s: archive created (%dms, %.1f MB)",
+ sandboxID, time.Since(t1).Milliseconds(), float64(archiveInfo.Size())/(1024*1024))
+
+ t2 := time.Now()
+ uploadCtx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
+ defer cancel()
+ if _, err := checkpointStore.Upload(uploadCtx, checkpointKey, archivePath); err != nil {
+ log.Printf("firecracker: async S3 upload failed for %s: %v", sandboxID, err)
+ return
+ }
+ log.Printf("firecracker: hibernate %s: S3 upload complete (%dms, key=%s)",
+ sandboxID, time.Since(t2).Milliseconds(), checkpointKey)
+
+ os.Remove(archivePath)
+ }()
+
+ return &sandbox.HibernateResult{
+ SandboxID: sandboxID,
+ CheckpointKey: checkpointKey,
+ SizeBytes: 0, // not known yet — archive happens async
+ }, nil
+}
+
+// doWake restores a VM from a memory snapshot. The VM resumes exactly where it
+// was paused — all processes, memory, open files, and PIDs are intact.
+//
+// Flow:
+// 1. Check for local snapshot files (fast path for same-machine wake)
+// 2. If missing, download from S3 and extract
+// 3. Read snapshot-meta.json for VM configuration
+// 4. Verify drives exist at original paths
+// 5. Recreate network with same TAP name (required by vmstate)
+// 6. Start fresh Firecracker process with API socket
+// 7. Load snapshot via API (restores full VM state)
+// 8. Wait for agent to become available
+// 9. Register VM
+func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, checkpointStore *storage.CheckpointStore, timeout int) (*types.Sandbox, error) {
+ sandboxDir := filepath.Join(m.cfg.DataDir, "sandboxes", sandboxID)
+ snapshotDir := filepath.Join(sandboxDir, "snapshot")
+
+ memFile := filepath.Join(snapshotDir, "mem")
+ vmstateFile := filepath.Join(snapshotDir, "vmstate")
+ metaPath := filepath.Join(snapshotDir, "snapshot-meta.json")
+
+ // Step 1-2: Ensure snapshot files are local
+ t0 := time.Now()
+ memExists := fileExists(memFile)
+ vmstateExists := fileExists(vmstateFile)
+ log.Printf("firecracker: wake %s: checking local files: mem=%s (exists=%v) vmstate=%s (exists=%v)",
+ sandboxID, memFile, memExists, vmstateFile, vmstateExists)
+ if !memExists || !vmstateExists {
+ log.Printf("firecracker: wake %s: local snapshot missing, downloading from S3 (key=%s)", sandboxID, checkpointKey)
+ if err := os.MkdirAll(sandboxDir, 0755); err != nil {
+ return nil, fmt.Errorf("mkdir sandbox dir: %w", err)
+ }
+ if err := os.MkdirAll(snapshotDir, 0755); err != nil {
+ return nil, fmt.Errorf("mkdir snapshot dir: %w", err)
+ }
+
+ archiveData, err := checkpointStore.Download(ctx, checkpointKey)
+ if err != nil {
+ return nil, fmt.Errorf("download checkpoint: %w", err)
+ }
+
+ archivePath := filepath.Join(sandboxDir, "checkpoint.tar.zst")
+ archiveFile, err := os.Create(archivePath)
+ if err != nil {
+ archiveData.Close()
+ return nil, fmt.Errorf("create archive file: %w", err)
+ }
+ if _, err := io.Copy(archiveFile, archiveData); err != nil {
+ archiveFile.Close()
+ archiveData.Close()
+ return nil, fmt.Errorf("write archive: %w", err)
+ }
+ archiveFile.Close()
+ archiveData.Close()
+
+ log.Printf("firecracker: wake %s: downloaded + wrote archive (%dms)", sandboxID, time.Since(t0).Milliseconds())
+ // Extract to sandboxDir — archive contains snapshot/{mem,vmstate,snapshot-meta.json} + workspace.ext4
+ if err := extractArchive(archivePath, sandboxDir); err != nil {
+ return nil, fmt.Errorf("extract archive: %w", err)
+ }
+ os.Remove(archivePath)
+ log.Printf("firecracker: wake %s: extracted archive (%dms total)", sandboxID, time.Since(t0).Milliseconds())
+ } else {
+ log.Printf("firecracker: wake %s: local snapshot found, skipping S3 download", sandboxID)
+ }
+
+ // Step 3: Read snapshot metadata
+ metaJSON, err := os.ReadFile(metaPath)
+ if err != nil {
+ return nil, fmt.Errorf("read snapshot meta: %w", err)
+ }
+ var meta SnapshotMeta
+ if err := json.Unmarshal(metaJSON, &meta); err != nil {
+ return nil, fmt.Errorf("parse snapshot meta: %w", err)
+ }
+
+ // Step 4: Ensure drives exist — provision if missing (cross-worker wake)
+ rootfsPath := filepath.Join(sandboxDir, "rootfs.ext4")
+ workspacePath := filepath.Join(sandboxDir, "workspace.ext4")
+
+ if !fileExists(rootfsPath) {
+ // Cross-worker wake: recreate rootfs from template image
+ log.Printf("firecracker: 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)
+ }
+ log.Printf("firecracker: wake %s: rootfs recreated from %s", sandboxID, baseImage)
+ }
+ if !fileExists(workspacePath) {
+ // workspace.ext4 should have been extracted from the S3 archive above.
+ // If still missing, the archive was created before workspace archiving was added.
+ return nil, fmt.Errorf("workspace not found at %s (not in S3 archive — sandbox was hibernated before workspace archiving was enabled)", workspacePath)
+ }
+
+ // Update metadata paths to this worker's sandboxDir (they may differ from the original worker).
+ // Keep the vsock filename from the original — it's baked into the vmstate for snapshot restore.
+ meta.RootfsPath = rootfsPath
+ meta.WorkspacePath = workspacePath
+ meta.VsockPath = filepath.Join(sandboxDir, filepath.Base(meta.VsockPath))
+
+ // Step 5: Try snapshot restore (fast path) or cold boot (cross-worker fallback).
+ //
+ // Snapshot restore requires the exact same TAP name (baked into vmstate).
+ // If the TAP name is already taken (cross-worker wake), fall back to cold boot:
+ // boot a fresh VM with the restored rootfs + workspace. Processes won't survive
+ // but filesystem state (user files, installed packages) is preserved.
+ snapshotRestore := true
+ netCfg, err := m.subnets.AllocateSpecific(meta.Network.TAPName)
+ if err != nil {
+ // TAP name collision — fall back to cold boot
+ log.Printf("firecracker: wake %s: TAP %s unavailable (%v), falling back to cold boot",
+ sandboxID, meta.Network.TAPName, err)
+ snapshotRestore = false
+ netCfg, err = m.subnets.Allocate()
+ if err != nil {
+ return nil, fmt.Errorf("allocate subnet for cold boot: %w", err)
+ }
+ }
+ if err := CreateTAP(netCfg); err != nil {
+ m.subnets.Release(netCfg.TAPName)
+ return nil, fmt.Errorf("create TAP: %w", err)
+ }
+
+ hostPort, err := FindFreePort()
+ if err != nil {
+ DeleteTAP(netCfg.TAPName)
+ m.subnets.Release(netCfg.TAPName)
+ return nil, fmt.Errorf("find free port: %w", err)
+ }
+ netCfg.HostPort = hostPort
+ netCfg.GuestPort = meta.GuestPort
+ if netCfg.GuestPort == 0 {
+ netCfg.GuestPort = 80
+ }
+
+ if err := AddDNAT(netCfg); err != nil {
+ DeleteTAP(netCfg.TAPName)
+ m.subnets.Release(netCfg.TAPName)
+ return nil, fmt.Errorf("add DNAT: %w", err)
+ }
+
+ apiSockPath := filepath.Join(sandboxDir, "firecracker.sock")
+ vsockPath := meta.VsockPath
+ os.Remove(apiSockPath)
+ os.Remove(vsockPath)
+
+ logPath := filepath.Join(sandboxDir, "firecracker.log")
+ logFile, err := os.Create(logPath)
+ if err != nil {
+ m.cleanupVM(netCfg, "")
+ return nil, fmt.Errorf("create log file: %w", err)
+ }
+
+ cmd := exec.Command(m.cfg.FirecrackerBin, "--api-sock", apiSockPath)
+ cmd.Stdout = logFile
+ cmd.Stderr = logFile
+
+ if err := cmd.Start(); err != nil {
+ logFile.Close()
+ m.cleanupVM(netCfg, "")
+ return nil, fmt.Errorf("start firecracker: %w", err)
+ }
+ logFile.Close()
+
+ fcClient := NewFirecrackerClient(apiSockPath)
+ if err := fcClient.WaitForSocket(5 * time.Second); err != nil {
+ cmd.Process.Kill()
+ cmd.Wait()
+ m.cleanupVM(netCfg, "")
+ return nil, fmt.Errorf("wait for API socket: %w", err)
+ }
+
+ if snapshotRestore {
+ // Hot restore: load snapshot, VM resumes exactly where it was paused
+ if err := fcClient.LoadSnapshot(vmstateFile, memFile, true); err != nil {
+ cmd.Process.Kill()
+ cmd.Wait()
+ m.cleanupVM(netCfg, "")
+ return nil, fmt.Errorf("load snapshot: %w", err)
+ }
+ log.Printf("firecracker: wake %s: snapshot restored (hot)", sandboxID)
+ } else {
+ // Cold boot: configure + boot fresh VM with restored drives.
+ // Filesystem state is preserved but running processes are not.
+ guestCID := m.allocateCID()
+ guestMAC := generateMAC(sandboxID)
+ bootArgs := fmt.Sprintf(
+ "keep_bootcon console=ttyS0 reboot=k panic=1 pci=off "+
+ "ip=%s::%s:%s::eth0:off "+
+ "init=/sbin/init "+
+ "osb.gateway=%s",
+ netCfg.GuestIP, netCfg.HostIP, netCfg.Mask, netCfg.HostIP,
+ )
+ meta.GuestCID = guestCID
+ meta.GuestMAC = guestMAC
+ meta.BootArgs = bootArgs
+
+ if err := fcClient.PutMachineConfig(meta.CpuCount, meta.MemoryMB); err != nil {
+ cmd.Process.Kill(); cmd.Wait(); m.cleanupVM(netCfg, "")
+ return nil, fmt.Errorf("cold boot: put machine config: %w", err)
+ }
+ if err := fcClient.PutBootSource(m.cfg.KernelPath, bootArgs); err != nil {
+ cmd.Process.Kill(); cmd.Wait(); m.cleanupVM(netCfg, "")
+ return nil, fmt.Errorf("cold boot: put boot source: %w", err)
+ }
+ if err := fcClient.PutDrive("rootfs", rootfsPath, true, false); err != nil {
+ cmd.Process.Kill(); cmd.Wait(); m.cleanupVM(netCfg, "")
+ return nil, fmt.Errorf("cold boot: put rootfs drive: %w", err)
+ }
+ if err := fcClient.PutDrive("workspace", workspacePath, false, false); err != nil {
+ cmd.Process.Kill(); cmd.Wait(); m.cleanupVM(netCfg, "")
+ return nil, fmt.Errorf("cold boot: put workspace drive: %w", err)
+ }
+ if err := fcClient.PutNetworkInterface("eth0", guestMAC, netCfg.TAPName); err != nil {
+ cmd.Process.Kill(); cmd.Wait(); m.cleanupVM(netCfg, "")
+ return nil, fmt.Errorf("cold boot: put network interface: %w", err)
+ }
+ if err := fcClient.PutVsock(guestCID, vsockPath); err != nil {
+ cmd.Process.Kill(); cmd.Wait(); m.cleanupVM(netCfg, "")
+ return nil, fmt.Errorf("cold boot: put vsock: %w", err)
+ }
+ if err := fcClient.StartInstance(); err != nil {
+ cmd.Process.Kill(); cmd.Wait(); m.cleanupVM(netCfg, "")
+ return nil, fmt.Errorf("cold boot: start instance: %w", err)
+ }
+ log.Printf("firecracker: wake %s: cold boot complete (cross-worker migration, tap=%s)",
+ sandboxID, netCfg.TAPName)
+ }
+
+ now := time.Now()
+ ttl := time.Duration(timeout) * time.Second
+ if ttl <= 0 {
+ ttl = 300 * time.Second
+ }
+
+ vm := &VMInstance{
+ ID: sandboxID,
+ Template: meta.Template,
+ Status: types.SandboxStatusRunning,
+ StartedAt: now,
+ EndAt: now.Add(ttl),
+ CpuCount: meta.CpuCount,
+ MemoryMB: meta.MemoryMB,
+ HostPort: hostPort,
+ GuestPort: netCfg.GuestPort,
+ pid: cmd.Process.Pid,
+ cmd: cmd,
+ network: netCfg,
+ vsockPath: vsockPath,
+ sandboxDir: sandboxDir,
+ apiSockPath: apiSockPath,
+ fcClient: fcClient,
+ guestMAC: meta.GuestMAC,
+ guestCID: meta.GuestCID,
+ bootArgs: meta.BootArgs,
+ }
+
+ // Wait for agent
+ agentClient, err := m.waitForAgent(context.Background(), vsockPath, 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
+
+ // Register VM
+ m.mu.Lock()
+ m.vms[sandboxID] = vm
+ m.mu.Unlock()
+
+ mode := "snapshot restore"
+ if !snapshotRestore {
+ mode = "cold boot (cross-worker)"
+ }
+ log.Printf("firecracker: woke VM %s (%s, port=%d, tap=%s)",
+ sandboxID, mode, hostPort, netCfg.TAPName)
+
+ return vmToSandbox(vm), nil
+}
+
+// createArchive creates a tar.zst archive of specific files from a directory.
+func createArchive(archivePath, baseDir string, files []string) error {
+ args := []string{
+ "--zstd",
+ "-cf", archivePath,
+ "-C", baseDir,
+ }
+ args = append(args, files...)
+
+ cmd := exec.Command("tar", args...)
+ if out, err := cmd.CombinedOutput(); err != nil {
+ return fmt.Errorf("tar create: %w (%s)", err, strings.TrimSpace(string(out)))
+ }
+ return nil
+}
+
+// extractArchive extracts a tar.zst archive to a directory.
+func extractArchive(archivePath, destDir string) error {
+ cmd := exec.Command("tar", "--zstd", "-xf", archivePath, "-C", destDir)
+ if out, err := cmd.CombinedOutput(); err != nil {
+ return fmt.Errorf("tar extract: %w (%s)", err, strings.TrimSpace(string(out)))
+ }
+ return nil
+}
+
+// fileExists checks if a file exists and is not a directory.
+func fileExists(path string) bool {
+ info, err := os.Stat(path)
+ return err == nil && !info.IsDir()
+}
diff --git a/internal/proxy/controlplane_proxy.go b/internal/proxy/controlplane_proxy.go
new file mode 100644
index 00000000..0ad70e98
--- /dev/null
+++ b/internal/proxy/controlplane_proxy.go
@@ -0,0 +1,236 @@
+package proxy
+
+import (
+ "fmt"
+ "io"
+ "log"
+ "net"
+ "net/http"
+ "net/http/httputil"
+ "net/url"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/labstack/echo/v4"
+ "github.com/opensandbox/opensandbox/internal/controlplane"
+ "github.com/opensandbox/opensandbox/internal/db"
+)
+
+// ControlPlaneProxy routes subdomain requests to the correct worker.
+// It looks up which worker owns the sandbox via the DB, then reverse-proxies
+// the request to that worker's HTTP server (which handles the local proxy to the VM).
+type ControlPlaneProxy struct {
+ baseDomain string
+ store *db.Store
+ registry *controlplane.RedisWorkerRegistry
+}
+
+// NewControlPlaneProxy creates a proxy for control plane subdomain routing.
+func NewControlPlaneProxy(baseDomain string, store *db.Store, registry *controlplane.RedisWorkerRegistry) *ControlPlaneProxy {
+ return &ControlPlaneProxy{
+ baseDomain: baseDomain,
+ store: store,
+ registry: registry,
+ }
+}
+
+// Middleware returns an Echo middleware that intercepts subdomain requests
+// and proxies them to the correct worker.
+func (p *ControlPlaneProxy) Middleware() echo.MiddlewareFunc {
+ return func(next echo.HandlerFunc) echo.HandlerFunc {
+ return func(c echo.Context) error {
+ host := c.Request().Host
+
+ // Strip port from host
+ hostOnly := host
+ if idx := strings.LastIndex(host, ":"); idx != -1 {
+ hostOnly = host[:idx]
+ }
+
+ sandboxID, ok := p.extractSandboxID(hostOnly)
+ if !ok {
+ return next(c)
+ }
+
+ return p.doProxy(c, sandboxID)
+ }
+ }
+}
+
+// extractSandboxID parses "{sandboxID}.{baseDomain}" from the host.
+func (p *ControlPlaneProxy) extractSandboxID(host string) (string, bool) {
+ suffix := "." + p.baseDomain
+ if !strings.HasSuffix(host, suffix) {
+ return "", false
+ }
+ sandboxID := strings.TrimSuffix(host, suffix)
+ if sandboxID == "" || strings.Contains(sandboxID, ".") {
+ return "", false
+ }
+ return sandboxID, true
+}
+
+// doProxy looks up the worker that owns this sandbox and reverse-proxies to it.
+func (p *ControlPlaneProxy) doProxy(c echo.Context, sandboxID string) error {
+ ctx := c.Request().Context()
+
+ // Look up which worker owns this sandbox
+ session, err := p.store.GetSandboxSession(ctx, sandboxID)
+ if err != nil {
+ return c.JSON(http.StatusNotFound, map[string]string{
+ "error": fmt.Sprintf("sandbox %s not found", sandboxID),
+ })
+ }
+
+ worker := p.registry.GetWorker(session.WorkerID)
+ if worker == nil {
+ return c.JSON(http.StatusBadGateway, map[string]string{
+ "error": fmt.Sprintf("worker %s not available", session.WorkerID),
+ })
+ }
+
+ workerURL := worker.HTTPAddr
+ if workerURL == "" {
+ return c.JSON(http.StatusBadGateway, map[string]string{
+ "error": "worker has no HTTP address",
+ })
+ }
+
+ log.Printf("cp-proxy: routing sandbox %s (worker %s) → %s", sandboxID, session.WorkerID, workerURL)
+
+ // WebSocket requests need raw TCP hijacking
+ if isWebSocketUpgrade(c.Request()) {
+ return p.doWebSocket(c, sandboxID, workerURL)
+ }
+
+ return p.doHTTP(c, sandboxID, workerURL)
+}
+
+// doHTTP reverse-proxies a normal HTTP request to the worker.
+func (p *ControlPlaneProxy) doHTTP(c echo.Context, sandboxID, workerURL string) error {
+ target, err := url.Parse(workerURL)
+ if err != nil {
+ return c.JSON(http.StatusBadGateway, map[string]string{
+ "error": "invalid worker URL",
+ })
+ }
+
+ proxy := httputil.NewSingleHostReverseProxy(target)
+ proxy.Transport = &http.Transport{
+ DialContext: (&net.Dialer{
+ Timeout: 5 * time.Second,
+ }).DialContext,
+ ResponseHeaderTimeout: 30 * time.Second,
+ MaxIdleConnsPerHost: 10,
+ }
+
+ var proxyErr error
+ proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
+ proxyErr = err
+ }
+
+ // The worker's proxy middleware matches on the Host header,
+ // so we keep the original Host (sb-xxx.workers.opensandbox.ai).
+ proxy.Director = func(r *http.Request) {
+ r.URL.Scheme = target.Scheme
+ r.URL.Host = target.Host
+ // Preserve original Host header so the worker's proxy can match the subdomain
+ r.Host = c.Request().Host
+ }
+
+ rec := &responseRecorder{
+ header: make(http.Header),
+ }
+ proxy.ServeHTTP(rec, c.Request())
+
+ if proxyErr != nil {
+ log.Printf("cp-proxy: error proxying sandbox %s to %s: %v", sandboxID, workerURL, proxyErr)
+ return c.JSON(http.StatusBadGateway, map[string]string{
+ "error": fmt.Sprintf("sandbox %s: worker unavailable", sandboxID),
+ })
+ }
+
+ rec.writeTo(c.Response())
+ return nil
+}
+
+// doWebSocket hijacks the connection and pipes it to the worker.
+func (p *ControlPlaneProxy) doWebSocket(c echo.Context, sandboxID, workerURL string) error {
+ target, err := url.Parse(workerURL)
+ if err != nil {
+ return c.JSON(http.StatusBadGateway, map[string]string{"error": "invalid worker URL"})
+ }
+
+ // Connect to the worker
+ workerAddr := target.Host
+ if !strings.Contains(workerAddr, ":") {
+ if target.Scheme == "https" {
+ workerAddr += ":443"
+ } else {
+ workerAddr += ":80"
+ }
+ }
+
+ upstream, err := net.DialTimeout("tcp", workerAddr, 5*time.Second)
+ if err != nil {
+ log.Printf("cp-proxy: websocket dial failed for sandbox %s (%s): %v", sandboxID, workerAddr, err)
+ return c.JSON(http.StatusBadGateway, map[string]string{
+ "error": fmt.Sprintf("sandbox %s: worker unavailable", sandboxID),
+ })
+ }
+ defer upstream.Close()
+
+ // Hijack client connection
+ hijacker, ok := c.Response().Writer.(http.Hijacker)
+ if !ok {
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": "websocket hijack not supported",
+ })
+ }
+
+ clientConn, clientBuf, err := hijacker.Hijack()
+ if err != nil {
+ log.Printf("cp-proxy: websocket hijack failed for sandbox %s: %v", sandboxID, err)
+ return err
+ }
+ defer clientConn.Close()
+
+ // Forward the original request to the worker (preserving Host header)
+ if err := c.Request().Write(upstream); err != nil {
+ log.Printf("cp-proxy: websocket write request failed for sandbox %s: %v", sandboxID, err)
+ return nil
+ }
+
+ // Flush any buffered client data
+ if clientBuf.Reader.Buffered() > 0 {
+ buffered := make([]byte, clientBuf.Reader.Buffered())
+ n, _ := clientBuf.Read(buffered)
+ if n > 0 {
+ upstream.Write(buffered[:n])
+ }
+ }
+
+ // Bidirectional pipe
+ var wg sync.WaitGroup
+ wg.Add(2)
+
+ go func() {
+ defer wg.Done()
+ io.Copy(clientConn, upstream)
+ if tc, ok := clientConn.(*net.TCPConn); ok {
+ tc.CloseWrite()
+ }
+ }()
+
+ go func() {
+ defer wg.Done()
+ io.Copy(upstream, clientConn)
+ if tc, ok := upstream.(*net.TCPConn); ok {
+ tc.CloseWrite()
+ }
+ }()
+
+ wg.Wait()
+ return nil
+}
diff --git a/internal/proxy/proxy.go b/internal/proxy/proxy.go
index 1782a71b..885b26d3 100644
--- a/internal/proxy/proxy.go
+++ b/internal/proxy/proxy.go
@@ -22,13 +22,13 @@ import (
// to the corresponding sandbox container's published port.
type SandboxProxy struct {
baseDomain string
- manager *sandbox.Manager
+ manager sandbox.Manager
router *sandbox.SandboxRouter
}
// New creates a new SandboxProxy.
// baseDomain is the base domain for sandbox subdomains (e.g., "workers.opensandbox.dev" or "localhost").
-func New(baseDomain string, mgr *sandbox.Manager, router *sandbox.SandboxRouter) *SandboxProxy {
+func New(baseDomain string, mgr sandbox.Manager, router *sandbox.SandboxRouter) *SandboxProxy {
return &SandboxProxy{
baseDomain: baseDomain,
manager: mgr,
diff --git a/internal/sandbox/exec.go b/internal/sandbox/exec.go
index db0b17ed..21e4d795 100644
--- a/internal/sandbox/exec.go
+++ b/internal/sandbox/exec.go
@@ -11,7 +11,7 @@ import (
)
// Exec runs a command inside a sandbox and returns the result.
-func (m *Manager) Exec(ctx context.Context, sandboxID string, cfg types.ProcessConfig) (*types.ProcessResult, error) {
+func (m *PodmanManager) Exec(ctx context.Context, sandboxID string, cfg types.ProcessConfig) (*types.ProcessResult, error) {
container := m.ContainerName(sandboxID)
timeout := cfg.Timeout
diff --git a/internal/sandbox/filesystem.go b/internal/sandbox/filesystem.go
index 689a06e9..1ab460e5 100644
--- a/internal/sandbox/filesystem.go
+++ b/internal/sandbox/filesystem.go
@@ -11,7 +11,7 @@ import (
)
// ReadFile reads a file from inside the sandbox.
-func (m *Manager) ReadFile(ctx context.Context, sandboxID, path string) (string, error) {
+func (m *PodmanManager) ReadFile(ctx context.Context, sandboxID, path string) (string, error) {
container := m.ContainerName(sandboxID)
content, err := m.podman.ExecSimple(ctx, container, "cat", path)
if err != nil {
@@ -21,7 +21,7 @@ func (m *Manager) ReadFile(ctx context.Context, sandboxID, path string) (string,
}
// WriteFile writes content to a file inside the sandbox.
-func (m *Manager) WriteFile(ctx context.Context, sandboxID, path, content string) error {
+func (m *PodmanManager) WriteFile(ctx context.Context, sandboxID, path, content string) error {
container := m.ContainerName(sandboxID)
// Ensure parent directory exists
@@ -45,7 +45,7 @@ func (m *Manager) WriteFile(ctx context.Context, sandboxID, path, content string
}
// ListDir lists directory contents inside the sandbox.
-func (m *Manager) ListDir(ctx context.Context, sandboxID, path string) ([]types.EntryInfo, error) {
+func (m *PodmanManager) ListDir(ctx context.Context, sandboxID, path string) ([]types.EntryInfo, error) {
container := m.ContainerName(sandboxID)
// Use a script that outputs machine-parseable format
@@ -96,7 +96,7 @@ func (m *Manager) ListDir(ctx context.Context, sandboxID, path string) ([]types.
}
// MakeDir creates a directory inside the sandbox.
-func (m *Manager) MakeDir(ctx context.Context, sandboxID, path string) error {
+func (m *PodmanManager) MakeDir(ctx context.Context, sandboxID, path string) error {
container := m.ContainerName(sandboxID)
_, err := m.podman.ExecSimple(ctx, container, "mkdir", "-p", path)
if err != nil {
@@ -106,7 +106,7 @@ func (m *Manager) MakeDir(ctx context.Context, sandboxID, path string) error {
}
// Remove removes a file or directory inside the sandbox.
-func (m *Manager) Remove(ctx context.Context, sandboxID, path string) error {
+func (m *PodmanManager) Remove(ctx context.Context, sandboxID, path string) error {
container := m.ContainerName(sandboxID)
_, err := m.podman.ExecSimple(ctx, container, "rm", "-rf", path)
if err != nil {
@@ -116,7 +116,7 @@ func (m *Manager) Remove(ctx context.Context, sandboxID, path string) error {
}
// Exists checks if a path exists inside the sandbox.
-func (m *Manager) Exists(ctx context.Context, sandboxID, path string) (bool, error) {
+func (m *PodmanManager) Exists(ctx context.Context, sandboxID, path string) (bool, error) {
container := m.ContainerName(sandboxID)
result, err := m.podman.ExecInContainer(ctx, podman.ExecConfig{
Container: container,
@@ -129,7 +129,7 @@ func (m *Manager) Exists(ctx context.Context, sandboxID, path string) (bool, err
}
// Stat returns file info for a path inside the sandbox.
-func (m *Manager) Stat(ctx context.Context, sandboxID, path string) (*types.FileInfo, error) {
+func (m *PodmanManager) Stat(ctx context.Context, sandboxID, path string) (*types.FileInfo, error) {
container := m.ContainerName(sandboxID)
output, err := m.podman.ExecSimple(ctx, container,
"stat", "--format", "%n\t%F\t%s\t%a\t%Y", path)
diff --git a/internal/sandbox/hibernate.go b/internal/sandbox/hibernate.go
index d80c99d8..48022564 100644
--- a/internal/sandbox/hibernate.go
+++ b/internal/sandbox/hibernate.go
@@ -27,7 +27,7 @@ type HibernateResult struct {
// Hibernate checkpoints a running sandbox, uploads to S3, and removes the container.
// The CRIU checkpoint (process memory) is cached on local NVMe for fast same-machine wake.
// The workspace directory stays on local NVMe and is archived to S3 async for cross-machine wake.
-func (m *Manager) Hibernate(ctx context.Context, sandboxID string, checkpointStore *storage.CheckpointStore) (*HibernateResult, error) {
+func (m *PodmanManager) Hibernate(ctx context.Context, sandboxID string, checkpointStore *storage.CheckpointStore) (*HibernateResult, error) {
name := m.ContainerName(sandboxID)
// 1. Trim memory before checkpoint (best-effort)
@@ -112,7 +112,7 @@ func (m *Manager) Hibernate(ctx context.Context, sandboxID string, checkpointSto
// Wake restores a hibernated sandbox.
// Fast path: if CRIU checkpoint + workspace are both on local NVMe, no S3 calls at all.
// Slow path: downloads missing data from S3 (and caches it locally for next time).
-func (m *Manager) Wake(ctx context.Context, sandboxID string, checkpointKey string, checkpointStore *storage.CheckpointStore, timeout int) (*types.Sandbox, error) {
+func (m *PodmanManager) Wake(ctx context.Context, sandboxID string, checkpointKey string, checkpointStore *storage.CheckpointStore, timeout int) (*types.Sandbox, error) {
name := m.ContainerName(sandboxID)
// 1. Ensure workspace is available
@@ -163,7 +163,7 @@ func (m *Manager) Wake(ctx context.Context, sandboxID string, checkpointKey stri
}
// trimBeforeCheckpoint reduces the container's memory footprint before checkpointing.
-func (m *Manager) trimBeforeCheckpoint(ctx context.Context, containerName string) {
+func (m *PodmanManager) trimBeforeCheckpoint(ctx context.Context, containerName string) {
trimCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
@@ -186,7 +186,7 @@ func WorkspaceS3Key(sandboxID string) string {
}
// archiveWorkspaceToS3 creates a tar.zst archive of the workspace directory and uploads it to S3.
-func (m *Manager) archiveWorkspaceToS3(ctx context.Context, sandboxID, workspaceDir string, store *storage.CheckpointStore) error {
+func (m *PodmanManager) archiveWorkspaceToS3(ctx context.Context, sandboxID, workspaceDir string, store *storage.CheckpointStore) error {
archivePath, err := createTarZstd(workspaceDir)
if err != nil {
return fmt.Errorf("failed to archive workspace: %w", err)
@@ -201,7 +201,7 @@ func (m *Manager) archiveWorkspaceToS3(ctx context.Context, sandboxID, workspace
}
// restoreWorkspaceFromS3 downloads a workspace archive from S3 and extracts it.
-func (m *Manager) restoreWorkspaceFromS3(ctx context.Context, sandboxID, workspaceDir string, store *storage.CheckpointStore) error {
+func (m *PodmanManager) restoreWorkspaceFromS3(ctx context.Context, sandboxID, workspaceDir string, store *storage.CheckpointStore) error {
s3Key := WorkspaceS3Key(sandboxID)
reader, err := store.Download(ctx, s3Key)
if err != nil {
diff --git a/internal/sandbox/interface.go b/internal/sandbox/interface.go
new file mode 100644
index 00000000..bc1ef491
--- /dev/null
+++ b/internal/sandbox/interface.go
@@ -0,0 +1,57 @@
+package sandbox
+
+import (
+ "context"
+
+ "github.com/opensandbox/opensandbox/internal/storage"
+ "github.com/opensandbox/opensandbox/pkg/types"
+)
+
+// SandboxStats holds live resource usage for a sandbox.
+// Runtime-agnostic: both Podman and Firecracker backends populate these fields.
+type SandboxStats struct {
+ CPUPercent float64 `json:"cpuPercent"`
+ MemUsage uint64 `json:"memUsage"` // bytes
+ MemLimit uint64 `json:"memLimit"` // bytes
+ NetInput uint64 `json:"netInput"` // bytes
+ NetOutput uint64 `json:"netOutput"`// bytes
+ PIDs int `json:"pids"`
+}
+
+// Manager defines the sandbox lifecycle interface.
+// Upper layers (SandboxRouter, HTTP/gRPC servers, proxy) depend on this interface,
+// not on a concrete implementation. This allows swapping the backend
+// (e.g., Podman containers → Firecracker microVMs) without changing callers.
+type Manager interface {
+ // Lifecycle
+ Create(ctx context.Context, cfg types.SandboxConfig) (*types.Sandbox, error)
+ Get(ctx context.Context, id string) (*types.Sandbox, error)
+ Kill(ctx context.Context, id string) error
+ List(ctx context.Context) ([]types.Sandbox, error)
+ Count(ctx context.Context) (int, error)
+ Close()
+
+ // Execution
+ Exec(ctx context.Context, sandboxID string, cfg types.ProcessConfig) (*types.ProcessResult, error)
+
+ // Filesystem
+ ReadFile(ctx context.Context, sandboxID, path string) (string, error)
+ WriteFile(ctx context.Context, sandboxID, path, content string) error
+ ListDir(ctx context.Context, sandboxID, path string) ([]types.EntryInfo, error)
+ MakeDir(ctx context.Context, sandboxID, path string) error
+ Remove(ctx context.Context, sandboxID, path string) error
+ Exists(ctx context.Context, sandboxID, path string) (bool, error)
+ Stat(ctx context.Context, sandboxID, path string) (*types.FileInfo, error)
+
+ // Monitoring
+ Stats(ctx context.Context, sandboxID string) (*SandboxStats, error)
+ HostPort(ctx context.Context, sandboxID string) (int, error)
+ DataDir() string
+
+ // Sandbox name (for logging/cleanup)
+ ContainerName(id string) string
+
+ // Hibernation
+ Hibernate(ctx context.Context, sandboxID string, checkpointStore *storage.CheckpointStore) (*HibernateResult, error)
+ Wake(ctx context.Context, sandboxID string, checkpointKey string, checkpointStore *storage.CheckpointStore, timeout int) (*types.Sandbox, error)
+}
diff --git a/internal/sandbox/manager.go b/internal/sandbox/manager.go
index 47f686e3..3787bd0d 100644
--- a/internal/sandbox/manager.go
+++ b/internal/sandbox/manager.go
@@ -28,9 +28,12 @@ const (
maxCPU = 4
)
-// Manager handles sandbox lifecycle operations (pure container executor).
+// Compile-time check: PodmanManager implements Manager interface.
+var _ Manager = (*PodmanManager)(nil)
+
+// PodmanManager handles sandbox lifecycle via Podman containers.
// Timer management and state machine logic live in SandboxRouter.
-type Manager struct {
+type PodmanManager struct {
podman *podman.Client
dataDir string // base directory for per-sandbox persistent data (workspace, sqlite)
defaultMemoryMB int
@@ -38,32 +41,32 @@ type Manager struct {
defaultDiskMB int // per-sandbox disk quota (0 = no quota)
}
-// ManagerOption configures a Manager.
-type ManagerOption func(*Manager)
+// ManagerOption configures a PodmanManager.
+type ManagerOption func(*PodmanManager)
// WithDataDir sets the base directory for per-sandbox persistent data.
func WithDataDir(dir string) ManagerOption {
- return func(m *Manager) { m.dataDir = dir }
+ return func(m *PodmanManager) { m.dataDir = dir }
}
// WithDefaultMemoryMB sets the default memory per sandbox (in MB).
func WithDefaultMemoryMB(mb int) ManagerOption {
- return func(m *Manager) { m.defaultMemoryMB = mb }
+ return func(m *PodmanManager) { m.defaultMemoryMB = mb }
}
// WithDefaultCPUs sets the default vCPU count per sandbox.
func WithDefaultCPUs(cpus int) ManagerOption {
- return func(m *Manager) { m.defaultCPU = cpus }
+ return func(m *PodmanManager) { m.defaultCPU = cpus }
}
// WithDefaultDiskMB sets the default disk quota per sandbox (in MB). 0 = no quota.
func WithDefaultDiskMB(mb int) ManagerOption {
- return func(m *Manager) { m.defaultDiskMB = mb }
+ return func(m *PodmanManager) { m.defaultDiskMB = mb }
}
// NewManager creates a new sandbox manager.
-func NewManager(client *podman.Client, opts ...ManagerOption) *Manager {
- m := &Manager{
+func NewManager(client *podman.Client, opts ...ManagerOption) *PodmanManager {
+ m := &PodmanManager{
podman: client,
defaultMemoryMB: 1024,
defaultCPU: 1,
@@ -75,12 +78,12 @@ func NewManager(client *podman.Client, opts ...ManagerOption) *Manager {
}
// DataDir returns the base data directory for sandbox storage.
-func (m *Manager) DataDir() string {
+func (m *PodmanManager) DataDir() string {
return m.dataDir
}
// Create creates a new sandbox container and starts it.
-func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (*types.Sandbox, error) {
+func (m *PodmanManager) Create(ctx context.Context, cfg types.SandboxConfig) (*types.Sandbox, error) {
id := uuid.New().String()[:8]
name := fmt.Sprintf("%s-%s", containerName, id)
@@ -182,7 +185,7 @@ func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (*types.S
}
// Get returns sandbox info by ID.
-func (m *Manager) Get(ctx context.Context, id string) (*types.Sandbox, error) {
+func (m *PodmanManager) Get(ctx context.Context, id string) (*types.Sandbox, error) {
name := fmt.Sprintf("%s-%s", containerName, id)
info, err := m.podman.InspectContainer(ctx, name)
if err != nil {
@@ -192,7 +195,7 @@ func (m *Manager) Get(ctx context.Context, id string) (*types.Sandbox, error) {
}
// Kill forcefully removes a sandbox and cleans up its on-disk workspace.
-func (m *Manager) Kill(ctx context.Context, id string) error {
+func (m *PodmanManager) Kill(ctx context.Context, id string) error {
name := fmt.Sprintf("%s-%s", containerName, id)
if err := m.podman.RemoveContainer(ctx, name, true); err != nil {
return fmt.Errorf("failed to kill sandbox %s: %w", id, err)
@@ -205,7 +208,7 @@ func (m *Manager) Kill(ctx context.Context, id string) error {
}
// List returns all sandboxes.
-func (m *Manager) List(ctx context.Context) ([]types.Sandbox, error) {
+func (m *PodmanManager) List(ctx context.Context) ([]types.Sandbox, error) {
entries, err := m.podman.ListContainers(ctx, labelID)
if err != nil {
return nil, fmt.Errorf("failed to list sandboxes: %w", err)
@@ -219,7 +222,7 @@ func (m *Manager) List(ctx context.Context) ([]types.Sandbox, error) {
}
// Count returns the number of active sandbox containers.
-func (m *Manager) Count(ctx context.Context) (int, error) {
+func (m *PodmanManager) Count(ctx context.Context) (int, error) {
entries, err := m.podman.ListContainers(ctx, labelID)
if err != nil {
return 0, fmt.Errorf("failed to count sandboxes: %w", err)
@@ -228,12 +231,12 @@ func (m *Manager) Count(ctx context.Context) (int, error) {
}
// ContainerName returns the podman container name for a sandbox ID.
-func (m *Manager) ContainerName(id string) string {
+func (m *PodmanManager) ContainerName(id string) string {
return fmt.Sprintf("%s-%s", containerName, id)
}
// HostPort returns the mapped host port for a sandbox's container port 80.
-func (m *Manager) HostPort(ctx context.Context, sandboxID string) (int, error) {
+func (m *PodmanManager) HostPort(ctx context.Context, sandboxID string) (int, error) {
name := m.ContainerName(sandboxID)
info, err := m.podman.InspectContainer(ctx, name)
if err != nil {
@@ -251,13 +254,24 @@ func (m *Manager) HostPort(ctx context.Context, sandboxID string) (int, error) {
}
// Stats returns live CPU/memory stats for a running sandbox.
-func (m *Manager) Stats(ctx context.Context, sandboxID string) (*podman.ContainerStats, error) {
+func (m *PodmanManager) Stats(ctx context.Context, sandboxID string) (*SandboxStats, error) {
name := m.ContainerName(sandboxID)
- return m.podman.ContainerStats(ctx, name)
+ cs, err := m.podman.ContainerStats(ctx, name)
+ if err != nil {
+ return nil, err
+ }
+ return &SandboxStats{
+ CPUPercent: cs.CPUPercent,
+ MemUsage: cs.MemUsage,
+ MemLimit: cs.MemLimit,
+ NetInput: cs.NetInput,
+ NetOutput: cs.NetOutput,
+ PIDs: cs.PIDs,
+ }, nil
}
// Close is a no-op — timer management now lives in SandboxRouter.
-func (m *Manager) Close() {}
+func (m *PodmanManager) Close() {}
func resolveTemplateImage(template string) string {
switch template {
diff --git a/internal/sandbox/pty.go b/internal/sandbox/pty.go
index 302c3151..669aa9f9 100644
--- a/internal/sandbox/pty.go
+++ b/internal/sandbox/pty.go
@@ -2,6 +2,7 @@ package sandbox
import (
"fmt"
+ "io"
"os"
"os/exec"
"sync"
@@ -12,23 +13,35 @@ import (
)
// PTYManager manages PTY sessions.
+// Supports both Podman (host-side PTY via podman exec) and Firecracker
+// (agent gRPC + vsock data port) by allowing the session creation function
+// to be overridden.
type PTYManager struct {
podmanPath string
authFile string
mu sync.RWMutex
sessions map[string]*PTYSessionHandle
+
+ // createFunc allows overriding session creation for Firecracker mode.
+ // If nil, defaults to Podman-based PTY via podman exec.
+ createFunc func(sandboxID string, req types.PTYCreateRequest) (*PTYSessionHandle, error)
}
// PTYSessionHandle holds the state for an active PTY session.
type PTYSessionHandle struct {
ID string
SandboxID string
- Cmd *exec.Cmd
- PTY *os.File // master side of the pseudo-terminal (read + write)
+ Cmd *exec.Cmd // Podman mode only (nil for Firecracker)
+ PTY io.ReadWriteCloser // PTY I/O stream (*os.File for Podman, net.Conn for Firecracker)
Done chan struct{}
+
+ // onKill is called when the session is killed (Firecracker: sends gRPC PTYKill).
+ onKill func()
+ // onResize is called when the session is resized (Firecracker: sends gRPC PTYResize).
+ onResize func(cols, rows int) error
}
-// NewPTYManager creates a new PTY manager.
+// NewPTYManager creates a new Podman-based PTY manager.
func NewPTYManager(podmanPath, authFile string) *PTYManager {
return &PTYManager{
podmanPath: podmanPath,
@@ -37,8 +50,35 @@ func NewPTYManager(podmanPath, authFile string) *PTYManager {
}
}
+// NewAgentPTYManager creates a PTY manager that delegates to a custom
+// create function (used by Firecracker mode).
+func NewAgentPTYManager(createFunc func(sandboxID string, req types.PTYCreateRequest) (*PTYSessionHandle, error)) *PTYManager {
+ return &PTYManager{
+ sessions: make(map[string]*PTYSessionHandle),
+ createFunc: createFunc,
+ }
+}
+
// CreateSession starts a new PTY session inside a sandbox.
func (pm *PTYManager) CreateSession(sandboxID string, req types.PTYCreateRequest) (*PTYSessionHandle, error) {
+ // Use override if set (Firecracker mode)
+ if pm.createFunc != nil {
+ handle, err := pm.createFunc(sandboxID, req)
+ if err != nil {
+ return nil, err
+ }
+ pm.mu.Lock()
+ pm.sessions[handle.ID] = handle
+ pm.mu.Unlock()
+ return handle, nil
+ }
+
+ // Default: Podman-based PTY
+ return pm.createPodmanSession(sandboxID, req)
+}
+
+// createPodmanSession creates a PTY session using podman exec.
+func (pm *PTYManager) createPodmanSession(sandboxID string, req types.PTYCreateRequest) (*PTYSessionHandle, error) {
sessionID := uuid.New().String()[:8]
containerName := fmt.Sprintf("osb-%s", sandboxID)
@@ -106,10 +146,19 @@ func (pm *PTYManager) Resize(sessionID string, cols, rows int) error {
return fmt.Errorf("PTY session %s not found", sessionID)
}
- return ptylib.Setsize(session.PTY, &ptylib.Winsize{
- Rows: uint16(rows),
- Cols: uint16(cols),
- })
+ // Use Firecracker resize if available
+ if session.onResize != nil {
+ return session.onResize(cols, rows)
+ }
+
+ // Podman mode: resize via pty ioctl
+ if f, ok := session.PTY.(*os.File); ok {
+ return ptylib.Setsize(f, &ptylib.Winsize{
+ Rows: uint16(rows),
+ Cols: uint16(cols),
+ })
+ }
+ return fmt.Errorf("resize not supported for this session type")
}
// GetSession returns a PTY session by ID.
@@ -137,8 +186,13 @@ func (pm *PTYManager) KillSession(sessionID string) error {
return fmt.Errorf("PTY session %s not found", sessionID)
}
+ // Call Firecracker kill callback if set
+ if session.onKill != nil {
+ session.onKill()
+ }
+
session.PTY.Close()
- if session.Cmd.Process != nil {
+ if session.Cmd != nil && session.Cmd.Process != nil {
_ = session.Cmd.Process.Kill()
}
return nil
@@ -150,8 +204,11 @@ func (pm *PTYManager) CloseAll() {
defer pm.mu.Unlock()
for _, session := range pm.sessions {
+ if session.onKill != nil {
+ session.onKill()
+ }
session.PTY.Close()
- if session.Cmd.Process != nil {
+ if session.Cmd != nil && session.Cmd.Process != nil {
_ = session.Cmd.Process.Kill()
}
}
diff --git a/internal/sandbox/quota.go b/internal/sandbox/quota.go
index 64ceffd7..ea8a976f 100644
--- a/internal/sandbox/quota.go
+++ b/internal/sandbox/quota.go
@@ -14,7 +14,7 @@ import (
// SetDiskQuota enforces a disk quota on a sandbox's data directory using XFS project quotas.
// This requires the filesystem to be mounted with -o prjquota and xfs_quota to be available.
// If quotas are not supported (e.g., dev mode on non-XFS), the error is logged and ignored.
-func (m *Manager) SetDiskQuota(sandboxID string, limitMB int) {
+func (m *PodmanManager) SetDiskQuota(sandboxID string, limitMB int) {
if m.dataDir == "" || limitMB <= 0 {
return
}
@@ -50,7 +50,7 @@ func (m *Manager) SetDiskQuota(sandboxID string, limitMB int) {
}
// RemoveDiskQuota removes the XFS project quota entries for a sandbox.
-func (m *Manager) RemoveDiskQuota(sandboxID string) {
+func (m *PodmanManager) RemoveDiskQuota(sandboxID string) {
if m.dataDir == "" {
return
}
diff --git a/internal/sandbox/router.go b/internal/sandbox/router.go
index b4757718..d32e04c2 100644
--- a/internal/sandbox/router.go
+++ b/internal/sandbox/router.go
@@ -50,7 +50,7 @@ type Middleware func(ctx context.Context, sandboxID string, op string, next func
// RouterConfig holds configuration for the SandboxRouter.
type RouterConfig struct {
- Manager *Manager
+ Manager Manager
CheckpointStore *storage.CheckpointStore // nil disables auto-wake/hibernate
Store *db.Store // nil disables DB lookups for wake
WorkerID string
@@ -65,7 +65,7 @@ type RouterConfig struct {
// which ensures the sandbox is running, executes the operation, and
// resets the rolling idle timeout.
type SandboxRouter struct {
- manager *Manager
+ manager Manager
checkpointStore *storage.CheckpointStore
store *db.Store
workerID string
@@ -268,9 +268,9 @@ func (r *SandboxRouter) Close() {
r.sandboxes = make(map[string]*sandboxEntry)
}
-// Manager returns the underlying Manager for direct lifecycle operations
+// GetManager returns the underlying Manager for direct lifecycle operations
// (create, kill, hibernate, wake) that don't go through routing.
-func (r *SandboxRouter) Manager() *Manager {
+func (r *SandboxRouter) GetManager() Manager {
return r.manager
}
@@ -461,11 +461,10 @@ func (r *SandboxRouter) onTimeout(sandboxID string) {
// Try hibernate if checkpoint store is available
if r.checkpointStore != nil {
- name := r.manager.ContainerName(sandboxID)
result, err := r.manager.Hibernate(ctx, sandboxID, r.checkpointStore)
if err != nil {
log.Printf("router: hibernate failed for %s, killing: %v", sandboxID, err)
- _ = r.manager.podman.RemoveContainer(ctx, name, true)
+ _ = r.manager.Kill(ctx, sandboxID)
r.Unregister(sandboxID)
if r.onKill != nil {
r.onKill(sandboxID)
@@ -487,8 +486,7 @@ func (r *SandboxRouter) onTimeout(sandboxID string) {
}
// No checkpoint store — just kill
- name := r.manager.ContainerName(sandboxID)
- _ = r.manager.podman.RemoveContainer(ctx, name, true)
+ _ = r.manager.Kill(ctx, sandboxID)
r.Unregister(sandboxID)
if r.onKill != nil {
r.onKill(sandboxID)
diff --git a/internal/storage/s3.go b/internal/storage/s3.go
index 7756f60f..1c026a45 100644
--- a/internal/storage/s3.go
+++ b/internal/storage/s3.go
@@ -233,41 +233,116 @@ func (s *CheckpointStore) openCached(key string) (io.ReadCloser, error) {
return f, nil
}
-// downloadAndCache downloads from S3, writes to NVMe cache, returns the cached file.
+// downloadAndCache downloads from S3 using parallel byte-range requests,
+// writes to NVMe cache, returns the cached file.
func (s *CheckpointStore) downloadAndCache(ctx context.Context, key string) (io.ReadCloser, error) {
- resp, err := s.client.GetObject(ctx, &s3.GetObjectInput{
- Bucket: aws.String(s.bucket),
- Key: aws.String(key),
- })
- if err != nil {
- return nil, fmt.Errorf("failed to download checkpoint from S3: %w", err)
- }
-
s.evictIfNeeded()
cachePath := s.CachePath(key)
tmpFile, err := os.CreateTemp(s.cacheDir, ".dl-tmp-*")
if err != nil {
- // Can't write to cache — fall back to direct S3 stream
- log.Printf("checkpoint-cache: can't create temp, streaming from S3: %v", err)
- return resp.Body, nil
+ // Can't write to cache — fall back to single-stream
+ log.Printf("checkpoint-cache: can't create temp, falling back to single-stream: %v", err)
+ return s.downloadFromS3(ctx, key)
}
tmpPath := tmpFile.Name()
- written, err := io.Copy(tmpFile, resp.Body)
- resp.Body.Close()
+ // Get object size via HeadObject
+ head, err := s.client.HeadObject(ctx, &s3.HeadObjectInput{
+ Bucket: aws.String(s.bucket),
+ Key: aws.String(key),
+ })
if err != nil {
tmpFile.Close()
os.Remove(tmpPath)
- return nil, fmt.Errorf("failed to download checkpoint from S3: %w", err)
+ return nil, fmt.Errorf("failed to head checkpoint in S3: %w", err)
}
+
+ totalSize := aws.ToInt64(head.ContentLength)
+ if totalSize <= 0 {
+ tmpFile.Close()
+ os.Remove(tmpPath)
+ return nil, fmt.Errorf("checkpoint has zero size in S3: %s", key)
+ }
+
+ // Pre-allocate the file
+ if err := tmpFile.Truncate(totalSize); err != nil {
+ tmpFile.Close()
+ os.Remove(tmpPath)
+ return nil, fmt.Errorf("failed to preallocate temp file: %w", err)
+ }
+
+ const chunkSize = 64 * 1024 * 1024 // 64 MB chunks
+ const maxParallel = 16
+
+ numChunks := int((totalSize + chunkSize - 1) / chunkSize)
+ t0 := time.Now()
+ log.Printf("checkpoint-cache: downloading %s (%.1f MB, %d chunks, %d parallel)",
+ key, float64(totalSize)/(1024*1024), numChunks, maxParallel)
+
+ // Download chunks in parallel
+ var wg sync.WaitGroup
+ sem := make(chan struct{}, maxParallel)
+ errs := make([]error, numChunks)
+
+ for i := 0; i < numChunks; i++ {
+ wg.Add(1)
+ sem <- struct{}{}
+ go func(idx int) {
+ defer wg.Done()
+ defer func() { <-sem }()
+
+ start := int64(idx) * chunkSize
+ end := start + chunkSize - 1
+ if end >= totalSize {
+ end = totalSize - 1
+ }
+ rangeHeader := fmt.Sprintf("bytes=%d-%d", start, end)
+
+ resp, err := s.client.GetObject(ctx, &s3.GetObjectInput{
+ Bucket: aws.String(s.bucket),
+ Key: aws.String(key),
+ Range: aws.String(rangeHeader),
+ })
+ if err != nil {
+ errs[idx] = fmt.Errorf("chunk %d: %w", idx, err)
+ return
+ }
+ defer resp.Body.Close()
+
+ buf, err := io.ReadAll(resp.Body)
+ if err != nil {
+ errs[idx] = fmt.Errorf("chunk %d read: %w", idx, err)
+ return
+ }
+
+ if _, err := tmpFile.WriteAt(buf, start); err != nil {
+ errs[idx] = fmt.Errorf("chunk %d write: %w", idx, err)
+ return
+ }
+ }(i)
+ }
+ wg.Wait()
+
tmpFile.Close()
+ // Check for errors
+ for _, e := range errs {
+ if e != nil {
+ os.Remove(tmpPath)
+ return nil, fmt.Errorf("parallel download failed: %w", e)
+ }
+ }
+
+ elapsed := time.Since(t0)
+ mbPerSec := float64(totalSize) / (1024 * 1024) / elapsed.Seconds()
+
if err := os.Rename(tmpPath, cachePath); err != nil {
os.Remove(tmpPath)
log.Printf("checkpoint-cache: rename failed: %v", err)
} else {
- log.Printf("checkpoint-cache: MISS %s (%d MB downloaded from S3, now cached)", key, written>>20)
+ log.Printf("checkpoint-cache: MISS %s (%.1f MB downloaded from S3 in %dms, %.0f MB/s, now cached)",
+ key, float64(totalSize)/(1024*1024), elapsed.Milliseconds(), mbPerSec)
}
f, err := os.Open(cachePath)
diff --git a/internal/template/builder.go b/internal/template/builder.go
index 27cd83c8..67fd68f6 100644
--- a/internal/template/builder.go
+++ b/internal/template/builder.go
@@ -5,29 +5,40 @@ import (
"fmt"
"log"
"os"
+ "os/exec"
"path/filepath"
+ "strings"
- "github.com/opensandbox/opensandbox/internal/ecr"
"github.com/opensandbox/opensandbox/internal/podman"
)
-// Builder builds container images from Dockerfiles and pushes to ECR.
+// Builder builds ext4 rootfs images from Dockerfiles using Podman as a build tool.
+// The workflow: Dockerfile → podman build → podman create → podman export → tar2ext4 → images dir.
+// The osb-agent binary and init script are injected into the image during build.
type Builder struct {
podman *podman.Client
- ecrConfig *ecr.Config // nil if ECR not configured
+ imagesDir string // target directory for ext4 images (e.g., /data/firecracker/images/)
+ agentPath string // path to osb-agent binary to inject into images
}
// NewBuilder creates a new template builder.
-func NewBuilder(client *podman.Client, ecrConfig *ecr.Config) *Builder {
+// imagesDir is where completed ext4 images are stored.
+// agentPath is the osb-agent binary to inject (if empty, uses /usr/local/bin/osb-agent).
+func NewBuilder(client *podman.Client, imagesDir, agentPath string) *Builder {
+ if agentPath == "" {
+ agentPath = "/usr/local/bin/osb-agent"
+ }
return &Builder{
podman: client,
- ecrConfig: ecrConfig,
+ imagesDir: imagesDir,
+ agentPath: agentPath,
}
}
-// Build builds a template from Dockerfile content, tags it, and pushes to ECR.
-// Returns the final ECR image reference and the build log.
-func (b *Builder) Build(ctx context.Context, dockerfile, name, tag, ecrImageRef string) (string, string, error) {
+// Build builds an ext4 rootfs image from a Dockerfile.
+// The resulting image is placed at {imagesDir}/{name}.ext4.
+// Returns the image path and the build log.
+func (b *Builder) Build(ctx context.Context, dockerfile, name, tag, _ string) (string, string, error) {
if tag == "" {
tag = "latest"
}
@@ -41,12 +52,31 @@ func (b *Builder) Build(ctx context.Context, dockerfile, name, tag, ecrImageRef
}
defer os.RemoveAll(tmpDir)
+ // Inject osb-agent and init script into the Dockerfile
+ augmentedDockerfile := b.augmentDockerfile(dockerfile)
+
dockerfilePath := filepath.Join(tmpDir, "Dockerfile")
- if err := os.WriteFile(dockerfilePath, []byte(dockerfile), 0644); err != nil {
+ if err := os.WriteFile(dockerfilePath, []byte(augmentedDockerfile), 0644); err != nil {
return "", "", fmt.Errorf("failed to write Dockerfile: %w", err)
}
+ // Copy agent binary into build context so COPY instruction works
+ if _, err := os.Stat(b.agentPath); err == nil {
+ agentDest := filepath.Join(tmpDir, "osb-agent")
+ if err := copyFile(b.agentPath, agentDest); err != nil {
+ return "", "", fmt.Errorf("failed to copy agent binary to build context: %w", err)
+ }
+ }
+
+ // Copy init script into build context
+ initScript := generateInitScript()
+ initPath := filepath.Join(tmpDir, "init")
+ if err := os.WriteFile(initPath, []byte(initScript), 0755); err != nil {
+ return "", "", fmt.Errorf("failed to write init script: %w", err)
+ }
+
// Build image with podman
+ log.Printf("template: building image %s from Dockerfile...", localImage)
result, err := b.podman.Run(ctx, "build", "-t", localImage, "-f", dockerfilePath, tmpDir)
if err != nil {
return "", "", fmt.Errorf("failed to build template %s: %w", name, err)
@@ -56,47 +86,252 @@ func (b *Builder) Build(ctx context.Context, dockerfile, name, tag, ecrImageRef
}
buildLog := result.Stdout + result.Stderr
- // If ECR is configured and an image ref was provided, tag and push
- if b.ecrConfig != nil && b.ecrConfig.IsConfigured() && ecrImageRef != "" {
- // Authenticate to ECR
- username, password, err := ecr.GetAuthToken(ctx, b.ecrConfig)
- if err != nil {
- return "", buildLog, fmt.Errorf("failed to get ECR auth: %w", err)
- }
+ // Export container filesystem as tar
+ log.Printf("template: exporting filesystem for %s...", name)
+ tarPath := filepath.Join(tmpDir, "rootfs.tar")
+ if err := b.exportImage(ctx, localImage, tarPath); err != nil {
+ return "", buildLog, fmt.Errorf("failed to export image: %w", err)
+ }
- if err := b.podman.LoginRegistry(ctx, b.ecrConfig.Registry, username, password); err != nil {
- return "", buildLog, fmt.Errorf("failed to login to ECR: %w", err)
- }
+ // Convert tar to ext4
+ log.Printf("template: converting to ext4 for %s...", name)
+ ext4Path := filepath.Join(tmpDir, "rootfs.ext4")
+ if err := tarToExt4(tarPath, ext4Path, 4096); err != nil {
+ return "", buildLog, fmt.Errorf("failed to convert to ext4: %w", err)
+ }
- // Tag with ECR reference
- if err := b.podman.TagImage(ctx, localImage, ecrImageRef); err != nil {
- return "", buildLog, fmt.Errorf("failed to tag image for ECR: %w", err)
+ // Move to images directory
+ if err := os.MkdirAll(b.imagesDir, 0755); err != nil {
+ return "", buildLog, fmt.Errorf("failed to create images dir: %w", err)
+ }
+ destPath := filepath.Join(b.imagesDir, name+".ext4")
+ if err := os.Rename(ext4Path, destPath); err != nil {
+ // Cross-device: copy + remove
+ if err := copyFile(ext4Path, destPath); err != nil {
+ return "", buildLog, fmt.Errorf("failed to move ext4 to images dir: %w", err)
}
+ os.Remove(ext4Path)
+ }
+
+ // Clean up local image
+ _, _ = b.podman.Run(ctx, "rmi", "-f", localImage)
+
+ log.Printf("template: built %s (%s)", name, destPath)
+ return destPath, buildLog, nil
+}
+
+// augmentDockerfile appends instructions to inject osb-agent and init script.
+func (b *Builder) augmentDockerfile(dockerfile string) string {
+ // Append agent + init injection after the user's Dockerfile
+ injection := `
+
+# --- OpenSandbox agent injection ---
+COPY osb-agent /usr/local/bin/osb-agent
+RUN chmod +x /usr/local/bin/osb-agent
+COPY init /sbin/init
+RUN chmod +x /sbin/init
+# Ensure workspace mount point exists
+RUN mkdir -p /workspace
+`
+ return dockerfile + injection
+}
+
+// exportImage creates a container from the image, exports its filesystem as a tar.
+func (b *Builder) exportImage(ctx context.Context, image, tarPath string) error {
+ // Create a container (don't start it)
+ containerName := "osb-export-" + filepath.Base(tarPath)
+ result, err := b.podman.Run(ctx, "create", "--name", containerName, image, "/bin/true")
+ if err != nil {
+ return fmt.Errorf("podman create: %w", err)
+ }
+ if result.ExitCode != 0 {
+ return fmt.Errorf("podman create failed (exit %d): %s", result.ExitCode, result.Stderr)
+ }
+ containerID := strings.TrimSpace(result.Stdout)
+ if containerID == "" {
+ containerID = containerName
+ }
+
+ // Export container filesystem
+ defer func() {
+ _, _ = b.podman.Run(ctx, "rm", "-f", containerID)
+ }()
+
+ result, err = b.podman.Run(ctx, "export", "-o", tarPath, containerID)
+ if err != nil {
+ return fmt.Errorf("podman export: %w", err)
+ }
+ if result.ExitCode != 0 {
+ return fmt.Errorf("podman export failed (exit %d): %s", result.ExitCode, result.Stderr)
+ }
+
+ return nil
+}
- // Push to ECR
- log.Printf("template: pushing %s to ECR...", ecrImageRef)
- if err := b.podman.PushImage(ctx, ecrImageRef); err != nil {
- return "", buildLog, fmt.Errorf("failed to push image to ECR: %w", err)
+// tarToExt4 converts a tar archive to an ext4 filesystem image.
+// sizeMB is the target size of the ext4 image.
+func tarToExt4(tarPath, ext4Path string, sizeMB int) error {
+ // Create sparse ext4 image
+ f, err := os.Create(ext4Path)
+ if err != nil {
+ return fmt.Errorf("create ext4 file: %w", err)
+ }
+ if err := f.Truncate(int64(sizeMB) * 1024 * 1024); err != nil {
+ f.Close()
+ return fmt.Errorf("truncate ext4: %w", err)
+ }
+ f.Close()
+
+ // Format as ext4
+ cmd := exec.Command("mkfs.ext4", "-q", "-F",
+ "-L", "rootfs",
+ "-d", "/dev/null", // dummy, we'll populate via mount
+ ext4Path)
+ if out, err := cmd.CombinedOutput(); err != nil {
+ // mkfs.ext4 -d might not be available on older versions, try without
+ cmd2 := exec.Command("mkfs.ext4", "-q", "-F", "-L", "rootfs", ext4Path)
+ if out2, err2 := cmd2.CombinedOutput(); err2 != nil {
+ return fmt.Errorf("mkfs.ext4: %w (%s / %s)", err2, strings.TrimSpace(string(out)), strings.TrimSpace(string(out2)))
}
- log.Printf("template: push complete for %s", ecrImageRef)
+ }
+
+ // Mount the ext4 image and extract tar into it
+ mountDir, err := os.MkdirTemp("", "osb-mount-*")
+ if err != nil {
+ return fmt.Errorf("create mount dir: %w", err)
+ }
+ defer os.RemoveAll(mountDir)
+
+ // Mount using loop device
+ mountCmd := exec.Command("mount", "-o", "loop", ext4Path, mountDir)
+ if out, err := mountCmd.CombinedOutput(); err != nil {
+ return fmt.Errorf("mount ext4: %w (%s)", err, strings.TrimSpace(string(out)))
+ }
+ defer func() {
+ exec.Command("umount", mountDir).Run()
+ }()
+
+ // Extract tar into mounted filesystem
+ tarCmd := exec.Command("tar", "xf", tarPath, "-C", mountDir)
+ if out, err := tarCmd.CombinedOutput(); err != nil {
+ return fmt.Errorf("extract tar: %w (%s)", err, strings.TrimSpace(string(out)))
+ }
+
+ // Ensure key directories exist
+ for _, dir := range []string{"proc", "sys", "dev", "tmp", "workspace", "run"} {
+ os.MkdirAll(filepath.Join(mountDir, dir), 0755)
+ }
+
+ // Sync and unmount
+ exec.Command("sync").Run()
+ umountCmd := exec.Command("umount", mountDir)
+ if out, err := umountCmd.CombinedOutput(); err != nil {
+ return fmt.Errorf("umount: %w (%s)", err, strings.TrimSpace(string(out)))
+ }
- return ecrImageRef, buildLog, nil
+ // Shrink the ext4 image to minimum size + headroom
+ resizeCmd := exec.Command("resize2fs", "-M", ext4Path)
+ if out, err := resizeCmd.CombinedOutput(); err != nil {
+ // Non-fatal — image just stays at full size
+ log.Printf("template: resize2fs -M warning: %v (%s)", err, strings.TrimSpace(string(out)))
}
- // No ECR — return local image reference
- return localImage, buildLog, nil
+ return nil
}
-// RefreshECRAuth authenticates podman to ECR. Call periodically (tokens expire after 12h).
-func (b *Builder) RefreshECRAuth(ctx context.Context) error {
- if b.ecrConfig == nil || !b.ecrConfig.IsConfigured() {
- return nil
+// generateInitScript creates the /sbin/init script for Firecracker VMs.
+func generateInitScript() string {
+ return `#!/bin/busybox sh
+# OpenSandbox VM init script
+# Runs as PID 1 inside the Firecracker microVM
+
+# Mount virtual filesystems
+mount -t proc proc /proc
+mount -t sysfs sysfs /sys
+mount -t devtmpfs devtmpfs /dev
+mount -t tmpfs tmpfs /tmp
+mount -t tmpfs tmpfs /run
+
+# Create device nodes if devtmpfs didn't
+[ -c /dev/null ] || mknod -m 666 /dev/null c 1 3
+[ -c /dev/zero ] || mknod -m 666 /dev/zero c 1 5
+[ -c /dev/random ] || mknod -m 444 /dev/random c 1 8
+[ -c /dev/urandom ] || mknod -m 444 /dev/urandom c 1 9
+[ -c /dev/tty ] || mknod -m 666 /dev/tty c 5 0
+[ -c /dev/console ] || mknod -m 600 /dev/console c 5 1
+[ -d /dev/pts ] || mkdir -p /dev/pts
+mount -t devpts devpts /dev/pts
+[ -d /dev/shm ] || mkdir -p /dev/shm
+mount -t tmpfs tmpfs /dev/shm
+
+# Mount workspace from vdb
+mkdir -p /workspace
+mount /dev/vdb /workspace 2>/dev/null || {
+ echo "init: warning: could not mount /dev/vdb, trying /dev/vdb1"
+ mount /dev/vdb1 /workspace 2>/dev/null || echo "init: warning: workspace mount failed"
+}
+
+# Configure networking from kernel command line
+# Format: ip=GUEST_IP::GATEWAY:NETMASK::IFACE:off osb.gateway=GATEWAY
+for param in $(cat /proc/cmdline); do
+ case "$param" in
+ ip=*)
+ IP_CONFIG="${param#ip=}"
+ GUEST_IP=$(echo "$IP_CONFIG" | cut -d: -f1)
+ GATEWAY=$(echo "$IP_CONFIG" | cut -d: -f3)
+ NETMASK=$(echo "$IP_CONFIG" | cut -d: -f4)
+ IFACE=$(echo "$IP_CONFIG" | cut -d: -f6)
+ ;;
+ osb.gateway=*)
+ GATEWAY="${param#osb.gateway=}"
+ ;;
+ esac
+done
+
+if [ -n "$GUEST_IP" ] && [ -n "$IFACE" ]; then
+ ip link set lo up
+ ip addr add "${GUEST_IP}/30" dev "$IFACE"
+ ip link set "$IFACE" up
+ if [ -n "$GATEWAY" ]; then
+ ip route add default via "$GATEWAY" dev "$IFACE"
+ fi
+fi
+
+# Set up DNS
+echo "nameserver 8.8.8.8" > /etc/resolv.conf
+echo "nameserver 8.8.4.4" >> /etc/resolv.conf
+
+# Set hostname
+hostname sandbox
+
+# Start the agent
+exec /usr/local/bin/osb-agent
+`
+}
+
+// copyFile copies a file from src to dst.
+func copyFile(src, dst string) error {
+ in, err := os.Open(src)
+ if err != nil {
+ return err
}
+ defer in.Close()
- username, password, err := ecr.GetAuthToken(ctx, b.ecrConfig)
+ out, err := os.Create(dst)
if err != nil {
- return fmt.Errorf("failed to get ECR auth: %w", err)
+ return err
+ }
+ defer out.Close()
+
+ if _, err := out.ReadFrom(in); err != nil {
+ return err
+ }
+
+ // Preserve execute permission
+ srcInfo, err := os.Stat(src)
+ if err == nil {
+ out.Chmod(srcInfo.Mode())
}
- return b.podman.LoginRegistry(ctx, b.ecrConfig.Registry, username, password)
+ return nil
}
diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.go
index 7180ad21..a68fbbe8 100644
--- a/internal/worker/grpc_server.go
+++ b/internal/worker/grpc_server.go
@@ -19,7 +19,7 @@ import (
// GRPCServer implements the SandboxWorker gRPC service for control plane communication.
type GRPCServer struct {
pb.UnimplementedSandboxWorkerServer
- manager *sandbox.Manager
+ manager sandbox.Manager
router *sandbox.SandboxRouter
ptyManager *sandbox.PTYManager
sandboxDBs *sandbox.SandboxDBManager
@@ -29,7 +29,7 @@ type GRPCServer struct {
}
// NewGRPCServer creates a new gRPC server wrapping the sandbox manager.
-func NewGRPCServer(mgr *sandbox.Manager, ptyMgr *sandbox.PTYManager, sandboxDBs *sandbox.SandboxDBManager, checkpointStore *storage.CheckpointStore, router *sandbox.SandboxRouter, builder *template.Builder) *GRPCServer {
+func NewGRPCServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, sandboxDBs *sandbox.SandboxDBManager, checkpointStore *storage.CheckpointStore, router *sandbox.SandboxRouter, builder *template.Builder) *GRPCServer {
s := &GRPCServer{
manager: mgr,
router: router,
diff --git a/internal/worker/http_server.go b/internal/worker/http_server.go
index a54dbace..0db0184f 100644
--- a/internal/worker/http_server.go
+++ b/internal/worker/http_server.go
@@ -15,7 +15,7 @@ import (
// It exposes the same endpoints as the control plane but authenticates via sandbox-scoped JWTs.
type HTTPServer struct {
echo *echo.Echo
- manager *sandbox.Manager
+ manager sandbox.Manager
ptyManager *sandbox.PTYManager
jwtIssuer *auth.JWTIssuer
sandboxDBs *sandbox.SandboxDBManager
@@ -24,7 +24,7 @@ type HTTPServer struct {
}
// NewHTTPServer creates a new worker HTTP server for direct SDK access.
-func NewHTTPServer(mgr *sandbox.Manager, ptyMgr *sandbox.PTYManager, jwtIssuer *auth.JWTIssuer, sandboxDBs *sandbox.SandboxDBManager, sbProxy *proxy.SandboxProxy, sbRouter *sandbox.SandboxRouter, sandboxDomain string) *HTTPServer {
+func NewHTTPServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, jwtIssuer *auth.JWTIssuer, sandboxDBs *sandbox.SandboxDBManager, sbProxy *proxy.SandboxProxy, sbRouter *sandbox.SandboxRouter, sandboxDomain string) *HTTPServer {
e := echo.New()
e.HideBanner = true
e.HidePort = true
diff --git a/proto/agent/agent.pb.go b/proto/agent/agent.pb.go
new file mode 100644
index 00000000..32d5165d
--- /dev/null
+++ b/proto/agent/agent.pb.go
@@ -0,0 +1,1848 @@
+// Code generated by protoc-gen-go. DO NOT EDIT.
+// versions:
+// protoc-gen-go v1.36.11
+// protoc v6.33.4
+// source: proto/agent/agent.proto
+
+package agent
+
+import (
+ protoreflect "google.golang.org/protobuf/reflect/protoreflect"
+ protoimpl "google.golang.org/protobuf/runtime/protoimpl"
+ reflect "reflect"
+ sync "sync"
+ unsafe "unsafe"
+)
+
+const (
+ // Verify that this generated code is sufficiently up-to-date.
+ _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
+ // Verify that runtime/protoimpl is sufficiently up-to-date.
+ _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
+)
+
+type ExecOutputChunk_Stream int32
+
+const (
+ ExecOutputChunk_STDOUT ExecOutputChunk_Stream = 0
+ ExecOutputChunk_STDERR ExecOutputChunk_Stream = 1
+)
+
+// Enum value maps for ExecOutputChunk_Stream.
+var (
+ ExecOutputChunk_Stream_name = map[int32]string{
+ 0: "STDOUT",
+ 1: "STDERR",
+ }
+ ExecOutputChunk_Stream_value = map[string]int32{
+ "STDOUT": 0,
+ "STDERR": 1,
+ }
+)
+
+func (x ExecOutputChunk_Stream) Enum() *ExecOutputChunk_Stream {
+ p := new(ExecOutputChunk_Stream)
+ *p = x
+ return p
+}
+
+func (x ExecOutputChunk_Stream) String() string {
+ return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
+}
+
+func (ExecOutputChunk_Stream) Descriptor() protoreflect.EnumDescriptor {
+ return file_proto_agent_agent_proto_enumTypes[0].Descriptor()
+}
+
+func (ExecOutputChunk_Stream) Type() protoreflect.EnumType {
+ return &file_proto_agent_agent_proto_enumTypes[0]
+}
+
+func (x ExecOutputChunk_Stream) Number() protoreflect.EnumNumber {
+ return protoreflect.EnumNumber(x)
+}
+
+// Deprecated: Use ExecOutputChunk_Stream.Descriptor instead.
+func (ExecOutputChunk_Stream) EnumDescriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{2, 0}
+}
+
+type ExecRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Command string `protobuf:"bytes,1,opt,name=command,proto3" json:"command,omitempty"`
+ Args []string `protobuf:"bytes,2,rep,name=args,proto3" json:"args,omitempty"`
+ Envs map[string]string `protobuf:"bytes,3,rep,name=envs,proto3" json:"envs,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+ Cwd string `protobuf:"bytes,4,opt,name=cwd,proto3" json:"cwd,omitempty"`
+ TimeoutSeconds int32 `protobuf:"varint,5,opt,name=timeout_seconds,json=timeoutSeconds,proto3" json:"timeout_seconds,omitempty"` // 0 = default (60s)
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ExecRequest) Reset() {
+ *x = ExecRequest{}
+ mi := &file_proto_agent_agent_proto_msgTypes[0]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ExecRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ExecRequest) ProtoMessage() {}
+
+func (x *ExecRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[0]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ExecRequest.ProtoReflect.Descriptor instead.
+func (*ExecRequest) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{0}
+}
+
+func (x *ExecRequest) GetCommand() string {
+ if x != nil {
+ return x.Command
+ }
+ return ""
+}
+
+func (x *ExecRequest) GetArgs() []string {
+ if x != nil {
+ return x.Args
+ }
+ return nil
+}
+
+func (x *ExecRequest) GetEnvs() map[string]string {
+ if x != nil {
+ return x.Envs
+ }
+ return nil
+}
+
+func (x *ExecRequest) GetCwd() string {
+ if x != nil {
+ return x.Cwd
+ }
+ return ""
+}
+
+func (x *ExecRequest) GetTimeoutSeconds() int32 {
+ if x != nil {
+ return x.TimeoutSeconds
+ }
+ return 0
+}
+
+type ExecResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ ExitCode int32 `protobuf:"varint,1,opt,name=exit_code,json=exitCode,proto3" json:"exit_code,omitempty"`
+ Stdout string `protobuf:"bytes,2,opt,name=stdout,proto3" json:"stdout,omitempty"`
+ Stderr string `protobuf:"bytes,3,opt,name=stderr,proto3" json:"stderr,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ExecResponse) Reset() {
+ *x = ExecResponse{}
+ mi := &file_proto_agent_agent_proto_msgTypes[1]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ExecResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ExecResponse) ProtoMessage() {}
+
+func (x *ExecResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[1]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ExecResponse.ProtoReflect.Descriptor instead.
+func (*ExecResponse) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{1}
+}
+
+func (x *ExecResponse) GetExitCode() int32 {
+ if x != nil {
+ return x.ExitCode
+ }
+ return 0
+}
+
+func (x *ExecResponse) GetStdout() string {
+ if x != nil {
+ return x.Stdout
+ }
+ return ""
+}
+
+func (x *ExecResponse) GetStderr() string {
+ if x != nil {
+ return x.Stderr
+ }
+ return ""
+}
+
+type ExecOutputChunk struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Stream ExecOutputChunk_Stream `protobuf:"varint,1,opt,name=stream,proto3,enum=agent.ExecOutputChunk_Stream" json:"stream,omitempty"`
+ Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ExecOutputChunk) Reset() {
+ *x = ExecOutputChunk{}
+ mi := &file_proto_agent_agent_proto_msgTypes[2]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ExecOutputChunk) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ExecOutputChunk) ProtoMessage() {}
+
+func (x *ExecOutputChunk) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[2]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ExecOutputChunk.ProtoReflect.Descriptor instead.
+func (*ExecOutputChunk) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{2}
+}
+
+func (x *ExecOutputChunk) GetStream() ExecOutputChunk_Stream {
+ if x != nil {
+ return x.Stream
+ }
+ return ExecOutputChunk_STDOUT
+}
+
+func (x *ExecOutputChunk) GetData() []byte {
+ if x != nil {
+ return x.Data
+ }
+ return nil
+}
+
+type ReadFileRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Path string `protobuf:"bytes,1,opt,name=path,proto3" json:"path,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ReadFileRequest) Reset() {
+ *x = ReadFileRequest{}
+ mi := &file_proto_agent_agent_proto_msgTypes[3]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ReadFileRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ReadFileRequest) ProtoMessage() {}
+
+func (x *ReadFileRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[3]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ReadFileRequest.ProtoReflect.Descriptor instead.
+func (*ReadFileRequest) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{3}
+}
+
+func (x *ReadFileRequest) GetPath() string {
+ if x != nil {
+ return x.Path
+ }
+ return ""
+}
+
+type ReadFileResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Content []byte `protobuf:"bytes,1,opt,name=content,proto3" json:"content,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ReadFileResponse) Reset() {
+ *x = ReadFileResponse{}
+ mi := &file_proto_agent_agent_proto_msgTypes[4]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ReadFileResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ReadFileResponse) ProtoMessage() {}
+
+func (x *ReadFileResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[4]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ReadFileResponse.ProtoReflect.Descriptor instead.
+func (*ReadFileResponse) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{4}
+}
+
+func (x *ReadFileResponse) GetContent() []byte {
+ if x != nil {
+ return x.Content
+ }
+ return nil
+}
+
+type WriteFileRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Path string `protobuf:"bytes,1,opt,name=path,proto3" json:"path,omitempty"`
+ Content []byte `protobuf:"bytes,2,opt,name=content,proto3" json:"content,omitempty"`
+ Mode uint32 `protobuf:"varint,3,opt,name=mode,proto3" json:"mode,omitempty"` // file mode (0 = default 0644)
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *WriteFileRequest) Reset() {
+ *x = WriteFileRequest{}
+ mi := &file_proto_agent_agent_proto_msgTypes[5]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *WriteFileRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*WriteFileRequest) ProtoMessage() {}
+
+func (x *WriteFileRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[5]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use WriteFileRequest.ProtoReflect.Descriptor instead.
+func (*WriteFileRequest) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{5}
+}
+
+func (x *WriteFileRequest) GetPath() string {
+ if x != nil {
+ return x.Path
+ }
+ return ""
+}
+
+func (x *WriteFileRequest) GetContent() []byte {
+ if x != nil {
+ return x.Content
+ }
+ return nil
+}
+
+func (x *WriteFileRequest) GetMode() uint32 {
+ if x != nil {
+ return x.Mode
+ }
+ return 0
+}
+
+type WriteFileResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *WriteFileResponse) Reset() {
+ *x = WriteFileResponse{}
+ mi := &file_proto_agent_agent_proto_msgTypes[6]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *WriteFileResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*WriteFileResponse) ProtoMessage() {}
+
+func (x *WriteFileResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[6]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use WriteFileResponse.ProtoReflect.Descriptor instead.
+func (*WriteFileResponse) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{6}
+}
+
+type ListDirRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Path string `protobuf:"bytes,1,opt,name=path,proto3" json:"path,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ListDirRequest) Reset() {
+ *x = ListDirRequest{}
+ mi := &file_proto_agent_agent_proto_msgTypes[7]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ListDirRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ListDirRequest) ProtoMessage() {}
+
+func (x *ListDirRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[7]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ListDirRequest.ProtoReflect.Descriptor instead.
+func (*ListDirRequest) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{7}
+}
+
+func (x *ListDirRequest) GetPath() string {
+ if x != nil {
+ return x.Path
+ }
+ return ""
+}
+
+type DirEntry struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
+ IsDir bool `protobuf:"varint,2,opt,name=is_dir,json=isDir,proto3" json:"is_dir,omitempty"`
+ Size int64 `protobuf:"varint,3,opt,name=size,proto3" json:"size,omitempty"`
+ Path string `protobuf:"bytes,4,opt,name=path,proto3" json:"path,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *DirEntry) Reset() {
+ *x = DirEntry{}
+ mi := &file_proto_agent_agent_proto_msgTypes[8]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *DirEntry) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*DirEntry) ProtoMessage() {}
+
+func (x *DirEntry) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[8]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use DirEntry.ProtoReflect.Descriptor instead.
+func (*DirEntry) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{8}
+}
+
+func (x *DirEntry) GetName() string {
+ if x != nil {
+ return x.Name
+ }
+ return ""
+}
+
+func (x *DirEntry) GetIsDir() bool {
+ if x != nil {
+ return x.IsDir
+ }
+ return false
+}
+
+func (x *DirEntry) GetSize() int64 {
+ if x != nil {
+ return x.Size
+ }
+ return 0
+}
+
+func (x *DirEntry) GetPath() string {
+ if x != nil {
+ return x.Path
+ }
+ return ""
+}
+
+type ListDirResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Entries []*DirEntry `protobuf:"bytes,1,rep,name=entries,proto3" json:"entries,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ListDirResponse) Reset() {
+ *x = ListDirResponse{}
+ mi := &file_proto_agent_agent_proto_msgTypes[9]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ListDirResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ListDirResponse) ProtoMessage() {}
+
+func (x *ListDirResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[9]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ListDirResponse.ProtoReflect.Descriptor instead.
+func (*ListDirResponse) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{9}
+}
+
+func (x *ListDirResponse) GetEntries() []*DirEntry {
+ if x != nil {
+ return x.Entries
+ }
+ return nil
+}
+
+type MakeDirRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Path string `protobuf:"bytes,1,opt,name=path,proto3" json:"path,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *MakeDirRequest) Reset() {
+ *x = MakeDirRequest{}
+ mi := &file_proto_agent_agent_proto_msgTypes[10]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *MakeDirRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*MakeDirRequest) ProtoMessage() {}
+
+func (x *MakeDirRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[10]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use MakeDirRequest.ProtoReflect.Descriptor instead.
+func (*MakeDirRequest) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{10}
+}
+
+func (x *MakeDirRequest) GetPath() string {
+ if x != nil {
+ return x.Path
+ }
+ return ""
+}
+
+type MakeDirResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *MakeDirResponse) Reset() {
+ *x = MakeDirResponse{}
+ mi := &file_proto_agent_agent_proto_msgTypes[11]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *MakeDirResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*MakeDirResponse) ProtoMessage() {}
+
+func (x *MakeDirResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[11]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use MakeDirResponse.ProtoReflect.Descriptor instead.
+func (*MakeDirResponse) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{11}
+}
+
+type RemoveRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Path string `protobuf:"bytes,1,opt,name=path,proto3" json:"path,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *RemoveRequest) Reset() {
+ *x = RemoveRequest{}
+ mi := &file_proto_agent_agent_proto_msgTypes[12]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *RemoveRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*RemoveRequest) ProtoMessage() {}
+
+func (x *RemoveRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[12]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use RemoveRequest.ProtoReflect.Descriptor instead.
+func (*RemoveRequest) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{12}
+}
+
+func (x *RemoveRequest) GetPath() string {
+ if x != nil {
+ return x.Path
+ }
+ return ""
+}
+
+type RemoveResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *RemoveResponse) Reset() {
+ *x = RemoveResponse{}
+ mi := &file_proto_agent_agent_proto_msgTypes[13]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *RemoveResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*RemoveResponse) ProtoMessage() {}
+
+func (x *RemoveResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[13]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use RemoveResponse.ProtoReflect.Descriptor instead.
+func (*RemoveResponse) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{13}
+}
+
+type ExistsRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Path string `protobuf:"bytes,1,opt,name=path,proto3" json:"path,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ExistsRequest) Reset() {
+ *x = ExistsRequest{}
+ mi := &file_proto_agent_agent_proto_msgTypes[14]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ExistsRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ExistsRequest) ProtoMessage() {}
+
+func (x *ExistsRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[14]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ExistsRequest.ProtoReflect.Descriptor instead.
+func (*ExistsRequest) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{14}
+}
+
+func (x *ExistsRequest) GetPath() string {
+ if x != nil {
+ return x.Path
+ }
+ return ""
+}
+
+type ExistsResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Exists bool `protobuf:"varint,1,opt,name=exists,proto3" json:"exists,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ExistsResponse) Reset() {
+ *x = ExistsResponse{}
+ mi := &file_proto_agent_agent_proto_msgTypes[15]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ExistsResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ExistsResponse) ProtoMessage() {}
+
+func (x *ExistsResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[15]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ExistsResponse.ProtoReflect.Descriptor instead.
+func (*ExistsResponse) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{15}
+}
+
+func (x *ExistsResponse) GetExists() bool {
+ if x != nil {
+ return x.Exists
+ }
+ return false
+}
+
+type StatRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Path string `protobuf:"bytes,1,opt,name=path,proto3" json:"path,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *StatRequest) Reset() {
+ *x = StatRequest{}
+ mi := &file_proto_agent_agent_proto_msgTypes[16]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *StatRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*StatRequest) ProtoMessage() {}
+
+func (x *StatRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[16]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use StatRequest.ProtoReflect.Descriptor instead.
+func (*StatRequest) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{16}
+}
+
+func (x *StatRequest) GetPath() string {
+ if x != nil {
+ return x.Path
+ }
+ return ""
+}
+
+type StatResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
+ IsDir bool `protobuf:"varint,2,opt,name=is_dir,json=isDir,proto3" json:"is_dir,omitempty"`
+ Size int64 `protobuf:"varint,3,opt,name=size,proto3" json:"size,omitempty"`
+ Mode string `protobuf:"bytes,4,opt,name=mode,proto3" json:"mode,omitempty"`
+ ModTime string `protobuf:"bytes,5,opt,name=mod_time,json=modTime,proto3" json:"mod_time,omitempty"`
+ Path string `protobuf:"bytes,6,opt,name=path,proto3" json:"path,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *StatResponse) Reset() {
+ *x = StatResponse{}
+ mi := &file_proto_agent_agent_proto_msgTypes[17]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *StatResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*StatResponse) ProtoMessage() {}
+
+func (x *StatResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[17]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use StatResponse.ProtoReflect.Descriptor instead.
+func (*StatResponse) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{17}
+}
+
+func (x *StatResponse) GetName() string {
+ if x != nil {
+ return x.Name
+ }
+ return ""
+}
+
+func (x *StatResponse) GetIsDir() bool {
+ if x != nil {
+ return x.IsDir
+ }
+ return false
+}
+
+func (x *StatResponse) GetSize() int64 {
+ if x != nil {
+ return x.Size
+ }
+ return 0
+}
+
+func (x *StatResponse) GetMode() string {
+ if x != nil {
+ return x.Mode
+ }
+ return ""
+}
+
+func (x *StatResponse) GetModTime() string {
+ if x != nil {
+ return x.ModTime
+ }
+ return ""
+}
+
+func (x *StatResponse) GetPath() string {
+ if x != nil {
+ return x.Path
+ }
+ return ""
+}
+
+type StatsRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *StatsRequest) Reset() {
+ *x = StatsRequest{}
+ mi := &file_proto_agent_agent_proto_msgTypes[18]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *StatsRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*StatsRequest) ProtoMessage() {}
+
+func (x *StatsRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[18]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use StatsRequest.ProtoReflect.Descriptor instead.
+func (*StatsRequest) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{18}
+}
+
+type StatsResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ CpuPercent float64 `protobuf:"fixed64,1,opt,name=cpu_percent,json=cpuPercent,proto3" json:"cpu_percent,omitempty"`
+ MemUsage uint64 `protobuf:"varint,2,opt,name=mem_usage,json=memUsage,proto3" json:"mem_usage,omitempty"` // bytes
+ MemLimit uint64 `protobuf:"varint,3,opt,name=mem_limit,json=memLimit,proto3" json:"mem_limit,omitempty"` // bytes
+ NetInput uint64 `protobuf:"varint,4,opt,name=net_input,json=netInput,proto3" json:"net_input,omitempty"` // bytes
+ NetOutput uint64 `protobuf:"varint,5,opt,name=net_output,json=netOutput,proto3" json:"net_output,omitempty"` // bytes
+ Pids int32 `protobuf:"varint,6,opt,name=pids,proto3" json:"pids,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *StatsResponse) Reset() {
+ *x = StatsResponse{}
+ mi := &file_proto_agent_agent_proto_msgTypes[19]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *StatsResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*StatsResponse) ProtoMessage() {}
+
+func (x *StatsResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[19]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use StatsResponse.ProtoReflect.Descriptor instead.
+func (*StatsResponse) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{19}
+}
+
+func (x *StatsResponse) GetCpuPercent() float64 {
+ if x != nil {
+ return x.CpuPercent
+ }
+ return 0
+}
+
+func (x *StatsResponse) GetMemUsage() uint64 {
+ if x != nil {
+ return x.MemUsage
+ }
+ return 0
+}
+
+func (x *StatsResponse) GetMemLimit() uint64 {
+ if x != nil {
+ return x.MemLimit
+ }
+ return 0
+}
+
+func (x *StatsResponse) GetNetInput() uint64 {
+ if x != nil {
+ return x.NetInput
+ }
+ return 0
+}
+
+func (x *StatsResponse) GetNetOutput() uint64 {
+ if x != nil {
+ return x.NetOutput
+ }
+ return 0
+}
+
+func (x *StatsResponse) GetPids() int32 {
+ if x != nil {
+ return x.Pids
+ }
+ return 0
+}
+
+type PingRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *PingRequest) Reset() {
+ *x = PingRequest{}
+ mi := &file_proto_agent_agent_proto_msgTypes[20]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *PingRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*PingRequest) ProtoMessage() {}
+
+func (x *PingRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[20]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use PingRequest.ProtoReflect.Descriptor instead.
+func (*PingRequest) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{20}
+}
+
+type PingResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Version string `protobuf:"bytes,1,opt,name=version,proto3" json:"version,omitempty"`
+ UptimeSeconds int64 `protobuf:"varint,2,opt,name=uptime_seconds,json=uptimeSeconds,proto3" json:"uptime_seconds,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *PingResponse) Reset() {
+ *x = PingResponse{}
+ mi := &file_proto_agent_agent_proto_msgTypes[21]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *PingResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*PingResponse) ProtoMessage() {}
+
+func (x *PingResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[21]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use PingResponse.ProtoReflect.Descriptor instead.
+func (*PingResponse) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{21}
+}
+
+func (x *PingResponse) GetVersion() string {
+ if x != nil {
+ return x.Version
+ }
+ return ""
+}
+
+func (x *PingResponse) GetUptimeSeconds() int64 {
+ if x != nil {
+ return x.UptimeSeconds
+ }
+ return 0
+}
+
+type PTYCreateRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Cols int32 `protobuf:"varint,1,opt,name=cols,proto3" json:"cols,omitempty"`
+ Rows int32 `protobuf:"varint,2,opt,name=rows,proto3" json:"rows,omitempty"`
+ Shell string `protobuf:"bytes,3,opt,name=shell,proto3" json:"shell,omitempty"` // e.g., "/bin/bash" (empty = default)
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *PTYCreateRequest) Reset() {
+ *x = PTYCreateRequest{}
+ mi := &file_proto_agent_agent_proto_msgTypes[22]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *PTYCreateRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*PTYCreateRequest) ProtoMessage() {}
+
+func (x *PTYCreateRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[22]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use PTYCreateRequest.ProtoReflect.Descriptor instead.
+func (*PTYCreateRequest) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{22}
+}
+
+func (x *PTYCreateRequest) GetCols() int32 {
+ if x != nil {
+ return x.Cols
+ }
+ return 0
+}
+
+func (x *PTYCreateRequest) GetRows() int32 {
+ if x != nil {
+ return x.Rows
+ }
+ return 0
+}
+
+func (x *PTYCreateRequest) GetShell() string {
+ if x != nil {
+ return x.Shell
+ }
+ return ""
+}
+
+type PTYCreateResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ SessionId string `protobuf:"bytes,1,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"`
+ DataPort uint32 `protobuf:"varint,2,opt,name=data_port,json=dataPort,proto3" json:"data_port,omitempty"` // vsock port for raw PTY I/O stream
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *PTYCreateResponse) Reset() {
+ *x = PTYCreateResponse{}
+ mi := &file_proto_agent_agent_proto_msgTypes[23]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *PTYCreateResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*PTYCreateResponse) ProtoMessage() {}
+
+func (x *PTYCreateResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[23]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use PTYCreateResponse.ProtoReflect.Descriptor instead.
+func (*PTYCreateResponse) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{23}
+}
+
+func (x *PTYCreateResponse) GetSessionId() string {
+ if x != nil {
+ return x.SessionId
+ }
+ return ""
+}
+
+func (x *PTYCreateResponse) GetDataPort() uint32 {
+ if x != nil {
+ return x.DataPort
+ }
+ return 0
+}
+
+type PTYResizeRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ SessionId string `protobuf:"bytes,1,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"`
+ Cols int32 `protobuf:"varint,2,opt,name=cols,proto3" json:"cols,omitempty"`
+ Rows int32 `protobuf:"varint,3,opt,name=rows,proto3" json:"rows,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *PTYResizeRequest) Reset() {
+ *x = PTYResizeRequest{}
+ mi := &file_proto_agent_agent_proto_msgTypes[24]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *PTYResizeRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*PTYResizeRequest) ProtoMessage() {}
+
+func (x *PTYResizeRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[24]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use PTYResizeRequest.ProtoReflect.Descriptor instead.
+func (*PTYResizeRequest) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{24}
+}
+
+func (x *PTYResizeRequest) GetSessionId() string {
+ if x != nil {
+ return x.SessionId
+ }
+ return ""
+}
+
+func (x *PTYResizeRequest) GetCols() int32 {
+ if x != nil {
+ return x.Cols
+ }
+ return 0
+}
+
+func (x *PTYResizeRequest) GetRows() int32 {
+ if x != nil {
+ return x.Rows
+ }
+ return 0
+}
+
+type PTYResizeResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *PTYResizeResponse) Reset() {
+ *x = PTYResizeResponse{}
+ mi := &file_proto_agent_agent_proto_msgTypes[25]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *PTYResizeResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*PTYResizeResponse) ProtoMessage() {}
+
+func (x *PTYResizeResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[25]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use PTYResizeResponse.ProtoReflect.Descriptor instead.
+func (*PTYResizeResponse) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{25}
+}
+
+type PTYKillRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ SessionId string `protobuf:"bytes,1,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *PTYKillRequest) Reset() {
+ *x = PTYKillRequest{}
+ mi := &file_proto_agent_agent_proto_msgTypes[26]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *PTYKillRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*PTYKillRequest) ProtoMessage() {}
+
+func (x *PTYKillRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[26]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use PTYKillRequest.ProtoReflect.Descriptor instead.
+func (*PTYKillRequest) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{26}
+}
+
+func (x *PTYKillRequest) GetSessionId() string {
+ if x != nil {
+ return x.SessionId
+ }
+ return ""
+}
+
+type PTYKillResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *PTYKillResponse) Reset() {
+ *x = PTYKillResponse{}
+ mi := &file_proto_agent_agent_proto_msgTypes[27]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *PTYKillResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*PTYKillResponse) ProtoMessage() {}
+
+func (x *PTYKillResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[27]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use PTYKillResponse.ProtoReflect.Descriptor instead.
+func (*PTYKillResponse) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{27}
+}
+
+type ShutdownRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ShutdownRequest) Reset() {
+ *x = ShutdownRequest{}
+ mi := &file_proto_agent_agent_proto_msgTypes[28]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ShutdownRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ShutdownRequest) ProtoMessage() {}
+
+func (x *ShutdownRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[28]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ShutdownRequest.ProtoReflect.Descriptor instead.
+func (*ShutdownRequest) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{28}
+}
+
+type ShutdownResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ShutdownResponse) Reset() {
+ *x = ShutdownResponse{}
+ mi := &file_proto_agent_agent_proto_msgTypes[29]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ShutdownResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ShutdownResponse) ProtoMessage() {}
+
+func (x *ShutdownResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[29]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ShutdownResponse.ProtoReflect.Descriptor instead.
+func (*ShutdownResponse) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{29}
+}
+
+type SyncFSRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *SyncFSRequest) Reset() {
+ *x = SyncFSRequest{}
+ mi := &file_proto_agent_agent_proto_msgTypes[30]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *SyncFSRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*SyncFSRequest) ProtoMessage() {}
+
+func (x *SyncFSRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[30]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use SyncFSRequest.ProtoReflect.Descriptor instead.
+func (*SyncFSRequest) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{30}
+}
+
+type SyncFSResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *SyncFSResponse) Reset() {
+ *x = SyncFSResponse{}
+ mi := &file_proto_agent_agent_proto_msgTypes[31]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *SyncFSResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*SyncFSResponse) ProtoMessage() {}
+
+func (x *SyncFSResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_agent_agent_proto_msgTypes[31]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use SyncFSResponse.ProtoReflect.Descriptor instead.
+func (*SyncFSResponse) Descriptor() ([]byte, []int) {
+ return file_proto_agent_agent_proto_rawDescGZIP(), []int{31}
+}
+
+var File_proto_agent_agent_proto protoreflect.FileDescriptor
+
+const file_proto_agent_agent_proto_rawDesc = "" +
+ "\n" +
+ "\x17proto/agent/agent.proto\x12\x05agent\"\xe1\x01\n" +
+ "\vExecRequest\x12\x18\n" +
+ "\acommand\x18\x01 \x01(\tR\acommand\x12\x12\n" +
+ "\x04args\x18\x02 \x03(\tR\x04args\x120\n" +
+ "\x04envs\x18\x03 \x03(\v2\x1c.agent.ExecRequest.EnvsEntryR\x04envs\x12\x10\n" +
+ "\x03cwd\x18\x04 \x01(\tR\x03cwd\x12'\n" +
+ "\x0ftimeout_seconds\x18\x05 \x01(\x05R\x0etimeoutSeconds\x1a7\n" +
+ "\tEnvsEntry\x12\x10\n" +
+ "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
+ "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"[\n" +
+ "\fExecResponse\x12\x1b\n" +
+ "\texit_code\x18\x01 \x01(\x05R\bexitCode\x12\x16\n" +
+ "\x06stdout\x18\x02 \x01(\tR\x06stdout\x12\x16\n" +
+ "\x06stderr\x18\x03 \x01(\tR\x06stderr\"~\n" +
+ "\x0fExecOutputChunk\x125\n" +
+ "\x06stream\x18\x01 \x01(\x0e2\x1d.agent.ExecOutputChunk.StreamR\x06stream\x12\x12\n" +
+ "\x04data\x18\x02 \x01(\fR\x04data\" \n" +
+ "\x06Stream\x12\n" +
+ "\n" +
+ "\x06STDOUT\x10\x00\x12\n" +
+ "\n" +
+ "\x06STDERR\x10\x01\"%\n" +
+ "\x0fReadFileRequest\x12\x12\n" +
+ "\x04path\x18\x01 \x01(\tR\x04path\",\n" +
+ "\x10ReadFileResponse\x12\x18\n" +
+ "\acontent\x18\x01 \x01(\fR\acontent\"T\n" +
+ "\x10WriteFileRequest\x12\x12\n" +
+ "\x04path\x18\x01 \x01(\tR\x04path\x12\x18\n" +
+ "\acontent\x18\x02 \x01(\fR\acontent\x12\x12\n" +
+ "\x04mode\x18\x03 \x01(\rR\x04mode\"\x13\n" +
+ "\x11WriteFileResponse\"$\n" +
+ "\x0eListDirRequest\x12\x12\n" +
+ "\x04path\x18\x01 \x01(\tR\x04path\"]\n" +
+ "\bDirEntry\x12\x12\n" +
+ "\x04name\x18\x01 \x01(\tR\x04name\x12\x15\n" +
+ "\x06is_dir\x18\x02 \x01(\bR\x05isDir\x12\x12\n" +
+ "\x04size\x18\x03 \x01(\x03R\x04size\x12\x12\n" +
+ "\x04path\x18\x04 \x01(\tR\x04path\"<\n" +
+ "\x0fListDirResponse\x12)\n" +
+ "\aentries\x18\x01 \x03(\v2\x0f.agent.DirEntryR\aentries\"$\n" +
+ "\x0eMakeDirRequest\x12\x12\n" +
+ "\x04path\x18\x01 \x01(\tR\x04path\"\x11\n" +
+ "\x0fMakeDirResponse\"#\n" +
+ "\rRemoveRequest\x12\x12\n" +
+ "\x04path\x18\x01 \x01(\tR\x04path\"\x10\n" +
+ "\x0eRemoveResponse\"#\n" +
+ "\rExistsRequest\x12\x12\n" +
+ "\x04path\x18\x01 \x01(\tR\x04path\"(\n" +
+ "\x0eExistsResponse\x12\x16\n" +
+ "\x06exists\x18\x01 \x01(\bR\x06exists\"!\n" +
+ "\vStatRequest\x12\x12\n" +
+ "\x04path\x18\x01 \x01(\tR\x04path\"\x90\x01\n" +
+ "\fStatResponse\x12\x12\n" +
+ "\x04name\x18\x01 \x01(\tR\x04name\x12\x15\n" +
+ "\x06is_dir\x18\x02 \x01(\bR\x05isDir\x12\x12\n" +
+ "\x04size\x18\x03 \x01(\x03R\x04size\x12\x12\n" +
+ "\x04mode\x18\x04 \x01(\tR\x04mode\x12\x19\n" +
+ "\bmod_time\x18\x05 \x01(\tR\amodTime\x12\x12\n" +
+ "\x04path\x18\x06 \x01(\tR\x04path\"\x0e\n" +
+ "\fStatsRequest\"\xba\x01\n" +
+ "\rStatsResponse\x12\x1f\n" +
+ "\vcpu_percent\x18\x01 \x01(\x01R\n" +
+ "cpuPercent\x12\x1b\n" +
+ "\tmem_usage\x18\x02 \x01(\x04R\bmemUsage\x12\x1b\n" +
+ "\tmem_limit\x18\x03 \x01(\x04R\bmemLimit\x12\x1b\n" +
+ "\tnet_input\x18\x04 \x01(\x04R\bnetInput\x12\x1d\n" +
+ "\n" +
+ "net_output\x18\x05 \x01(\x04R\tnetOutput\x12\x12\n" +
+ "\x04pids\x18\x06 \x01(\x05R\x04pids\"\r\n" +
+ "\vPingRequest\"O\n" +
+ "\fPingResponse\x12\x18\n" +
+ "\aversion\x18\x01 \x01(\tR\aversion\x12%\n" +
+ "\x0euptime_seconds\x18\x02 \x01(\x03R\ruptimeSeconds\"P\n" +
+ "\x10PTYCreateRequest\x12\x12\n" +
+ "\x04cols\x18\x01 \x01(\x05R\x04cols\x12\x12\n" +
+ "\x04rows\x18\x02 \x01(\x05R\x04rows\x12\x14\n" +
+ "\x05shell\x18\x03 \x01(\tR\x05shell\"O\n" +
+ "\x11PTYCreateResponse\x12\x1d\n" +
+ "\n" +
+ "session_id\x18\x01 \x01(\tR\tsessionId\x12\x1b\n" +
+ "\tdata_port\x18\x02 \x01(\rR\bdataPort\"Y\n" +
+ "\x10PTYResizeRequest\x12\x1d\n" +
+ "\n" +
+ "session_id\x18\x01 \x01(\tR\tsessionId\x12\x12\n" +
+ "\x04cols\x18\x02 \x01(\x05R\x04cols\x12\x12\n" +
+ "\x04rows\x18\x03 \x01(\x05R\x04rows\"\x13\n" +
+ "\x11PTYResizeResponse\"/\n" +
+ "\x0ePTYKillRequest\x12\x1d\n" +
+ "\n" +
+ "session_id\x18\x01 \x01(\tR\tsessionId\"\x11\n" +
+ "\x0fPTYKillResponse\"\x11\n" +
+ "\x0fShutdownRequest\"\x12\n" +
+ "\x10ShutdownResponse\"\x0f\n" +
+ "\rSyncFSRequest\"\x10\n" +
+ "\x0eSyncFSResponse2\x9e\a\n" +
+ "\fSandboxAgent\x12/\n" +
+ "\x04Exec\x12\x12.agent.ExecRequest\x1a\x13.agent.ExecResponse\x12:\n" +
+ "\n" +
+ "ExecStream\x12\x12.agent.ExecRequest\x1a\x16.agent.ExecOutputChunk0\x01\x12;\n" +
+ "\bReadFile\x12\x16.agent.ReadFileRequest\x1a\x17.agent.ReadFileResponse\x12>\n" +
+ "\tWriteFile\x12\x17.agent.WriteFileRequest\x1a\x18.agent.WriteFileResponse\x128\n" +
+ "\aListDir\x12\x15.agent.ListDirRequest\x1a\x16.agent.ListDirResponse\x128\n" +
+ "\aMakeDir\x12\x15.agent.MakeDirRequest\x1a\x16.agent.MakeDirResponse\x125\n" +
+ "\x06Remove\x12\x14.agent.RemoveRequest\x1a\x15.agent.RemoveResponse\x125\n" +
+ "\x06Exists\x12\x14.agent.ExistsRequest\x1a\x15.agent.ExistsResponse\x12/\n" +
+ "\x04Stat\x12\x12.agent.StatRequest\x1a\x13.agent.StatResponse\x122\n" +
+ "\x05Stats\x12\x13.agent.StatsRequest\x1a\x14.agent.StatsResponse\x12/\n" +
+ "\x04Ping\x12\x12.agent.PingRequest\x1a\x13.agent.PingResponse\x12>\n" +
+ "\tPTYCreate\x12\x17.agent.PTYCreateRequest\x1a\x18.agent.PTYCreateResponse\x12>\n" +
+ "\tPTYResize\x12\x17.agent.PTYResizeRequest\x1a\x18.agent.PTYResizeResponse\x128\n" +
+ "\aPTYKill\x12\x15.agent.PTYKillRequest\x1a\x16.agent.PTYKillResponse\x12;\n" +
+ "\bShutdown\x12\x16.agent.ShutdownRequest\x1a\x17.agent.ShutdownResponse\x125\n" +
+ "\x06SyncFS\x12\x14.agent.SyncFSRequest\x1a\x15.agent.SyncFSResponseB0Z.github.com/opensandbox/opensandbox/proto/agentb\x06proto3"
+
+var (
+ file_proto_agent_agent_proto_rawDescOnce sync.Once
+ file_proto_agent_agent_proto_rawDescData []byte
+)
+
+func file_proto_agent_agent_proto_rawDescGZIP() []byte {
+ file_proto_agent_agent_proto_rawDescOnce.Do(func() {
+ file_proto_agent_agent_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_proto_agent_agent_proto_rawDesc), len(file_proto_agent_agent_proto_rawDesc)))
+ })
+ return file_proto_agent_agent_proto_rawDescData
+}
+
+var file_proto_agent_agent_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
+var file_proto_agent_agent_proto_msgTypes = make([]protoimpl.MessageInfo, 33)
+var file_proto_agent_agent_proto_goTypes = []any{
+ (ExecOutputChunk_Stream)(0), // 0: agent.ExecOutputChunk.Stream
+ (*ExecRequest)(nil), // 1: agent.ExecRequest
+ (*ExecResponse)(nil), // 2: agent.ExecResponse
+ (*ExecOutputChunk)(nil), // 3: agent.ExecOutputChunk
+ (*ReadFileRequest)(nil), // 4: agent.ReadFileRequest
+ (*ReadFileResponse)(nil), // 5: agent.ReadFileResponse
+ (*WriteFileRequest)(nil), // 6: agent.WriteFileRequest
+ (*WriteFileResponse)(nil), // 7: agent.WriteFileResponse
+ (*ListDirRequest)(nil), // 8: agent.ListDirRequest
+ (*DirEntry)(nil), // 9: agent.DirEntry
+ (*ListDirResponse)(nil), // 10: agent.ListDirResponse
+ (*MakeDirRequest)(nil), // 11: agent.MakeDirRequest
+ (*MakeDirResponse)(nil), // 12: agent.MakeDirResponse
+ (*RemoveRequest)(nil), // 13: agent.RemoveRequest
+ (*RemoveResponse)(nil), // 14: agent.RemoveResponse
+ (*ExistsRequest)(nil), // 15: agent.ExistsRequest
+ (*ExistsResponse)(nil), // 16: agent.ExistsResponse
+ (*StatRequest)(nil), // 17: agent.StatRequest
+ (*StatResponse)(nil), // 18: agent.StatResponse
+ (*StatsRequest)(nil), // 19: agent.StatsRequest
+ (*StatsResponse)(nil), // 20: agent.StatsResponse
+ (*PingRequest)(nil), // 21: agent.PingRequest
+ (*PingResponse)(nil), // 22: agent.PingResponse
+ (*PTYCreateRequest)(nil), // 23: agent.PTYCreateRequest
+ (*PTYCreateResponse)(nil), // 24: agent.PTYCreateResponse
+ (*PTYResizeRequest)(nil), // 25: agent.PTYResizeRequest
+ (*PTYResizeResponse)(nil), // 26: agent.PTYResizeResponse
+ (*PTYKillRequest)(nil), // 27: agent.PTYKillRequest
+ (*PTYKillResponse)(nil), // 28: agent.PTYKillResponse
+ (*ShutdownRequest)(nil), // 29: agent.ShutdownRequest
+ (*ShutdownResponse)(nil), // 30: agent.ShutdownResponse
+ (*SyncFSRequest)(nil), // 31: agent.SyncFSRequest
+ (*SyncFSResponse)(nil), // 32: agent.SyncFSResponse
+ nil, // 33: agent.ExecRequest.EnvsEntry
+}
+var file_proto_agent_agent_proto_depIdxs = []int32{
+ 33, // 0: agent.ExecRequest.envs:type_name -> agent.ExecRequest.EnvsEntry
+ 0, // 1: agent.ExecOutputChunk.stream:type_name -> agent.ExecOutputChunk.Stream
+ 9, // 2: agent.ListDirResponse.entries:type_name -> agent.DirEntry
+ 1, // 3: agent.SandboxAgent.Exec:input_type -> agent.ExecRequest
+ 1, // 4: agent.SandboxAgent.ExecStream:input_type -> agent.ExecRequest
+ 4, // 5: agent.SandboxAgent.ReadFile:input_type -> agent.ReadFileRequest
+ 6, // 6: agent.SandboxAgent.WriteFile:input_type -> agent.WriteFileRequest
+ 8, // 7: agent.SandboxAgent.ListDir:input_type -> agent.ListDirRequest
+ 11, // 8: agent.SandboxAgent.MakeDir:input_type -> agent.MakeDirRequest
+ 13, // 9: agent.SandboxAgent.Remove:input_type -> agent.RemoveRequest
+ 15, // 10: agent.SandboxAgent.Exists:input_type -> agent.ExistsRequest
+ 17, // 11: agent.SandboxAgent.Stat:input_type -> agent.StatRequest
+ 19, // 12: agent.SandboxAgent.Stats:input_type -> agent.StatsRequest
+ 21, // 13: agent.SandboxAgent.Ping:input_type -> agent.PingRequest
+ 23, // 14: agent.SandboxAgent.PTYCreate:input_type -> agent.PTYCreateRequest
+ 25, // 15: agent.SandboxAgent.PTYResize:input_type -> agent.PTYResizeRequest
+ 27, // 16: agent.SandboxAgent.PTYKill:input_type -> agent.PTYKillRequest
+ 29, // 17: agent.SandboxAgent.Shutdown:input_type -> agent.ShutdownRequest
+ 31, // 18: agent.SandboxAgent.SyncFS:input_type -> agent.SyncFSRequest
+ 2, // 19: agent.SandboxAgent.Exec:output_type -> agent.ExecResponse
+ 3, // 20: agent.SandboxAgent.ExecStream:output_type -> agent.ExecOutputChunk
+ 5, // 21: agent.SandboxAgent.ReadFile:output_type -> agent.ReadFileResponse
+ 7, // 22: agent.SandboxAgent.WriteFile:output_type -> agent.WriteFileResponse
+ 10, // 23: agent.SandboxAgent.ListDir:output_type -> agent.ListDirResponse
+ 12, // 24: agent.SandboxAgent.MakeDir:output_type -> agent.MakeDirResponse
+ 14, // 25: agent.SandboxAgent.Remove:output_type -> agent.RemoveResponse
+ 16, // 26: agent.SandboxAgent.Exists:output_type -> agent.ExistsResponse
+ 18, // 27: agent.SandboxAgent.Stat:output_type -> agent.StatResponse
+ 20, // 28: agent.SandboxAgent.Stats:output_type -> agent.StatsResponse
+ 22, // 29: agent.SandboxAgent.Ping:output_type -> agent.PingResponse
+ 24, // 30: agent.SandboxAgent.PTYCreate:output_type -> agent.PTYCreateResponse
+ 26, // 31: agent.SandboxAgent.PTYResize:output_type -> agent.PTYResizeResponse
+ 28, // 32: agent.SandboxAgent.PTYKill:output_type -> agent.PTYKillResponse
+ 30, // 33: agent.SandboxAgent.Shutdown:output_type -> agent.ShutdownResponse
+ 32, // 34: agent.SandboxAgent.SyncFS:output_type -> agent.SyncFSResponse
+ 19, // [19:35] is the sub-list for method output_type
+ 3, // [3:19] is the sub-list for method input_type
+ 3, // [3:3] is the sub-list for extension type_name
+ 3, // [3:3] is the sub-list for extension extendee
+ 0, // [0:3] is the sub-list for field type_name
+}
+
+func init() { file_proto_agent_agent_proto_init() }
+func file_proto_agent_agent_proto_init() {
+ if File_proto_agent_agent_proto != nil {
+ return
+ }
+ type x struct{}
+ out := protoimpl.TypeBuilder{
+ File: protoimpl.DescBuilder{
+ GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
+ RawDescriptor: unsafe.Slice(unsafe.StringData(file_proto_agent_agent_proto_rawDesc), len(file_proto_agent_agent_proto_rawDesc)),
+ NumEnums: 1,
+ NumMessages: 33,
+ NumExtensions: 0,
+ NumServices: 1,
+ },
+ GoTypes: file_proto_agent_agent_proto_goTypes,
+ DependencyIndexes: file_proto_agent_agent_proto_depIdxs,
+ EnumInfos: file_proto_agent_agent_proto_enumTypes,
+ MessageInfos: file_proto_agent_agent_proto_msgTypes,
+ }.Build()
+ File_proto_agent_agent_proto = out.File
+ file_proto_agent_agent_proto_goTypes = nil
+ file_proto_agent_agent_proto_depIdxs = nil
+}
diff --git a/proto/agent/agent.proto b/proto/agent/agent.proto
new file mode 100644
index 00000000..92c5aa4a
--- /dev/null
+++ b/proto/agent/agent.proto
@@ -0,0 +1,194 @@
+syntax = "proto3";
+
+package agent;
+
+option go_package = "github.com/opensandbox/opensandbox/proto/agent";
+
+// SandboxAgent runs inside each Firecracker microVM and handles
+// exec, file ops, PTY, and stats over gRPC via vsock.
+service SandboxAgent {
+ // Exec runs a command and returns the result after completion.
+ rpc Exec(ExecRequest) returns (ExecResponse);
+
+ // ExecStream runs a command and streams stdout/stderr chunks in real time.
+ rpc ExecStream(ExecRequest) returns (stream ExecOutputChunk);
+
+ // Filesystem operations
+ rpc ReadFile(ReadFileRequest) returns (ReadFileResponse);
+ rpc WriteFile(WriteFileRequest) returns (WriteFileResponse);
+ rpc ListDir(ListDirRequest) returns (ListDirResponse);
+ rpc MakeDir(MakeDirRequest) returns (MakeDirResponse);
+ rpc Remove(RemoveRequest) returns (RemoveResponse);
+ rpc Exists(ExistsRequest) returns (ExistsResponse);
+ rpc Stat(StatRequest) returns (StatResponse);
+
+ // Stats returns live resource usage from /proc.
+ rpc Stats(StatsRequest) returns (StatsResponse);
+
+ // Ping verifies the agent is responsive.
+ rpc Ping(PingRequest) returns (PingResponse);
+
+ // PTY management (data flows over a separate vsock port per session)
+ rpc PTYCreate(PTYCreateRequest) returns (PTYCreateResponse);
+ rpc PTYResize(PTYResizeRequest) returns (PTYResizeResponse);
+ rpc PTYKill(PTYKillRequest) returns (PTYKillResponse);
+
+ // Shutdown gracefully terminates the agent and syncs disks.
+ rpc Shutdown(ShutdownRequest) returns (ShutdownResponse);
+
+ // SyncFS flushes all filesystem buffers without exiting.
+ // Used before snapshot to ensure disk state is consistent.
+ rpc SyncFS(SyncFSRequest) returns (SyncFSResponse);
+}
+
+// --- Exec ---
+
+message ExecRequest {
+ string command = 1;
+ repeated string args = 2;
+ map<string, string> envs = 3;
+ string cwd = 4;
+ int32 timeout_seconds = 5; // 0 = default (60s)
+}
+
+message ExecResponse {
+ int32 exit_code = 1;
+ string stdout = 2;
+ string stderr = 3;
+}
+
+message ExecOutputChunk {
+ enum Stream {
+ STDOUT = 0;
+ STDERR = 1;
+ }
+ Stream stream = 1;
+ bytes data = 2;
+}
+
+// --- Filesystem ---
+
+message ReadFileRequest {
+ string path = 1;
+}
+
+message ReadFileResponse {
+ bytes content = 1;
+}
+
+message WriteFileRequest {
+ string path = 1;
+ bytes content = 2;
+ uint32 mode = 3; // file mode (0 = default 0644)
+}
+
+message WriteFileResponse {}
+
+message ListDirRequest {
+ string path = 1;
+}
+
+message DirEntry {
+ string name = 1;
+ bool is_dir = 2;
+ int64 size = 3;
+ string path = 4;
+}
+
+message ListDirResponse {
+ repeated DirEntry entries = 1;
+}
+
+message MakeDirRequest {
+ string path = 1;
+}
+
+message MakeDirResponse {}
+
+message RemoveRequest {
+ string path = 1;
+}
+
+message RemoveResponse {}
+
+message ExistsRequest {
+ string path = 1;
+}
+
+message ExistsResponse {
+ bool exists = 1;
+}
+
+message StatRequest {
+ string path = 1;
+}
+
+message StatResponse {
+ string name = 1;
+ bool is_dir = 2;
+ int64 size = 3;
+ string mode = 4;
+ string mod_time = 5;
+ string path = 6;
+}
+
+// --- Stats ---
+
+message StatsRequest {}
+
+message StatsResponse {
+ double cpu_percent = 1;
+ uint64 mem_usage = 2; // bytes
+ uint64 mem_limit = 3; // bytes
+ uint64 net_input = 4; // bytes
+ uint64 net_output = 5; // bytes
+ int32 pids = 6;
+}
+
+// --- Ping ---
+
+message PingRequest {}
+
+message PingResponse {
+ string version = 1;
+ int64 uptime_seconds = 2;
+}
+
+// --- PTY ---
+
+message PTYCreateRequest {
+ int32 cols = 1;
+ int32 rows = 2;
+ string shell = 3; // e.g., "/bin/bash" (empty = default)
+}
+
+message PTYCreateResponse {
+ string session_id = 1;
+ uint32 data_port = 2; // vsock port for raw PTY I/O stream
+}
+
+message PTYResizeRequest {
+ string session_id = 1;
+ int32 cols = 2;
+ int32 rows = 3;
+}
+
+message PTYResizeResponse {}
+
+message PTYKillRequest {
+ string session_id = 1;
+}
+
+message PTYKillResponse {}
+
+// --- Shutdown ---
+
+message ShutdownRequest {}
+
+message ShutdownResponse {}
+
+// --- SyncFS ---
+
+message SyncFSRequest {}
+
+message SyncFSResponse {}
diff --git a/proto/agent/agent_grpc.pb.go b/proto/agent/agent_grpc.pb.go
new file mode 100644
index 00000000..6beca548
--- /dev/null
+++ b/proto/agent/agent_grpc.pb.go
@@ -0,0 +1,719 @@
+// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
+// versions:
+// - protoc-gen-go-grpc v1.6.1
+// - protoc v6.33.4
+// source: proto/agent/agent.proto
+
+package agent
+
+import (
+ context "context"
+ grpc "google.golang.org/grpc"
+ codes "google.golang.org/grpc/codes"
+ status "google.golang.org/grpc/status"
+)
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the grpc package it is being compiled against.
+// Requires gRPC-Go v1.64.0 or later.
+const _ = grpc.SupportPackageIsVersion9
+
+const (
+ SandboxAgent_Exec_FullMethodName = "/agent.SandboxAgent/Exec"
+ SandboxAgent_ExecStream_FullMethodName = "/agent.SandboxAgent/ExecStream"
+ SandboxAgent_ReadFile_FullMethodName = "/agent.SandboxAgent/ReadFile"
+ SandboxAgent_WriteFile_FullMethodName = "/agent.SandboxAgent/WriteFile"
+ SandboxAgent_ListDir_FullMethodName = "/agent.SandboxAgent/ListDir"
+ SandboxAgent_MakeDir_FullMethodName = "/agent.SandboxAgent/MakeDir"
+ SandboxAgent_Remove_FullMethodName = "/agent.SandboxAgent/Remove"
+ SandboxAgent_Exists_FullMethodName = "/agent.SandboxAgent/Exists"
+ SandboxAgent_Stat_FullMethodName = "/agent.SandboxAgent/Stat"
+ SandboxAgent_Stats_FullMethodName = "/agent.SandboxAgent/Stats"
+ SandboxAgent_Ping_FullMethodName = "/agent.SandboxAgent/Ping"
+ SandboxAgent_PTYCreate_FullMethodName = "/agent.SandboxAgent/PTYCreate"
+ SandboxAgent_PTYResize_FullMethodName = "/agent.SandboxAgent/PTYResize"
+ SandboxAgent_PTYKill_FullMethodName = "/agent.SandboxAgent/PTYKill"
+ SandboxAgent_Shutdown_FullMethodName = "/agent.SandboxAgent/Shutdown"
+ SandboxAgent_SyncFS_FullMethodName = "/agent.SandboxAgent/SyncFS"
+)
+
+// SandboxAgentClient is the client API for SandboxAgent service.
+//
+// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
+//
+// SandboxAgent runs inside each Firecracker microVM and handles
+// exec, file ops, PTY, and stats over gRPC via vsock.
+type SandboxAgentClient interface {
+ // Exec runs a command and returns the result after completion.
+ Exec(ctx context.Context, in *ExecRequest, opts ...grpc.CallOption) (*ExecResponse, error)
+ // ExecStream runs a command and streams stdout/stderr chunks in real time.
+ ExecStream(ctx context.Context, in *ExecRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[ExecOutputChunk], error)
+ // Filesystem operations
+ ReadFile(ctx context.Context, in *ReadFileRequest, opts ...grpc.CallOption) (*ReadFileResponse, error)
+ WriteFile(ctx context.Context, in *WriteFileRequest, opts ...grpc.CallOption) (*WriteFileResponse, error)
+ ListDir(ctx context.Context, in *ListDirRequest, opts ...grpc.CallOption) (*ListDirResponse, error)
+ MakeDir(ctx context.Context, in *MakeDirRequest, opts ...grpc.CallOption) (*MakeDirResponse, error)
+ Remove(ctx context.Context, in *RemoveRequest, opts ...grpc.CallOption) (*RemoveResponse, error)
+ Exists(ctx context.Context, in *ExistsRequest, opts ...grpc.CallOption) (*ExistsResponse, error)
+ Stat(ctx context.Context, in *StatRequest, opts ...grpc.CallOption) (*StatResponse, error)
+ // Stats returns live resource usage from /proc.
+ Stats(ctx context.Context, in *StatsRequest, opts ...grpc.CallOption) (*StatsResponse, error)
+ // Ping verifies the agent is responsive.
+ Ping(ctx context.Context, in *PingRequest, opts ...grpc.CallOption) (*PingResponse, error)
+ // PTY management (data flows over a separate vsock port per session)
+ PTYCreate(ctx context.Context, in *PTYCreateRequest, opts ...grpc.CallOption) (*PTYCreateResponse, error)
+ PTYResize(ctx context.Context, in *PTYResizeRequest, opts ...grpc.CallOption) (*PTYResizeResponse, error)
+ PTYKill(ctx context.Context, in *PTYKillRequest, opts ...grpc.CallOption) (*PTYKillResponse, error)
+ // Shutdown gracefully terminates the agent and syncs disks.
+ Shutdown(ctx context.Context, in *ShutdownRequest, opts ...grpc.CallOption) (*ShutdownResponse, error)
+ // SyncFS flushes all filesystem buffers without exiting.
+ // Used before snapshot to ensure disk state is consistent.
+ SyncFS(ctx context.Context, in *SyncFSRequest, opts ...grpc.CallOption) (*SyncFSResponse, error)
+}
+
+type sandboxAgentClient struct {
+ cc grpc.ClientConnInterface
+}
+
+func NewSandboxAgentClient(cc grpc.ClientConnInterface) SandboxAgentClient {
+ return &sandboxAgentClient{cc}
+}
+
+func (c *sandboxAgentClient) Exec(ctx context.Context, in *ExecRequest, opts ...grpc.CallOption) (*ExecResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(ExecResponse)
+ err := c.cc.Invoke(ctx, SandboxAgent_Exec_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *sandboxAgentClient) ExecStream(ctx context.Context, in *ExecRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[ExecOutputChunk], error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ stream, err := c.cc.NewStream(ctx, &SandboxAgent_ServiceDesc.Streams[0], SandboxAgent_ExecStream_FullMethodName, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ x := &grpc.GenericClientStream[ExecRequest, ExecOutputChunk]{ClientStream: stream}
+ if err := x.ClientStream.SendMsg(in); err != nil {
+ return nil, err
+ }
+ if err := x.ClientStream.CloseSend(); err != nil {
+ return nil, err
+ }
+ return x, nil
+}
+
+// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
+type SandboxAgent_ExecStreamClient = grpc.ServerStreamingClient[ExecOutputChunk]
+
+func (c *sandboxAgentClient) ReadFile(ctx context.Context, in *ReadFileRequest, opts ...grpc.CallOption) (*ReadFileResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(ReadFileResponse)
+ err := c.cc.Invoke(ctx, SandboxAgent_ReadFile_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *sandboxAgentClient) WriteFile(ctx context.Context, in *WriteFileRequest, opts ...grpc.CallOption) (*WriteFileResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(WriteFileResponse)
+ err := c.cc.Invoke(ctx, SandboxAgent_WriteFile_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *sandboxAgentClient) ListDir(ctx context.Context, in *ListDirRequest, opts ...grpc.CallOption) (*ListDirResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(ListDirResponse)
+ err := c.cc.Invoke(ctx, SandboxAgent_ListDir_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *sandboxAgentClient) MakeDir(ctx context.Context, in *MakeDirRequest, opts ...grpc.CallOption) (*MakeDirResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(MakeDirResponse)
+ err := c.cc.Invoke(ctx, SandboxAgent_MakeDir_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *sandboxAgentClient) Remove(ctx context.Context, in *RemoveRequest, opts ...grpc.CallOption) (*RemoveResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(RemoveResponse)
+ err := c.cc.Invoke(ctx, SandboxAgent_Remove_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *sandboxAgentClient) Exists(ctx context.Context, in *ExistsRequest, opts ...grpc.CallOption) (*ExistsResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(ExistsResponse)
+ err := c.cc.Invoke(ctx, SandboxAgent_Exists_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *sandboxAgentClient) Stat(ctx context.Context, in *StatRequest, opts ...grpc.CallOption) (*StatResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(StatResponse)
+ err := c.cc.Invoke(ctx, SandboxAgent_Stat_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *sandboxAgentClient) Stats(ctx context.Context, in *StatsRequest, opts ...grpc.CallOption) (*StatsResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(StatsResponse)
+ err := c.cc.Invoke(ctx, SandboxAgent_Stats_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *sandboxAgentClient) Ping(ctx context.Context, in *PingRequest, opts ...grpc.CallOption) (*PingResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(PingResponse)
+ err := c.cc.Invoke(ctx, SandboxAgent_Ping_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *sandboxAgentClient) PTYCreate(ctx context.Context, in *PTYCreateRequest, opts ...grpc.CallOption) (*PTYCreateResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(PTYCreateResponse)
+ err := c.cc.Invoke(ctx, SandboxAgent_PTYCreate_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *sandboxAgentClient) PTYResize(ctx context.Context, in *PTYResizeRequest, opts ...grpc.CallOption) (*PTYResizeResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(PTYResizeResponse)
+ err := c.cc.Invoke(ctx, SandboxAgent_PTYResize_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *sandboxAgentClient) PTYKill(ctx context.Context, in *PTYKillRequest, opts ...grpc.CallOption) (*PTYKillResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(PTYKillResponse)
+ err := c.cc.Invoke(ctx, SandboxAgent_PTYKill_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *sandboxAgentClient) Shutdown(ctx context.Context, in *ShutdownRequest, opts ...grpc.CallOption) (*ShutdownResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(ShutdownResponse)
+ err := c.cc.Invoke(ctx, SandboxAgent_Shutdown_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *sandboxAgentClient) SyncFS(ctx context.Context, in *SyncFSRequest, opts ...grpc.CallOption) (*SyncFSResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(SyncFSResponse)
+ err := c.cc.Invoke(ctx, SandboxAgent_SyncFS_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+// SandboxAgentServer is the server API for SandboxAgent service.
+// All implementations must embed UnimplementedSandboxAgentServer
+// for forward compatibility.
+//
+// SandboxAgent runs inside each Firecracker microVM and handles
+// exec, file ops, PTY, and stats over gRPC via vsock.
+type SandboxAgentServer interface {
+ // Exec runs a command and returns the result after completion.
+ Exec(context.Context, *ExecRequest) (*ExecResponse, error)
+ // ExecStream runs a command and streams stdout/stderr chunks in real time.
+ ExecStream(*ExecRequest, grpc.ServerStreamingServer[ExecOutputChunk]) error
+ // Filesystem operations
+ ReadFile(context.Context, *ReadFileRequest) (*ReadFileResponse, error)
+ WriteFile(context.Context, *WriteFileRequest) (*WriteFileResponse, error)
+ ListDir(context.Context, *ListDirRequest) (*ListDirResponse, error)
+ MakeDir(context.Context, *MakeDirRequest) (*MakeDirResponse, error)
+ Remove(context.Context, *RemoveRequest) (*RemoveResponse, error)
+ Exists(context.Context, *ExistsRequest) (*ExistsResponse, error)
+ Stat(context.Context, *StatRequest) (*StatResponse, error)
+ // Stats returns live resource usage from /proc.
+ Stats(context.Context, *StatsRequest) (*StatsResponse, error)
+ // Ping verifies the agent is responsive.
+ Ping(context.Context, *PingRequest) (*PingResponse, error)
+ // PTY management (data flows over a separate vsock port per session)
+ PTYCreate(context.Context, *PTYCreateRequest) (*PTYCreateResponse, error)
+ PTYResize(context.Context, *PTYResizeRequest) (*PTYResizeResponse, error)
+ PTYKill(context.Context, *PTYKillRequest) (*PTYKillResponse, error)
+ // Shutdown gracefully terminates the agent and syncs disks.
+ Shutdown(context.Context, *ShutdownRequest) (*ShutdownResponse, error)
+ // SyncFS flushes all filesystem buffers without exiting.
+ // Used before snapshot to ensure disk state is consistent.
+ SyncFS(context.Context, *SyncFSRequest) (*SyncFSResponse, error)
+ mustEmbedUnimplementedSandboxAgentServer()
+}
+
+// UnimplementedSandboxAgentServer must be embedded to have
+// forward compatible implementations.
+//
+// NOTE: this should be embedded by value instead of pointer to avoid a nil
+// pointer dereference when methods are called.
+type UnimplementedSandboxAgentServer struct{}
+
+func (UnimplementedSandboxAgentServer) Exec(context.Context, *ExecRequest) (*ExecResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method Exec not implemented")
+}
+func (UnimplementedSandboxAgentServer) ExecStream(*ExecRequest, grpc.ServerStreamingServer[ExecOutputChunk]) error {
+ return status.Error(codes.Unimplemented, "method ExecStream not implemented")
+}
+func (UnimplementedSandboxAgentServer) ReadFile(context.Context, *ReadFileRequest) (*ReadFileResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method ReadFile not implemented")
+}
+func (UnimplementedSandboxAgentServer) WriteFile(context.Context, *WriteFileRequest) (*WriteFileResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method WriteFile not implemented")
+}
+func (UnimplementedSandboxAgentServer) ListDir(context.Context, *ListDirRequest) (*ListDirResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method ListDir not implemented")
+}
+func (UnimplementedSandboxAgentServer) MakeDir(context.Context, *MakeDirRequest) (*MakeDirResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method MakeDir not implemented")
+}
+func (UnimplementedSandboxAgentServer) Remove(context.Context, *RemoveRequest) (*RemoveResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method Remove not implemented")
+}
+func (UnimplementedSandboxAgentServer) Exists(context.Context, *ExistsRequest) (*ExistsResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method Exists not implemented")
+}
+func (UnimplementedSandboxAgentServer) Stat(context.Context, *StatRequest) (*StatResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method Stat not implemented")
+}
+func (UnimplementedSandboxAgentServer) Stats(context.Context, *StatsRequest) (*StatsResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method Stats not implemented")
+}
+func (UnimplementedSandboxAgentServer) Ping(context.Context, *PingRequest) (*PingResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method Ping not implemented")
+}
+func (UnimplementedSandboxAgentServer) PTYCreate(context.Context, *PTYCreateRequest) (*PTYCreateResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method PTYCreate not implemented")
+}
+func (UnimplementedSandboxAgentServer) PTYResize(context.Context, *PTYResizeRequest) (*PTYResizeResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method PTYResize not implemented")
+}
+func (UnimplementedSandboxAgentServer) PTYKill(context.Context, *PTYKillRequest) (*PTYKillResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method PTYKill not implemented")
+}
+func (UnimplementedSandboxAgentServer) Shutdown(context.Context, *ShutdownRequest) (*ShutdownResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method Shutdown not implemented")
+}
+func (UnimplementedSandboxAgentServer) SyncFS(context.Context, *SyncFSRequest) (*SyncFSResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method SyncFS not implemented")
+}
+func (UnimplementedSandboxAgentServer) mustEmbedUnimplementedSandboxAgentServer() {}
+func (UnimplementedSandboxAgentServer) testEmbeddedByValue() {}
+
+// UnsafeSandboxAgentServer may be embedded to opt out of forward compatibility for this service.
+// Use of this interface is not recommended, as added methods to SandboxAgentServer will
+// result in compilation errors.
+type UnsafeSandboxAgentServer interface {
+ mustEmbedUnimplementedSandboxAgentServer()
+}
+
+func RegisterSandboxAgentServer(s grpc.ServiceRegistrar, srv SandboxAgentServer) {
+ // If the following call panics, it indicates UnimplementedSandboxAgentServer was
+ // embedded by pointer and is nil. This will cause panics if an
+ // unimplemented method is ever invoked, so we test this at initialization
+ // time to prevent it from happening at runtime later due to I/O.
+ if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
+ t.testEmbeddedByValue()
+ }
+ s.RegisterService(&SandboxAgent_ServiceDesc, srv)
+}
+
+func _SandboxAgent_Exec_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(ExecRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(SandboxAgentServer).Exec(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: SandboxAgent_Exec_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(SandboxAgentServer).Exec(ctx, req.(*ExecRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _SandboxAgent_ExecStream_Handler(srv interface{}, stream grpc.ServerStream) error {
+ m := new(ExecRequest)
+ if err := stream.RecvMsg(m); err != nil {
+ return err
+ }
+ return srv.(SandboxAgentServer).ExecStream(m, &grpc.GenericServerStream[ExecRequest, ExecOutputChunk]{ServerStream: stream})
+}
+
+// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
+type SandboxAgent_ExecStreamServer = grpc.ServerStreamingServer[ExecOutputChunk]
+
+func _SandboxAgent_ReadFile_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(ReadFileRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(SandboxAgentServer).ReadFile(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: SandboxAgent_ReadFile_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(SandboxAgentServer).ReadFile(ctx, req.(*ReadFileRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _SandboxAgent_WriteFile_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(WriteFileRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(SandboxAgentServer).WriteFile(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: SandboxAgent_WriteFile_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(SandboxAgentServer).WriteFile(ctx, req.(*WriteFileRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _SandboxAgent_ListDir_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(ListDirRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(SandboxAgentServer).ListDir(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: SandboxAgent_ListDir_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(SandboxAgentServer).ListDir(ctx, req.(*ListDirRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _SandboxAgent_MakeDir_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(MakeDirRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(SandboxAgentServer).MakeDir(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: SandboxAgent_MakeDir_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(SandboxAgentServer).MakeDir(ctx, req.(*MakeDirRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _SandboxAgent_Remove_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(RemoveRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(SandboxAgentServer).Remove(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: SandboxAgent_Remove_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(SandboxAgentServer).Remove(ctx, req.(*RemoveRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _SandboxAgent_Exists_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(ExistsRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(SandboxAgentServer).Exists(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: SandboxAgent_Exists_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(SandboxAgentServer).Exists(ctx, req.(*ExistsRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _SandboxAgent_Stat_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(StatRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(SandboxAgentServer).Stat(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: SandboxAgent_Stat_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(SandboxAgentServer).Stat(ctx, req.(*StatRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _SandboxAgent_Stats_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(StatsRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(SandboxAgentServer).Stats(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: SandboxAgent_Stats_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(SandboxAgentServer).Stats(ctx, req.(*StatsRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _SandboxAgent_Ping_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(PingRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(SandboxAgentServer).Ping(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: SandboxAgent_Ping_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(SandboxAgentServer).Ping(ctx, req.(*PingRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _SandboxAgent_PTYCreate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(PTYCreateRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(SandboxAgentServer).PTYCreate(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: SandboxAgent_PTYCreate_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(SandboxAgentServer).PTYCreate(ctx, req.(*PTYCreateRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _SandboxAgent_PTYResize_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(PTYResizeRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(SandboxAgentServer).PTYResize(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: SandboxAgent_PTYResize_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(SandboxAgentServer).PTYResize(ctx, req.(*PTYResizeRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _SandboxAgent_PTYKill_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(PTYKillRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(SandboxAgentServer).PTYKill(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: SandboxAgent_PTYKill_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(SandboxAgentServer).PTYKill(ctx, req.(*PTYKillRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _SandboxAgent_Shutdown_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(ShutdownRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(SandboxAgentServer).Shutdown(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: SandboxAgent_Shutdown_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(SandboxAgentServer).Shutdown(ctx, req.(*ShutdownRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _SandboxAgent_SyncFS_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(SyncFSRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(SandboxAgentServer).SyncFS(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: SandboxAgent_SyncFS_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(SandboxAgentServer).SyncFS(ctx, req.(*SyncFSRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+// SandboxAgent_ServiceDesc is the grpc.ServiceDesc for SandboxAgent service.
+// It's only intended for direct use with grpc.RegisterService,
+// and not to be introspected or modified (even as a copy)
+var SandboxAgent_ServiceDesc = grpc.ServiceDesc{
+ ServiceName: "agent.SandboxAgent",
+ HandlerType: (*SandboxAgentServer)(nil),
+ Methods: []grpc.MethodDesc{
+ {
+ MethodName: "Exec",
+ Handler: _SandboxAgent_Exec_Handler,
+ },
+ {
+ MethodName: "ReadFile",
+ Handler: _SandboxAgent_ReadFile_Handler,
+ },
+ {
+ MethodName: "WriteFile",
+ Handler: _SandboxAgent_WriteFile_Handler,
+ },
+ {
+ MethodName: "ListDir",
+ Handler: _SandboxAgent_ListDir_Handler,
+ },
+ {
+ MethodName: "MakeDir",
+ Handler: _SandboxAgent_MakeDir_Handler,
+ },
+ {
+ MethodName: "Remove",
+ Handler: _SandboxAgent_Remove_Handler,
+ },
+ {
+ MethodName: "Exists",
+ Handler: _SandboxAgent_Exists_Handler,
+ },
+ {
+ MethodName: "Stat",
+ Handler: _SandboxAgent_Stat_Handler,
+ },
+ {
+ MethodName: "Stats",
+ Handler: _SandboxAgent_Stats_Handler,
+ },
+ {
+ MethodName: "Ping",
+ Handler: _SandboxAgent_Ping_Handler,
+ },
+ {
+ MethodName: "PTYCreate",
+ Handler: _SandboxAgent_PTYCreate_Handler,
+ },
+ {
+ MethodName: "PTYResize",
+ Handler: _SandboxAgent_PTYResize_Handler,
+ },
+ {
+ MethodName: "PTYKill",
+ Handler: _SandboxAgent_PTYKill_Handler,
+ },
+ {
+ MethodName: "Shutdown",
+ Handler: _SandboxAgent_Shutdown_Handler,
+ },
+ {
+ MethodName: "SyncFS",
+ Handler: _SandboxAgent_SyncFS_Handler,
+ },
+ },
+ Streams: []grpc.StreamDesc{
+ {
+ StreamName: "ExecStream",
+ Handler: _SandboxAgent_ExecStream_Handler,
+ ServerStreams: true,
+ },
+ },
+ Metadata: "proto/agent/agent.proto",
+}
diff --git a/scripts/bench-grpc.sh b/scripts/bench-grpc.sh
new file mode 100644
index 00000000..d7a03afa
--- /dev/null
+++ b/scripts/bench-grpc.sh
@@ -0,0 +1,225 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+# Benchmark sandbox launch times via gRPC (runs on worker directly).
+#
+# Tests:
+# 1. Fresh launch (cold start)
+# 2. Hibernate → local wake (snapshot restore, same machine)
+# 3. Hibernate → purge local → S3 wake (snapshot restore, cross-machine)
+# 4. Process survival verification (the "money test")
+#
+# Usage: ./scripts/bench-grpc.sh <worker-ssh> <ssh-key>
+# Example: ./scripts/bench-grpc.sh [email protected] ~/.ssh/opensandbox-digger.pem
+
+WORKER_SSH="${1:?Usage: $0 <user@host> <ssh-key>}"
+SSH_KEY="${2:?Usage: $0 <user@host> <ssh-key>}"
+
+SSH="ssh -i $SSH_KEY -o StrictHostKeyChecking=no $WORKER_SSH"
+
+# Colors
+RED='\033[0;31m'
+GREEN='\033[0;32m'
+YELLOW='\033[1;33m'
+CYAN='\033[0;36m'
+BOLD='\033[1m'
+NC='\033[0m'
+
+header() { echo -e "\n${BOLD}${CYAN}═══════════════════════════════════════════════════${NC}"; echo -e "${BOLD}${CYAN} $1${NC}"; echo -e "${BOLD}${CYAN}═══════════════════════════════════════════════════${NC}"; }
+info() { echo -e "${YELLOW}→${NC} $1"; }
+ok() { echo -e "${GREEN}✓${NC} $1"; }
+fail() { echo -e "${RED}✗${NC} $1"; }
+timing() { echo -e "${BOLD}${GREEN} ⏱ $1${NC}"; }
+
+grpc() {
+ $SSH "grpcurl -plaintext -import-path /tmp -proto worker.proto $* localhost:9090"
+}
+
+# Ensure grpcurl + proto are available on the worker
+info "Checking worker prerequisites..."
+$SSH "which grpcurl > /dev/null 2>&1" || { fail "grpcurl not found on worker"; exit 1; }
+$SSH "test -f /tmp/worker.proto" || { fail "/tmp/worker.proto not found on worker — upload it first"; exit 1; }
+
+# ─────────────────────────────────────────────────────
+header "BENCHMARK: Firecracker Snapshot Launch Times"
+echo -e "Worker: ${WORKER_SSH}"
+echo ""
+
+# ─────────────────────────────────────────────────────
+header "TEST 1: Fresh Launch (cold start)"
+info "Creating sandbox from ubuntu template..."
+
+T_START=$(python3 -c 'import time; print(time.time())')
+
+CREATE_RESP=$($SSH 'grpcurl -plaintext -import-path /tmp -proto worker.proto \
+ -d '"'"'{"template":"ubuntu","timeout":600,"cpu_count":1,"memory_mb":512}'"'"' \
+ localhost:9090 worker.SandboxWorker/CreateSandbox' 2>&1)
+
+T_END=$(python3 -c 'import time; print(time.time())')
+FRESH_MS=$(python3 -c "print(f'{($T_END - $T_START) * 1000:.0f}')")
+
+SANDBOX_ID=$(echo "$CREATE_RESP" | python3 -c "import sys,json; print(json.load(sys.stdin)['sandboxId'])")
+STATUS=$(echo "$CREATE_RESP" | python3 -c "import sys,json; print(json.load(sys.stdin)['status'])")
+
+ok "Sandbox created: ${SANDBOX_ID} (status: ${STATUS})"
+timing "Fresh launch: ${FRESH_MS}ms"
+
+# Write test data + start background process
+info "Writing state and starting background process..."
+$SSH 'grpcurl -plaintext -import-path /tmp -proto worker.proto \
+ -d '"'"'{"sandbox_id":"'"$SANDBOX_ID"'","command":"sh","args":["-c","echo benchmark-marker-12345 > /workspace/bench.txt && date +%s > /workspace/bench-time.txt"]}'"'"' \
+ localhost:9090 worker.SandboxWorker/ExecCommand' > /dev/null 2>&1
+
+$SSH 'grpcurl -plaintext -import-path /tmp -proto worker.proto \
+ -d '"'"'{"sandbox_id":"'"$SANDBOX_ID"'","command":"sh","args":["-c","setsid sleep 9999 </dev/null >/dev/null 2>&1 & echo STARTED"]}'"'"' \
+ localhost:9090 worker.SandboxWorker/ExecCommand' > /dev/null 2>&1
+
+# Get PID
+PID_RESP=$($SSH 'grpcurl -plaintext -import-path /tmp -proto worker.proto \
+ -d '"'"'{"sandbox_id":"'"$SANDBOX_ID"'","command":"pgrep","args":["sleep"],"timeout":3}'"'"' \
+ localhost:9090 worker.SandboxWorker/ExecCommand' 2>&1)
+SLEEP_PIDS=$(echo "$PID_RESP" | python3 -c "import sys,json; print(json.load(sys.stdin).get('stdout','').strip())" 2>/dev/null || echo "none")
+
+ok "Background sleep PIDs: $(echo $SLEEP_PIDS | tr '\n' ' ')"
+
+# Verify state
+MARKER=$($SSH 'grpcurl -plaintext -import-path /tmp -proto worker.proto \
+ -d '"'"'{"sandbox_id":"'"$SANDBOX_ID"'","command":"cat","args":["/workspace/bench.txt"],"timeout":3}'"'"' \
+ localhost:9090 worker.SandboxWorker/ExecCommand' 2>&1 | python3 -c "import sys,json; print(json.load(sys.stdin).get('stdout','').strip())" 2>/dev/null || echo "")
+
+if [[ "$MARKER" == "benchmark-marker-12345" ]]; then
+ ok "State verified"
+else
+ fail "State verification failed (got: $MARKER)"
+fi
+
+sleep 1
+
+# ─────────────────────────────────────────────────────
+header "TEST 2: Hibernate → Wake (local snapshot restore)"
+info "Hibernating sandbox ${SANDBOX_ID}..."
+
+T_START=$(python3 -c 'import time; print(time.time())')
+
+HIB_RESP=$($SSH 'grpcurl -plaintext -import-path /tmp -proto worker.proto \
+ -d '"'"'{"sandbox_id":"'"$SANDBOX_ID"'"}'"'"' \
+ localhost:9090 worker.SandboxWorker/HibernateSandbox' 2>&1)
+
+T_END=$(python3 -c 'import time; print(time.time())')
+HIB_MS=$(python3 -c "print(f'{($T_END - $T_START) * 1000:.0f}')")
+
+CP_KEY=$(echo "$HIB_RESP" | python3 -c "import sys,json; print(json.load(sys.stdin)['checkpointKey'])")
+CP_SIZE=$(echo "$HIB_RESP" | python3 -c "import sys,json; print(json.load(sys.stdin).get('sizeBytes','0'))")
+CP_SIZE_MB=$(python3 -c "print(f'{int(\"$CP_SIZE\") / 1024 / 1024:.1f}')")
+
+ok "Hibernated (checkpoint: ${CP_SIZE_MB} MB, key: ${CP_KEY})"
+timing "Hibernate: ${HIB_MS}ms"
+
+sleep 1
+
+info "Waking sandbox (local snapshot restore)..."
+T_START=$(python3 -c 'import time; print(time.time())')
+
+WAKE_RESP=$($SSH 'grpcurl -plaintext -import-path /tmp -proto worker.proto \
+ -d '"'"'{"sandbox_id":"'"$SANDBOX_ID"'","checkpoint_key":"'"$CP_KEY"'","timeout":600}'"'"' \
+ localhost:9090 worker.SandboxWorker/WakeSandbox' 2>&1)
+
+T_END=$(python3 -c 'import time; print(time.time())')
+LOCAL_WAKE_MS=$(python3 -c "print(f'{($T_END - $T_START) * 1000:.0f}')")
+
+ok "Woke from local snapshot"
+timing "Local wake: ${LOCAL_WAKE_MS}ms"
+
+# Verify process survival
+info "Verifying process survival after snapshot restore..."
+PIDS_AFTER=$($SSH 'grpcurl -plaintext -import-path /tmp -proto worker.proto \
+ -d '"'"'{"sandbox_id":"'"$SANDBOX_ID"'","command":"pgrep","args":["sleep"],"timeout":3}'"'"' \
+ localhost:9090 worker.SandboxWorker/ExecCommand' 2>&1 | python3 -c "import sys,json; print(json.load(sys.stdin).get('stdout','').strip())" 2>/dev/null || echo "none")
+
+if [[ "$PIDS_AFTER" == "$SLEEP_PIDS" ]]; then
+ ok "Process survival verified — PIDs match: $(echo $PIDS_AFTER | tr '\n' ' ')"
+else
+ fail "PID mismatch — before: $(echo $SLEEP_PIDS | tr '\n' ' '), after: $(echo $PIDS_AFTER | tr '\n' ' ')"
+fi
+
+# Verify state
+MARKER=$($SSH 'grpcurl -plaintext -import-path /tmp -proto worker.proto \
+ -d '"'"'{"sandbox_id":"'"$SANDBOX_ID"'","command":"cat","args":["/workspace/bench.txt"],"timeout":3}'"'"' \
+ localhost:9090 worker.SandboxWorker/ExecCommand' 2>&1 | python3 -c "import sys,json; print(json.load(sys.stdin).get('stdout','').strip())" 2>/dev/null || echo "")
+
+if [[ "$MARKER" == "benchmark-marker-12345" ]]; then
+ ok "Workspace state verified after wake"
+else
+ fail "Workspace state lost (got: $MARKER)"
+fi
+
+sleep 1
+
+# ─────────────────────────────────────────────────────
+header "TEST 3: Hibernate → Purge Local → Wake (S3 restore)"
+info "Hibernating sandbox again..."
+
+T_START=$(python3 -c 'import time; print(time.time())')
+
+HIB2_RESP=$($SSH 'grpcurl -plaintext -import-path /tmp -proto worker.proto \
+ -d '"'"'{"sandbox_id":"'"$SANDBOX_ID"'"}'"'"' \
+ localhost:9090 worker.SandboxWorker/HibernateSandbox' 2>&1)
+
+T_END=$(python3 -c 'import time; print(time.time())')
+HIB2_MS=$(python3 -c "print(f'{($T_END - $T_START) * 1000:.0f}')")
+
+CP_KEY2=$(echo "$HIB2_RESP" | python3 -c "import sys,json; print(json.load(sys.stdin)['checkpointKey'])")
+ok "Hibernated"
+timing "Hibernate: ${HIB2_MS}ms"
+
+# Purge local snapshot files to force S3 download
+info "Purging local snapshot files to force S3 restore..."
+$SSH "sudo rm -rf /data/sandboxes/sandboxes/${SANDBOX_ID}/snapshot/" 2>/dev/null || true
+ok "Local snapshot files purged"
+
+sleep 1
+
+info "Waking sandbox (must pull snapshot from S3)..."
+T_START=$(python3 -c 'import time; print(time.time())')
+
+WAKE2_RESP=$($SSH 'grpcurl -plaintext -import-path /tmp -proto worker.proto \
+ -d '"'"'{"sandbox_id":"'"$SANDBOX_ID"'","checkpoint_key":"'"$CP_KEY2"'","timeout":600}'"'"' \
+ localhost:9090 worker.SandboxWorker/WakeSandbox' 2>&1)
+
+T_END=$(python3 -c 'import time; print(time.time())')
+S3_WAKE_MS=$(python3 -c "print(f'{($T_END - $T_START) * 1000:.0f}')")
+
+ok "Woke from S3 snapshot"
+timing "S3 wake: ${S3_WAKE_MS}ms"
+
+# Verify process survival through S3 round-trip
+info "Verifying process survival after S3 restore..."
+PIDS_S3=$($SSH 'grpcurl -plaintext -import-path /tmp -proto worker.proto \
+ -d '"'"'{"sandbox_id":"'"$SANDBOX_ID"'","command":"pgrep","args":["sleep"],"timeout":3}'"'"' \
+ localhost:9090 worker.SandboxWorker/ExecCommand' 2>&1 | python3 -c "import sys,json; print(json.load(sys.stdin).get('stdout','').strip())" 2>/dev/null || echo "none")
+
+if [[ "$PIDS_S3" == "$SLEEP_PIDS" ]]; then
+ ok "Process survival verified after S3 restore — PIDs: $(echo $PIDS_S3 | tr '\n' ' ')"
+else
+ fail "PID mismatch — original: $(echo $SLEEP_PIDS | tr '\n' ' '), S3 restore: $(echo $PIDS_S3 | tr '\n' ' ')"
+fi
+
+# ─────────────────────────────────────────────────────
+# Cleanup
+info "Cleaning up — destroying sandbox..."
+$SSH 'grpcurl -plaintext -import-path /tmp -proto worker.proto \
+ -d '"'"'{"sandbox_id":"'"$SANDBOX_ID"'"}'"'"' \
+ localhost:9090 worker.SandboxWorker/DestroySandbox' > /dev/null 2>&1 || true
+
+# ─────────────────────────────────────────────────────
+header "RESULTS"
+echo ""
+echo -e " ${BOLD}Fresh launch (cold start):${NC} ${BOLD}${GREEN}${FRESH_MS}ms${NC}"
+echo -e " ${BOLD}Hibernate:${NC} ${HIB_MS}ms (snapshot: ${CP_SIZE_MB} MB)"
+echo -e " ${BOLD}Wake (local snapshot):${NC} ${BOLD}${GREEN}${LOCAL_WAKE_MS}ms${NC} (process survival: ✓)"
+echo -e " ${BOLD}Hibernate (2nd):${NC} ${HIB2_MS}ms"
+echo -e " ${BOLD}Wake (S3 snapshot):${NC} ${BOLD}${GREEN}${S3_WAKE_MS}ms${NC} (process survival: ✓)"
+echo ""
+echo -e " ${CYAN}Speedup local vs fresh:${NC} $(python3 -c "print(f'{int(\"$FRESH_MS\") / max(int(\"$LOCAL_WAKE_MS\"), 1):.1f}')") x"
+echo -e " ${CYAN}Speedup S3 vs fresh:${NC} $(python3 -c "print(f'{int(\"$FRESH_MS\") / max(int(\"$S3_WAKE_MS\"), 1):.1f}')") x"
+echo ""
diff --git a/scripts/bench-heavy.sh b/scripts/bench-heavy.sh
index 6273b498..eec47adb 100755
--- a/scripts/bench-heavy.sh
+++ b/scripts/bench-heavy.sh
@@ -1,7 +1,7 @@
#!/usr/bin/env bash
set -euo pipefail
-# Heavy benchmark: sandbox with running processes + 2GB user data.
+# Heavy benchmark: sandbox with running processes + 2GB user data on workspace.
#
# Compares:
# 1. Fresh launch + full setup (install packages, start processes, write 2GB)
@@ -36,20 +36,10 @@ parse_response() {
[[ "$http_code" -lt 400 ]] || { fail "HTTP $http_code: $body"; return 1; }
}
-run_cmd() {
- # run_cmd <sandbox_id> <bash_command> [timeout_secs]
- local sid="$1" cmd="$2" tout="${3:-30}"
- local resp
- resp=$(curl -s --max-time "$tout" -X POST "${EXEC_URL}/sandboxes/${sid}/commands" \
- -H "${AUTH_HEADER}" -H "Content-Type: application/json" \
- -d "$(python3 -c "import json; print(json.dumps({'cmd':'bash','args':['-c',$(python3 -c "import json; print(json.dumps('$cmd'))")]}))") ")
- echo "$resp"
-}
-
run_cmd_raw() {
- # Passes a raw JSON body — use for complex commands with quotes
- local sid="$1" json_body="$2" tout="${3:-30}"
- curl -s --max-time "$tout" -X POST "${EXEC_URL}/sandboxes/${sid}/commands" \
+ # Passes a raw JSON body — no client-side timeout, let the command finish
+ local sid="$1" json_body="$2"
+ curl -s -X POST "${EXEC_URL}/sandboxes/${sid}/commands" \
-H "${AUTH_HEADER}" -H "Content-Type: application/json" \
-d "$json_body"
}
@@ -94,48 +84,62 @@ fi
ok "Sandbox created: ${SANDBOX_ID} on ${WORKER_ID} (${CREATE_MS}ms)"
# --- Install packages ---
-info "Installing packages (python packages, curl, etc.)..."
+info "Installing system packages (curl, wget, net-tools)..."
T_START=$(python3 -c 'import time; print(time.time())')
-run_cmd_raw "$SANDBOX_ID" '{"cmd":"bash","args":["-c","apt-get update -qq && apt-get install -y -qq curl wget redis-tools net-tools > /dev/null 2>&1 && echo done"]}' 120 > /dev/null
+RESP=$(run_cmd_raw "$SANDBOX_ID" '{"cmd":"bash","args":["-c","apt-get update -qq && apt-get install -y -qq curl wget net-tools > /dev/null 2>&1 && echo done"]}' 180)
+EXIT_CODE=$(echo "$RESP" | python3 -c "import sys,json; print(json.load(sys.stdin).get('exitCode','?'))" 2>/dev/null || echo "?")
T_END=$(python3 -c 'import time; print(time.time())')
APT_MS=$(python3 -c "print(f'{($T_END - $T_START) * 1000:.0f}')")
-ok "APT packages installed (${APT_MS}ms)"
-info "Installing Python packages..."
+if [[ "$EXIT_CODE" == "0" ]]; then
+ ok "APT packages installed (${APT_MS}ms)"
+else
+ fail "APT install failed (exit=$EXIT_CODE, ${APT_MS}ms)"
+ echo " Response: $(echo "$RESP" | head -c 200)"
+fi
+
+info "Installing Python packages (flask, requests, numpy, pandas)..."
T_START=$(python3 -c 'import time; print(time.time())')
-run_cmd_raw "$SANDBOX_ID" '{"cmd":"bash","args":["-c","pip install --quiet flask requests numpy pandas > /dev/null 2>&1 && echo done"]}' 120 > /dev/null
+RESP=$(run_cmd_raw "$SANDBOX_ID" '{"cmd":"bash","args":["-c","pip install --quiet flask requests numpy pandas 2>&1 | tail -3 && echo done"]}' 180)
+EXIT_CODE=$(echo "$RESP" | python3 -c "import sys,json; print(json.load(sys.stdin).get('exitCode','?'))" 2>/dev/null || echo "?")
T_END=$(python3 -c 'import time; print(time.time())')
PIP_MS=$(python3 -c "print(f'{($T_END - $T_START) * 1000:.0f}')")
-ok "Python packages installed (${PIP_MS}ms)"
+
+if [[ "$EXIT_CODE" == "0" ]]; then
+ ok "Python packages installed (${PIP_MS}ms)"
+else
+ fail "pip install failed (exit=$EXIT_CODE, ${PIP_MS}ms)"
+ echo " Response: $(echo "$RESP" | head -c 300)"
+fi
# --- Start background processes ---
info "Starting background processes..."
T_START=$(python3 -c 'import time; print(time.time())')
# Start a Flask web server
-run_cmd_raw "$SANDBOX_ID" '{"cmd":"bash","args":["-c","cat > /tmp/app.py << PYEOF\nfrom flask import Flask\nimport os, time\napp = Flask(__name__)\nstart_time = time.time()\[email protected](\"/\")\ndef index():\n return {\"uptime\": time.time() - start_time, \"pid\": os.getpid()}\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=5000)\nPYEOF\nnohup python3 /tmp/app.py > /tmp/flask.log 2>&1 &\necho started"]}' 10 > /dev/null
+run_cmd_raw "$SANDBOX_ID" '{"cmd":"bash","args":["-c","cat > /workspace/app.py << PYEOF\nfrom flask import Flask\nimport os, time\napp = Flask(__name__)\nstart_time = time.time()\[email protected](\"/\")\ndef index():\n return {\"uptime\": time.time() - start_time, \"pid\": os.getpid()}\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=5000)\nPYEOF\nnohup python3 /workspace/app.py > /workspace/flask.log 2>&1 &\nsleep 0.5 && echo started"]}' 10 > /dev/null
# Start a CPU worker process
-run_cmd_raw "$SANDBOX_ID" '{"cmd":"bash","args":["-c","nohup python3 -c \"import time, hashlib; [hashlib.sha256(str(i).encode()).hexdigest() for i in iter(int, 1)]\" > /dev/null 2>&1 &\necho started"]}' 10 > /dev/null
+run_cmd_raw "$SANDBOX_ID" '{"cmd":"bash","args":["-c","nohup python3 -c \"import time, hashlib\nwhile True:\n hashlib.sha256(str(time.time()).encode()).hexdigest()\n time.sleep(0.001)\" > /dev/null 2>&1 &\necho started"]}' 10 > /dev/null
# Start a periodic logger
-run_cmd_raw "$SANDBOX_ID" '{"cmd":"bash","args":["-c","nohup bash -c \"while true; do echo $(date) heartbeat >> /tmp/heartbeat.log; sleep 1; done\" > /dev/null 2>&1 &\necho started"]}' 10 > /dev/null
+run_cmd_raw "$SANDBOX_ID" '{"cmd":"bash","args":["-c","nohup bash -c \"while true; do date >> /workspace/heartbeat.log; sleep 1; done\" > /dev/null 2>&1 &\necho started"]}' 10 > /dev/null
T_END=$(python3 -c 'import time; print(time.time())')
PROC_MS=$(python3 -c "print(f'{($T_END - $T_START) * 1000:.0f}')")
ok "3 background processes started (${PROC_MS}ms)"
-# --- Write 2GB of data ---
-info "Writing 2GB of user data (this will take a minute)..."
+# --- Write 2GB of data to /workspace (persists through hibernate) ---
+info "Writing 2GB of user data to /workspace..."
T_START=$(python3 -c 'import time; print(time.time())')
-# Write 2GB in 256MB chunks to avoid command timeouts
+# Write 2GB in 256MB chunks
for i in $(seq 1 8); do
- run_cmd_raw "$SANDBOX_ID" "{\"cmd\":\"bash\",\"args\":[\"-c\",\"dd if=/dev/urandom of=/tmp/data_${i}.bin bs=1M count=256 2>/dev/null && echo chunk_${i}_done\"]}" 120 > /dev/null
+ run_cmd_raw "$SANDBOX_ID" "{\"cmd\":\"bash\",\"args\":[\"-c\",\"dd if=/dev/urandom of=/workspace/data_${i}.bin bs=1M count=256 2>/dev/null && echo chunk_${i}_done\"]}" 120 > /dev/null
echo -ne " Writing chunk ${i}/8 ($(( i * 256 )) MB)...\r"
done
echo ""
@@ -143,11 +147,14 @@ echo ""
T_END=$(python3 -c 'import time; print(time.time())')
DATA_MS=$(python3 -c "print(f'{($T_END - $T_START) * 1000:.0f}')")
DATA_SECS=$(python3 -c "print(f'{($T_END - $T_START):.1f}')")
-ok "2GB data written (${DATA_SECS}s)"
+ok "2GB data written to /workspace (${DATA_SECS}s)"
+
+# Write a marker for verification
+run_cmd_raw "$SANDBOX_ID" '{"cmd":"bash","args":["-c","echo heavy-benchmark-marker > /workspace/marker.txt"]}' 5 > /dev/null
# Verify data + processes
info "Verifying sandbox state..."
-VERIFY=$(run_cmd_raw "$SANDBOX_ID" '{"cmd":"bash","args":["-c","echo marker=benchmark-heavy-12345 && echo data_size=$(du -sh /tmp/data_*.bin 2>/dev/null | tail -1 | cut -f1) && echo total_files=$(ls /tmp/data_*.bin 2>/dev/null | wc -l) && echo procs=$(ps aux | grep -v grep | grep -c python) && echo flask_up=$(curl -s http://localhost:5000/ | head -c 50)"]}' 10)
+VERIFY=$(run_cmd_raw "$SANDBOX_ID" '{"cmd":"bash","args":["-c","echo marker=$(cat /workspace/marker.txt) && echo data_size=$(du -sh /workspace/data_*.bin 2>/dev/null | tail -1) && echo total_files=$(ls /workspace/data_*.bin 2>/dev/null | wc -l) && echo procs=$(ps aux | grep -v grep | grep -c python || echo 0) && echo flask_up=$(curl -s http://localhost:5000/ | head -c 80)"]}' 10)
echo "$VERIFY" | python3 -c "
import sys, json
d = json.load(sys.stdin)
@@ -163,7 +170,7 @@ ok "Sandbox fully set up"
timing "Total fresh setup: ${SETUP_TOTAL_SECS}s (${SETUP_TOTAL_MS}ms)"
echo ""
echo -e " Breakdown:"
-echo -e " Create container: ${CREATE_MS}ms"
+echo -e " Create VM: ${CREATE_MS}ms"
echo -e " APT install: ${APT_MS}ms"
echo -e " pip install: ${PIP_MS}ms"
echo -e " Start processes: ${PROC_MS}ms"
@@ -209,7 +216,7 @@ timing "Local wake: ${LOCAL_WAKE_SECS}s (${LOCAL_WAKE_MS}ms)"
# Verify everything survived
info "Verifying state after local wake..."
-VERIFY=$(run_cmd_raw "$SANDBOX_ID" '{"cmd":"bash","args":["-c","echo data_size=$(du -sh /tmp/data_*.bin 2>/dev/null | tail -1 | cut -f1) && echo total_files=$(ls /tmp/data_*.bin 2>/dev/null | wc -l) && echo procs=$(ps aux | grep -v grep | grep -c python) && echo flask=$(curl -s http://localhost:5000/ | head -c 80) && echo heartbeat_lines=$(wc -l < /tmp/heartbeat.log 2>/dev/null || echo 0)"]}' 10)
+VERIFY=$(run_cmd_raw "$SANDBOX_ID" '{"cmd":"bash","args":["-c","echo marker=$(cat /workspace/marker.txt) && echo data_files=$(ls /workspace/data_*.bin 2>/dev/null | wc -l) && echo data_size=$(du -sh /workspace/data_*.bin 2>/dev/null | tail -1)"]}' 10)
echo "$VERIFY" | python3 -c "
import sys, json
d = json.load(sys.stdin)
@@ -235,15 +242,15 @@ CP2_SIZE_MB=$(python3 -c "print(f'{int($CP2_SIZE) / 1024 / 1024:.1f}')")
ok "Hibernated (checkpoint: ${CP2_SIZE_MB} MB)"
timing "Hibernate: ${HIB2_SECS}s"
-info "Purging local checkpoint to force S3 pull..."
-# Purge on both workers
+info "Waiting for async S3 upload to finish..."
+sleep 30
+
+info "Purging snapshot files + all NVMe cache (keeping drives for restore)..."
ssh -i ~/.ssh/opensandbox-digger.pem -o StrictHostKeyChecking=no -o ConnectTimeout=5 [email protected] \
- "sudo find /data/sandboxes/checkpoints -name '*${SANDBOX_ID}*' -exec rm -rf {} + 2>/dev/null; echo purged" 2>/dev/null || true
-ssh -i ~/.ssh/opensandbox-digger.pem -o StrictHostKeyChecking=no -o ConnectTimeout=5 [email protected] \
- "sudo find /data/sandboxes/checkpoints -name '*${SANDBOX_ID}*' -exec rm -rf {} + 2>/dev/null; echo purged" 2>/dev/null || true
-ok "Local checkpoint purged"
+ "sudo rm -rf /data/sandboxes/sandboxes/${SANDBOX_ID}/snapshot /data/sandboxes/sandboxes/${SANDBOX_ID}/checkpoint.tar.zst && sudo rm -rf /data/sandboxes/checkpoints && sudo mkdir -p /data/sandboxes/checkpoints && echo purged" 2>/dev/null || true
+ok "Snapshot + cache purged (drives kept)"
-sleep 1
+sleep 2
info "Waking from S3 (must download checkpoint)..."
T_START=$(python3 -c 'import time; print(time.time())')
@@ -264,7 +271,7 @@ ok "Woke from S3"
timing "S3 wake: ${S3_WAKE_SECS}s (${S3_WAKE_MS}ms)"
info "Verifying state after S3 restore..."
-VERIFY=$(run_cmd_raw "$SANDBOX_ID" '{"cmd":"bash","args":["-c","echo data_size=$(du -sh /tmp/data_*.bin 2>/dev/null | tail -1 | cut -f1) && echo total_files=$(ls /tmp/data_*.bin 2>/dev/null | wc -l) && echo procs=$(ps aux | grep -v grep | grep -c python) && echo flask=$(curl -s http://localhost:5000/ | head -c 80)"]}' 10)
+VERIFY=$(run_cmd_raw "$SANDBOX_ID" '{"cmd":"bash","args":["-c","echo marker=$(cat /workspace/marker.txt) && echo data_files=$(ls /workspace/data_*.bin 2>/dev/null | wc -l) && echo data_size=$(du -sh /workspace/data_*.bin 2>/dev/null | tail -1)"]}' 10)
echo "$VERIFY" | python3 -c "
import sys, json
d = json.load(sys.stdin)
@@ -281,26 +288,26 @@ api DELETE "/api/sandboxes/${SANDBOX_ID}" > /dev/null 2>&1 || true
header "RESULTS SUMMARY"
echo ""
echo -e " ${BOLD}Sandbox config:${NC} python template, 4 CPUs, 4GB RAM"
-echo -e " ${BOLD}Payload:${NC} 2GB random data, Flask server, CPU worker, heartbeat logger"
+echo -e " ${BOLD}Payload:${NC} 2GB random data on /workspace, Flask server, CPU worker, logger"
echo -e " ${BOLD}Checkpoint:${NC} ${CP_SIZE_MB} MB (1st), ${CP2_SIZE_MB} MB (2nd)"
echo ""
-echo -e " ┌───────────────────────────────────┬────────────┐"
-echo -e " │ Operation │ Time │"
-echo -e " ├───────────────────────────────────┼────────────┤"
-echo -e " │ ${BOLD}Fresh create + full setup${NC} │ ${BOLD}${RED}${SETUP_TOTAL_SECS}s${NC} │"
-echo -e " │ └ Container create │ ${CREATE_MS}ms │"
-echo -e " │ └ APT packages │ ${APT_MS}ms │"
-echo -e " │ └ pip packages │ ${PIP_MS}ms │"
-echo -e " │ └ Start processes │ ${PROC_MS}ms │"
-echo -e " │ └ Write 2GB data │ ${DATA_SECS}s │"
-echo -e " ├───────────────────────────────────┼────────────┤"
-echo -e " │ Hibernate (1st) │ ${HIB_SECS}s │"
-echo -e " │ ${BOLD}${GREEN}Wake (local checkpoint)${NC} │ ${BOLD}${GREEN}${LOCAL_WAKE_SECS}s${NC} │"
-echo -e " ├───────────────────────────────────┼────────────┤"
-echo -e " │ Hibernate (2nd) │ ${HIB2_SECS}s │"
-echo -e " │ ${BOLD}${GREEN}Wake (S3 → restore)${NC} │ ${BOLD}${GREEN}${S3_WAKE_SECS}s${NC} │"
-echo -e " └───────────────────────────────────┴────────────┘"
+echo -e " ┌───────────────────────────────────┬──────────────┐"
+echo -e " │ Operation │ Time │"
+echo -e " ├───────────────────────────────────┼──────────────┤"
+printf " │ ${BOLD}Fresh create + full setup${NC} │ ${BOLD}${RED}%10ss${NC} │\n" "$SETUP_TOTAL_SECS"
+printf " │ └ VM create │ %10sms │\n" "$CREATE_MS"
+printf " │ └ APT packages │ %10sms │\n" "$APT_MS"
+printf " │ └ pip packages │ %10sms │\n" "$PIP_MS"
+printf " │ └ Start processes │ %10sms │\n" "$PROC_MS"
+printf " │ └ Write 2GB data │ %10ss │\n" "$DATA_SECS"
+echo -e " ├───────────────────────────────────┼──────────────┤"
+printf " │ Hibernate (1st, %5s MB) │ %10ss │\n" "$CP_SIZE_MB" "$HIB_SECS"
+printf " │ ${BOLD}${GREEN}Wake (local checkpoint)${NC} │ ${BOLD}${GREEN}%10ss${NC} │\n" "$LOCAL_WAKE_SECS"
+echo -e " ├───────────────────────────────────┼──────────────┤"
+printf " │ Hibernate (2nd, %5s MB) │ %10ss │\n" "$CP2_SIZE_MB" "$HIB2_SECS"
+printf " │ ${BOLD}${GREEN}Wake (S3 → restore)${NC} │ ${BOLD}${GREEN}%10ss${NC} │\n" "$S3_WAKE_SECS"
+echo -e " └───────────────────────────────────┴──────────────┘"
echo ""
echo -e " ${BOLD}${CYAN}Speedup (local wake vs fresh):${NC} $(python3 -c "print(f'{int($SETUP_TOTAL_MS) / max(int($LOCAL_WAKE_MS), 1):.0f}')") x faster"
-echo -e " ${BOLD}${CYAN}Speedup (S3 wake vs fresh):${NC} $(python3 -c "print(f'{int($SETUP_TOTAL_MS) / max(int($S3_WAKE_MS), 1):.0f}')") x faster"
+echo -e " ${BOLD}${CYAN}Speedup (S3 wake vs fresh):${NC} $(python3 -c "print(f'{int($SETUP_TOTAL_MS) / max(int($S3_WAKE_MS), 1):.0f}')") x faster"
echo ""
diff --git a/scripts/bench-launch.sh b/scripts/bench-launch.sh
index f74db1fa..85564a37 100755
--- a/scripts/bench-launch.sh
+++ b/scripts/bench-launch.sh
@@ -53,12 +53,12 @@ echo ""
# ─────────────────────────────────────────────────────
header "TEST 1: Fresh Launch (cold start)"
-info "Creating sandbox from base template..."
+info "Creating sandbox from ubuntu template..."
T_START=$(python3 -c 'import time; print(time.time())')
RESP=$(api POST /api/sandboxes -d '{
- "templateID": "base",
+ "templateID": "ubuntu",
"timeout": 600,
"memoryMB": 512,
"cpuCount": 2
@@ -90,13 +90,13 @@ fi
curl -s -X POST "${EXEC_URL}/sandboxes/${SANDBOX_ID}/commands" \
-H "${AUTH_HEADER}" \
-H "Content-Type: application/json" \
- -d '{"cmd":"bash","args":["-c","echo benchmark-marker-12345 > /tmp/bench.txt && date +%s > /tmp/bench-time.txt"]}' > /dev/null 2>&1
+ -d '{"cmd":"bash","args":["-c","echo benchmark-marker-12345 > /workspace/bench.txt && date +%s > /workspace/bench-time.txt"]}' > /dev/null 2>&1
# Verify state
CMD_RESP=$(curl -s -X POST "${EXEC_URL}/sandboxes/${SANDBOX_ID}/commands" \
-H "${AUTH_HEADER}" \
-H "Content-Type: application/json" \
- -d '{"cmd":"bash","args":["-c","cat /tmp/bench.txt"]}')
+ -d '{"cmd":"bash","args":["-c","cat /workspace/bench.txt"]}')
MARKER=$(echo "$CMD_RESP" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d.get('stdout','').strip())" 2>/dev/null || echo "")
if [[ "$MARKER" == "benchmark-marker-12345" ]]; then
ok "State written and verified"
@@ -146,7 +146,7 @@ info "Verifying state persistence..."
CMD_RESP=$(curl -s -X POST "${EXEC_URL}/sandboxes/${SANDBOX_ID}/commands" \
-H "${AUTH_HEADER}" \
-H "Content-Type: application/json" \
- -d '{"cmd":"bash","args":["-c","cat /tmp/bench.txt"]}')
+ -d '{"cmd":"bash","args":["-c","cat /workspace/bench.txt"]}')
MARKER=$(echo "$CMD_RESP" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d.get('stdout','').strip())" 2>/dev/null || echo "")
if [[ "$MARKER" == "benchmark-marker-12345" ]]; then
ok "State verified after local wake ✓"
@@ -225,7 +225,7 @@ info "Verifying state persistence after S3 restore..."
CMD_RESP=$(curl -s -X POST "${EXEC_URL}/sandboxes/${SANDBOX_ID}/commands" \
-H "${AUTH_HEADER}" \
-H "Content-Type: application/json" \
- -d '{"cmd":"bash","args":["-c","cat /tmp/bench.txt"]}')
+ -d '{"cmd":"bash","args":["-c","cat /workspace/bench.txt"]}')
MARKER=$(echo "$CMD_RESP" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d.get('stdout','').strip())" 2>/dev/null || echo "")
if [[ "$MARKER" == "benchmark-marker-12345" ]]; then
ok "State verified after S3 wake ✓"
diff --git a/scripts/build-rootfs.sh b/scripts/build-rootfs.sh
new file mode 100755
index 00000000..5d29781a
--- /dev/null
+++ b/scripts/build-rootfs.sh
@@ -0,0 +1,268 @@
+#!/usr/bin/env bash
+# build-rootfs.sh — Build ext4 rootfs images for Firecracker VMs
+#
+# Usage:
+# ./scripts/build-rootfs.sh [ubuntu|python|node|all]
+# IMAGES_DIR=/data/firecracker/images ./scripts/build-rootfs.sh all
+#
+# Requirements:
+# - podman (for building container images)
+# - mkfs.ext4, mount, umount (for ext4 conversion — requires root)
+# - osb-agent binary in bin/ (built via: make build-agent)
+#
+# The script:
+# 1. Builds a container image from the Dockerfile
+# 2. Injects osb-agent and init script
+# 3. Exports the filesystem as tar
+# 4. Converts tar → ext4 image
+# 5. Shrinks the ext4 image to minimum size
+# 6. Places the result in $IMAGES_DIR/{name}.ext4
+
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
+DOCKERFILE_DIR="$PROJECT_ROOT/deploy/firecracker/rootfs"
+IMAGES_DIR="${IMAGES_DIR:-$PROJECT_ROOT/bin/images}"
+AGENT_BIN="${AGENT_BIN:-$PROJECT_ROOT/bin/osb-agent}"
+EXT4_SIZE_MB="${EXT4_SIZE_MB:-4096}" # 4GB sparse (actual usage much less)
+
+# Colors
+RED='\033[0;31m'
+GREEN='\033[0;32m'
+YELLOW='\033[1;33m'
+NC='\033[0m'
+
+log() { echo -e "${GREEN}[build-rootfs]${NC} $*"; }
+warn() { echo -e "${YELLOW}[build-rootfs]${NC} $*"; }
+err() { echo -e "${RED}[build-rootfs]${NC} $*" >&2; }
+
+# Check prerequisites
+check_prereqs() {
+ local missing=()
+ command -v podman &>/dev/null || missing+=(podman)
+ command -v mkfs.ext4 &>/dev/null || missing+=(e2fsprogs)
+
+ if [ ${#missing[@]} -gt 0 ]; then
+ err "Missing prerequisites: ${missing[*]}"
+ exit 1
+ fi
+
+ if [ ! -f "$AGENT_BIN" ]; then
+ warn "osb-agent not found at $AGENT_BIN"
+ warn "Building agent binary..."
+ (cd "$PROJECT_ROOT" && make build-agent)
+ if [ ! -f "$AGENT_BIN" ]; then
+ err "Failed to build osb-agent. Run: make build-agent"
+ exit 1
+ fi
+ fi
+
+ # Check if running as root (needed for mount/umount)
+ if [ "$(id -u)" -ne 0 ]; then
+ err "This script requires root privileges for mount/umount operations."
+ err "Run with: sudo $0 $*"
+ exit 1
+ fi
+}
+
+# Generate the init script
+generate_init_script() {
+ cat << 'INIT_EOF'
+#!/bin/busybox sh
+# OpenSandbox VM init script
+# Runs as PID 1 inside the Firecracker microVM
+
+# Mount virtual filesystems
+mount -t proc proc /proc
+mount -t sysfs sysfs /sys
+mount -t devtmpfs devtmpfs /dev
+mount -t tmpfs tmpfs /tmp
+mount -t tmpfs tmpfs /run
+
+# Create device nodes if devtmpfs didn't
+[ -c /dev/null ] || mknod -m 666 /dev/null c 1 3
+[ -c /dev/zero ] || mknod -m 666 /dev/zero c 1 5
+[ -c /dev/random ] || mknod -m 444 /dev/random c 1 8
+[ -c /dev/urandom ] || mknod -m 444 /dev/urandom c 1 9
+[ -c /dev/tty ] || mknod -m 666 /dev/tty c 5 0
+[ -c /dev/console ] || mknod -m 600 /dev/console c 5 1
+[ -d /dev/pts ] || mkdir -p /dev/pts
+mount -t devpts devpts /dev/pts
+[ -d /dev/shm ] || mkdir -p /dev/shm
+mount -t tmpfs tmpfs /dev/shm
+
+# Mount workspace from vdb
+mkdir -p /workspace
+mount /dev/vdb /workspace 2>/dev/null || {
+ echo "init: warning: could not mount /dev/vdb, trying /dev/vdb1"
+ mount /dev/vdb1 /workspace 2>/dev/null || echo "init: warning: workspace mount failed"
+}
+
+# Configure networking from kernel command line
+# Format: ip=GUEST_IP::GATEWAY:NETMASK::IFACE:off osb.gateway=GATEWAY
+for param in $(cat /proc/cmdline); do
+ case "$param" in
+ ip=*)
+ IP_CONFIG="${param#ip=}"
+ GUEST_IP=$(echo "$IP_CONFIG" | cut -d: -f1)
+ GATEWAY=$(echo "$IP_CONFIG" | cut -d: -f3)
+ NETMASK=$(echo "$IP_CONFIG" | cut -d: -f4)
+ IFACE=$(echo "$IP_CONFIG" | cut -d: -f6)
+ ;;
+ osb.gateway=*)
+ GATEWAY="${param#osb.gateway=}"
+ ;;
+ esac
+done
+
+if [ -n "$GUEST_IP" ] && [ -n "$IFACE" ]; then
+ ip link set lo up
+ ip addr add "${GUEST_IP}/30" dev "$IFACE"
+ ip link set "$IFACE" up
+ if [ -n "$GATEWAY" ]; then
+ ip route add default via "$GATEWAY" dev "$IFACE"
+ fi
+fi
+
+# Set up DNS
+echo "nameserver 8.8.8.8" > /etc/resolv.conf
+echo "nameserver 8.8.4.4" >> /etc/resolv.conf
+
+# Set hostname
+hostname sandbox
+
+# Start the agent
+exec /usr/local/bin/osb-agent
+INIT_EOF
+}
+
+# Build a single rootfs image
+build_image() {
+ local name="$1"
+ local dockerfile="$DOCKERFILE_DIR/Dockerfile.${name}"
+
+ if [ ! -f "$dockerfile" ]; then
+ err "Dockerfile not found: $dockerfile"
+ return 1
+ fi
+
+ log "Building $name rootfs image..."
+
+ local tmpdir
+ tmpdir=$(mktemp -d /tmp/osb-rootfs-XXXXXXXX)
+ trap "rm -rf $tmpdir" RETURN
+
+ local image_tag="localhost/opensandbox-rootfs/${name}:build"
+
+ # Copy Dockerfile to build context
+ cp "$dockerfile" "$tmpdir/Dockerfile"
+
+ # Copy agent binary
+ cp "$AGENT_BIN" "$tmpdir/osb-agent"
+ chmod +x "$tmpdir/osb-agent"
+
+ # Generate init script
+ generate_init_script > "$tmpdir/init"
+ chmod +x "$tmpdir/init"
+
+ # Append agent/init injection to Dockerfile
+ cat >> "$tmpdir/Dockerfile" << 'INJECT_EOF'
+
+# --- OpenSandbox agent injection ---
+COPY osb-agent /usr/local/bin/osb-agent
+RUN chmod +x /usr/local/bin/osb-agent
+COPY init /sbin/init
+RUN chmod +x /sbin/init
+RUN mkdir -p /workspace
+INJECT_EOF
+
+ # Build with podman
+ log " podman build..."
+ if ! podman build -t "$image_tag" -f "$tmpdir/Dockerfile" "$tmpdir" 2>&1 | tail -5; then
+ err " podman build failed for $name"
+ return 1
+ fi
+
+ # Create container and export filesystem
+ log " exporting filesystem..."
+ local container_id
+ container_id=$(podman create "$image_tag" /bin/true 2>/dev/null)
+ podman export "$container_id" -o "$tmpdir/rootfs.tar"
+ podman rm -f "$container_id" &>/dev/null || true
+
+ # Convert tar to ext4
+ log " converting to ext4 (${EXT4_SIZE_MB}MB sparse)..."
+ local ext4_path="$tmpdir/rootfs.ext4"
+
+ # Create sparse file
+ truncate -s "${EXT4_SIZE_MB}M" "$ext4_path"
+
+ # Format as ext4
+ mkfs.ext4 -q -F -L rootfs "$ext4_path"
+
+ # Mount and populate
+ local mnt_dir="$tmpdir/mnt"
+ mkdir -p "$mnt_dir"
+ mount -o loop "$ext4_path" "$mnt_dir"
+
+ tar xf "$tmpdir/rootfs.tar" -C "$mnt_dir"
+
+ # Ensure key directories
+ for dir in proc sys dev dev/pts dev/shm tmp workspace run; do
+ mkdir -p "$mnt_dir/$dir"
+ done
+
+ sync
+ umount "$mnt_dir"
+
+ # Shrink to minimum
+ log " shrinking ext4 image..."
+ resize2fs -M "$ext4_path" 2>/dev/null || warn " resize2fs -M failed (non-fatal)"
+
+ # Get final size
+ local final_size
+ final_size=$(du -h "$ext4_path" | cut -f1)
+
+ # Move to images directory
+ mkdir -p "$IMAGES_DIR"
+ cp "$ext4_path" "$IMAGES_DIR/${name}.ext4"
+
+ # Clean up podman image
+ podman rmi -f "$image_tag" &>/dev/null || true
+
+ log " Done: $IMAGES_DIR/${name}.ext4 ($final_size)"
+}
+
+# Main
+main() {
+ local targets=("${@:-all}")
+
+ check_prereqs
+
+ mkdir -p "$IMAGES_DIR"
+
+ for target in "${targets[@]}"; do
+ case "$target" in
+ all)
+ build_image ubuntu
+ build_image python
+ build_image node
+ ;;
+ ubuntu|python|node)
+ build_image "$target"
+ ;;
+ *)
+ err "Unknown target: $target"
+ echo "Usage: $0 [ubuntu|python|node|all]"
+ exit 1
+ ;;
+ esac
+ done
+
+ log ""
+ log "All images built successfully:"
+ ls -lh "$IMAGES_DIR"/*.ext4 2>/dev/null || true
+}
+
+main "$@"
diff --git a/scripts/download-kernel.sh b/scripts/download-kernel.sh
new file mode 100755
index 00000000..0f4789ec
--- /dev/null
+++ b/scripts/download-kernel.sh
@@ -0,0 +1,163 @@
+#!/usr/bin/env bash
+# download-kernel.sh — Download the Firecracker-compatible Linux kernel
+#
+# Usage:
+# ./scripts/download-kernel.sh [--dest /data/firecracker/vmlinux-arm64]
+#
+# Downloads the pre-built Firecracker kernel for ARM64.
+# The kernel is from the Firecracker project's official releases,
+# built with their microvm config optimized for fast boot.
+#
+# Default destination: bin/vmlinux-arm64
+
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
+
+# Firecracker kernel version — matches their v1.7+ releases
+# Using the 5.10 series which is the most tested with Firecracker
+FC_VERSION="${FC_VERSION:-v1.9.1}"
+ARCH="${ARCH:-aarch64}" # aarch64 for ARM64 Graviton
+
+# Kernel binary name from Firecracker releases
+KERNEL_NAME="vmlinux-5.10.225"
+
+# Default destination
+DEST="${1:-$PROJECT_ROOT/bin/vmlinux-arm64}"
+
+# Colors
+GREEN='\033[0;32m'
+YELLOW='\033[1;33m'
+RED='\033[0;31m'
+NC='\033[0m'
+
+log() { echo -e "${GREEN}[download-kernel]${NC} $*"; }
+warn() { echo -e "${YELLOW}[download-kernel]${NC} $*"; }
+err() { echo -e "${RED}[download-kernel]${NC} $*" >&2; }
+
+# Parse --dest flag
+while [[ $# -gt 0 ]]; do
+ case "$1" in
+ --dest)
+ DEST="$2"
+ shift 2
+ ;;
+ --version)
+ FC_VERSION="$2"
+ shift 2
+ ;;
+ --arch)
+ ARCH="$2"
+ shift 2
+ ;;
+ *)
+ DEST="$1"
+ shift
+ ;;
+ esac
+done
+
+main() {
+ log "Downloading Firecracker kernel for $ARCH..."
+ log " Firecracker version: $FC_VERSION"
+ log " Destination: $DEST"
+
+ # Create destination directory
+ mkdir -p "$(dirname "$DEST")"
+
+ # Check if already exists
+ if [ -f "$DEST" ]; then
+ local size
+ size=$(du -h "$DEST" | cut -f1)
+ warn "Kernel already exists at $DEST ($size)"
+ read -p "Overwrite? [y/N] " -r
+ if [[ ! $REPLY =~ ^[Yy]$ ]]; then
+ log "Keeping existing kernel."
+ return 0
+ fi
+ fi
+
+ # Download URL from Firecracker GitHub releases
+ local url="https://github.com/firecracker-microvm/firecracker/releases/download/${FC_VERSION}/${KERNEL_NAME}.bin"
+
+ log " Downloading from: $url"
+
+ if command -v curl &>/dev/null; then
+ curl -fSL --progress-bar -o "$DEST" "$url" || {
+ err "Download failed. Trying alternative kernel names..."
+ try_alternative_kernels
+ return $?
+ }
+ elif command -v wget &>/dev/null; then
+ wget -q --show-progress -O "$DEST" "$url" || {
+ err "Download failed. Trying alternative kernel names..."
+ try_alternative_kernels
+ return $?
+ }
+ else
+ err "Neither curl nor wget found. Install one and retry."
+ exit 1
+ fi
+
+ # Verify the kernel binary
+ if [ ! -f "$DEST" ] || [ ! -s "$DEST" ]; then
+ err "Downloaded file is empty or missing."
+ rm -f "$DEST"
+ exit 1
+ fi
+
+ # Check it looks like a kernel (ELF binary)
+ local file_type
+ file_type=$(file "$DEST" 2>/dev/null || echo "unknown")
+ if echo "$file_type" | grep -q "ELF"; then
+ log " Verified: ELF binary"
+ else
+ warn " Warning: file type is '$file_type' (expected ELF)"
+ fi
+
+ local size
+ size=$(du -h "$DEST" | cut -f1)
+ log " Downloaded: $DEST ($size)"
+ log "Done!"
+}
+
+# Try alternative kernel names from Firecracker releases
+try_alternative_kernels() {
+ local base_url="https://github.com/firecracker-microvm/firecracker/releases/download/${FC_VERSION}"
+
+ # Try common kernel names from different Firecracker versions
+ local candidates=(
+ "vmlinux-5.10.225.bin"
+ "vmlinux-5.10.217.bin"
+ "vmlinux-5.10.210.bin"
+ "vmlinux-5.10.204.bin"
+ "vmlinux-5.10.198.bin"
+ "vmlinux-6.1.102.bin"
+ "vmlinux-6.1.96.bin"
+ )
+
+ for kernel in "${candidates[@]}"; do
+ local url="${base_url}/${kernel}"
+ log " Trying: $kernel"
+ if curl -fSL --progress-bar -o "$DEST" "$url" 2>/dev/null; then
+ if [ -s "$DEST" ]; then
+ log " Success: $kernel"
+ return 0
+ fi
+ fi
+ done
+
+ # Last resort: list available assets from the release
+ err "Could not find a kernel binary in Firecracker ${FC_VERSION}."
+ err ""
+ err "Try listing available assets:"
+ err " curl -s https://api.github.com/repos/firecracker-microvm/firecracker/releases/tags/${FC_VERSION} | jq -r '.assets[].name'"
+ err ""
+ err "Or download manually from:"
+ err " https://github.com/firecracker-microvm/firecracker/releases/tag/${FC_VERSION}"
+ rm -f "$DEST"
+ return 1
+}
+
+main
diff --git a/scripts/reliability-test.sh b/scripts/reliability-test.sh
new file mode 100755
index 00000000..33b19c92
--- /dev/null
+++ b/scripts/reliability-test.sh
@@ -0,0 +1,105 @@
+#!/usr/bin/env bash
+set -uo pipefail
+
+# Reliability test: runs benchmarks + TypeScript SDK tests in a loop.
+# Usage: ./scripts/reliability-test.sh [iterations]
+
+ITERATIONS="${1:-10}"
+SERVER="https://app.opensandbox.ai"
+API_KEY="osb_600b1a9ba2e515c6e54141588da39204d5123cb4b1a28da22b7bd92b88be1534"
+REPO_DIR="$(cd "$(dirname "$0")/.." && pwd)"
+
+# Export env vars for SDK tests
+export OPENSANDBOX_API_KEY="$API_KEY"
+export OPENSANDBOX_API_URL="$SERVER"
+
+RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'
+CYAN='\033[0;36m'; BOLD='\033[1m'; NC='\033[0m'
+
+RESULTS_FILE="/tmp/reliability-results-$(date +%s).txt"
+
+pass=0
+fail=0
+
+cleanup_sandboxes() {
+ for id in $(curl -s "$SERVER/api/sandboxes" -H "X-API-Key: $API_KEY" 2>/dev/null | python3 -c "import sys,json; [print(s['sandboxID']) for s in json.load(sys.stdin)]" 2>/dev/null); do
+ curl -s -X DELETE "$SERVER/api/sandboxes/$id" -H "X-API-Key: $API_KEY" > /dev/null 2>&1
+ done
+}
+
+run_test() {
+ local iter="$1" name="$2" cmd="$3"
+ echo -e "\n${BOLD}${CYAN}━━━ Run $iter/$ITERATIONS: $name ━━━${NC}"
+ local t_start=$(python3 -c 'import time; print(time.time())')
+
+ eval "$cmd" > "/tmp/reliability-run-${iter}-${name}.log" 2>&1
+ local exit_code=$?
+
+ local t_end=$(python3 -c 'import time; print(time.time())')
+ local elapsed=$(python3 -c "print(f'{($t_end - $t_start):.1f}')")
+
+ if [[ $exit_code -eq 0 ]]; then
+ echo -e " ${GREEN}✓${NC} ${name} passed (${elapsed}s)"
+ echo "PASS iter=$iter test=$name time=${elapsed}s" >> "$RESULTS_FILE"
+ ((pass++))
+ else
+ echo -e " ${RED}✗${NC} ${name} FAILED (exit=$exit_code, ${elapsed}s)"
+ echo "FAIL iter=$iter test=$name time=${elapsed}s exit=$exit_code" >> "$RESULTS_FILE"
+ echo " Log: /tmp/reliability-run-${iter}-${name}.log"
+ ((fail++))
+ fi
+}
+
+echo -e "${BOLD}${CYAN}═══════════════════════════════════════════════════════════${NC}"
+echo -e "${BOLD}${CYAN} RELIABILITY TEST: $ITERATIONS iterations${NC}"
+echo -e "${BOLD}${CYAN}═══════════════════════════════════════════════════════════${NC}"
+echo ""
+echo "Results log: $RESULTS_FILE"
+
+T_TOTAL_START=$(python3 -c 'import time; print(time.time())')
+
+for i in $(seq 1 "$ITERATIONS"); do
+ echo -e "\n${BOLD}${YELLOW}╔══════════════════════════════════════════╗${NC}"
+ echo -e "${BOLD}${YELLOW}║ ITERATION $i / $ITERATIONS ║${NC}"
+ echo -e "${BOLD}${YELLOW}╚══════════════════════════════════════════╝${NC}"
+
+ # Clean slate
+ cleanup_sandboxes
+
+ # Light benchmark (gRPC, runs on worker)
+ run_test "$i" "bench-grpc" "bash ${REPO_DIR}/scripts/bench-grpc.sh [email protected] ~/.ssh/opensandbox-digger.pem"
+
+ # Clean slate
+ cleanup_sandboxes
+
+ # TypeScript SDK tests (subshell to avoid cwd contamination)
+ run_test "$i" "sdk-tests" "(cd ${REPO_DIR}/sdks/typescript && npx tsx examples/run-all-tests.ts)"
+
+ # Clean slate
+ cleanup_sandboxes
+done
+
+T_TOTAL_END=$(python3 -c 'import time; print(time.time())')
+TOTAL_SECS=$(python3 -c "print(f'{($T_TOTAL_END - $T_TOTAL_START):.0f}')")
+TOTAL_MINS=$(python3 -c "print(f'{($T_TOTAL_END - $T_TOTAL_START) / 60:.1f}')")
+
+echo -e "\n${BOLD}${CYAN}═══════════════════════════════════════════════════════════${NC}"
+echo -e "${BOLD}${CYAN} RESULTS SUMMARY${NC}"
+echo -e "${BOLD}${CYAN}═══════════════════════════════════════════════════════════${NC}"
+echo ""
+echo -e " Iterations: $ITERATIONS"
+echo -e " Total time: ${TOTAL_MINS} min (${TOTAL_SECS}s)"
+echo -e " ${GREEN}Passed: $pass${NC}"
+echo -e " ${RED}Failed: $fail${NC}"
+echo ""
+
+if [[ $fail -gt 0 ]]; then
+ echo -e " ${RED}${BOLD}FAILURES:${NC}"
+ grep "^FAIL" "$RESULTS_FILE" | while read -r line; do
+ echo -e " ${RED}$line${NC}"
+ done
+ echo ""
+fi
+
+echo -e " Full results: $RESULTS_FILE"
+echo ""
diff --git a/scripts/test-autoscale.sh b/scripts/test-autoscale.sh
new file mode 100755
index 00000000..c73ebaff
--- /dev/null
+++ b/scripts/test-autoscale.sh
@@ -0,0 +1,213 @@
+#!/usr/bin/env bash
+set -o pipefail
+
+SERVER="https://app.opensandbox.ai"
+API_KEY="osb_600b1a9ba2e515c6e54141588da39204d5123cb4b1a28da22b7bd92b88be1534"
+AUTH_HEADER="X-API-Key: $API_KEY"
+SSH="ssh -i ~/.ssh/opensandbox-digger.pem -o StrictHostKeyChecking=no -o ConnectTimeout=5"
+
+RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'
+CYAN='\033[0;36m'; BOLD='\033[1m'; NC='\033[0m'
+
+SANDBOX_IDS=()
+
+info() { echo -e "${CYAN}[INFO]${NC} $*"; }
+ok() { echo -e "${GREEN}[OK]${NC} $*"; }
+fail() { echo -e "${RED}[FAIL]${NC} $*"; }
+warn() { echo -e "${YELLOW}[WARN]${NC} $*"; }
+header(){ echo -e "\n${BOLD}${CYAN}━━━ $* ━━━${NC}"; }
+
+api() {
+ local method="$1" path="$2" body="${3:-}"
+ if [[ -n "$body" ]]; then
+ curl -s -X "$method" "$SERVER/api$path" -H "$AUTH_HEADER" -H "Content-Type: application/json" -d "$body"
+ else
+ curl -s -X "$method" "$SERVER/api$path" -H "$AUTH_HEADER"
+ fi
+}
+
+create_sandbox() {
+ local resp sid
+ for retry in 1 2 3; do
+ resp=$(api POST /sandboxes '{"template":"base","timeout":600}')
+ sid=$(echo "$resp" | python3 -c "import sys,json; print(json.load(sys.stdin).get('sandboxID',''))" 2>/dev/null)
+ if [[ -n "$sid" && "$sid" != "None" && "$sid" != "" ]]; then
+ echo "$sid"
+ return 0
+ fi
+ sleep 3
+ done
+ echo "FAILED: $resp" >&2
+ return 1
+}
+
+worker_of() { api GET "/sandboxes/$1" | python3 -c "import sys,json; print(json.load(sys.stdin).get('workerID',''))" 2>/dev/null; }
+workers() { api GET /workers; }
+worker_count(){ workers | python3 -c "
+import sys,json
+d=json.load(sys.stdin)
+if isinstance(d,list): print(len(d))
+else: print(0)
+" 2>/dev/null; }
+worker_ids() { workers | python3 -c "
+import sys,json
+d=json.load(sys.stdin)
+if isinstance(d,list):
+ for w in d: print(w['worker_id'])
+" 2>/dev/null; }
+worker_table(){ workers | python3 -c "
+import sys,json
+d=json.load(sys.stdin)
+if not isinstance(d,list): print(' (no workers)'); sys.exit()
+for w in d:
+ u = w['current']/w['capacity']*100 if w['capacity']>0 else 0
+ print(f\" {w['worker_id']}: {w['current']}/{w['capacity']} ({u:.0f}%)\")
+" 2>/dev/null; }
+
+cleanup() {
+ header "CLEANUP"
+ if [[ ${#SANDBOX_IDS[@]} -gt 0 ]]; then
+ info "Destroying ${#SANDBOX_IDS[@]} sandboxes..."
+ for sid in "${SANDBOX_IDS[@]}"; do
+ api DELETE "/sandboxes/$sid" > /dev/null 2>&1
+ done
+ SANDBOX_IDS=()
+ fi
+ ok "Done"
+}
+trap cleanup EXIT
+
+# ═══════════════════════════════════════════════════════════
+header "PHASE 1: Baseline"
+# ═══════════════════════════════════════════════════════════
+info "Waiting for worker registry to populate..."
+for attempt in $(seq 1 12); do
+ INITIAL_WORKERS=$(worker_count)
+ if [[ "$INITIAL_WORKERS" -gt 0 ]] 2>/dev/null; then break; fi
+ sleep 5
+done
+INITIAL_WORKER_ID=$(worker_ids | head -1)
+if [[ -z "$INITIAL_WORKER_ID" ]]; then
+ fail "No workers found after 60s"
+ exit 1
+fi
+info "Workers: $INITIAL_WORKERS Initial: $INITIAL_WORKER_ID"
+worker_table
+
+# ═══════════════════════════════════════════════════════════
+header "PHASE 2: Fill to 80% (4/5 sandboxes)"
+# ═══════════════════════════════════════════════════════════
+for i in 1 2 3 4; do
+ sid=$(create_sandbox)
+ SANDBOX_IDS+=("$sid")
+ ok "$i/4: $sid → $(worker_of "$sid")"
+done
+sleep 5
+worker_table
+
+# ═══════════════════════════════════════════════════════════
+header "PHASE 3: Wait for new worker"
+# ═══════════════════════════════════════════════════════════
+info "Polling every 10s (up to 15 min)..."
+for i in $(seq 10 10 900); do
+ sleep 10
+ n=$(worker_count)
+ echo -e " ${i}s workers=$n"
+ if [[ "$n" -gt "$INITIAL_WORKERS" ]]; then
+ ok "New worker appeared at ${i}s!"
+ worker_table
+ NEW_WORKER_ID=$(worker_ids | grep -v "$INITIAL_WORKER_ID" | head -1)
+ info "New worker: $NEW_WORKER_ID"
+ break
+ fi
+ if [[ "$i" -ge 900 ]]; then
+ fail "Timed out after 15 min"
+ $SSH $CP "sudo journalctl -u opensandbox-server --no-pager -n 20 --grep scaler" 2>/dev/null
+ exit 1
+ fi
+done
+
+# ═══════════════════════════════════════════════════════════
+header "PHASE 4: Place sandbox on new worker"
+# ═══════════════════════════════════════════════════════════
+sid=$(create_sandbox)
+SANDBOX_IDS+=("$sid")
+w=$(worker_of "$sid")
+if [[ "$w" == "$NEW_WORKER_ID" ]]; then
+ ok "$sid → NEW worker $w"
+else
+ warn "$sid → $w (expected $NEW_WORKER_ID)"
+fi
+
+# ═══════════════════════════════════════════════════════════
+header "PHASE 5: Cross-worker migration"
+# ═══════════════════════════════════════════════════════════
+MIGRATE_SID=""
+info "Looking for sandbox on initial worker ($INITIAL_WORKER_ID) from ${#SANDBOX_IDS[@]} sandboxes..."
+for sid in "${SANDBOX_IDS[@]}"; do
+ w=$(worker_of "$sid")
+ info " $sid → worker=$w"
+ if [[ "$w" == "$INITIAL_WORKER_ID" ]]; then MIGRATE_SID="$sid"; break; fi
+done
+
+if [[ -z "$MIGRATE_SID" ]]; then
+ warn "No sandbox on initial worker to migrate"
+else
+ info "Hibernate $MIGRATE_SID (on $INITIAL_WORKER_ID)..."
+ hib=$(api POST "/sandboxes/$MIGRATE_SID/hibernate")
+ echo "$hib" | python3 -c "import sys,json; d=json.load(sys.stdin); print(f' status={d.get(\"status\")} key={d.get(\"checkpointKey\",\"\")[:40]}')" 2>/dev/null
+
+ info "Waiting 60s for S3 upload (includes workspace.ext4)..."
+ sleep 60
+
+ info "Waking $MIGRATE_SID..."
+ wake=$(api POST "/sandboxes/$MIGRATE_SID/wake" '{"timeout":300}')
+ wake_worker=$(echo "$wake" | python3 -c "import sys,json; print(json.load(sys.stdin).get('workerID',''))" 2>/dev/null)
+
+ if [[ "$wake_worker" != "$INITIAL_WORKER_ID" && -n "$wake_worker" && "$wake_worker" != "None" ]]; then
+ ok "MIGRATED: $INITIAL_WORKER_ID → $wake_worker"
+ elif [[ "$wake_worker" == "$INITIAL_WORKER_ID" ]]; then
+ warn "Woke on same worker (it was least-loaded)"
+ else
+ fail "Wake failed: $wake"
+ fi
+fi
+
+# ═══════════════════════════════════════════════════════════
+header "PHASE 6: Exec on both workers"
+# ═══════════════════════════════════════════════════════════
+info "Testing exec on ${#SANDBOX_IDS[@]} sandboxes..."
+for sid in "${SANDBOX_IDS[@]}"; do
+ w=$(worker_of "$sid")
+ resp=$(api POST "/sandboxes/$sid/commands" '{"cmd":"echo ok"}')
+ ec=$(echo "$resp" | python3 -c "import sys,json; print(json.load(sys.stdin).get('exitCode','?'))" 2>/dev/null)
+ [[ "$ec" == "0" ]] && ok "$sid ($w)" || fail "$sid ($w) exit=$ec resp=$resp"
+done
+
+# ═══════════════════════════════════════════════════════════
+header "PHASE 7: Scale down"
+# ═══════════════════════════════════════════════════════════
+info "Destroying ${#SANDBOX_IDS[@]} sandboxes..."
+for sid in "${SANDBOX_IDS[@]}"; do
+ resp=$(api DELETE "/sandboxes/$sid")
+ info " destroyed $sid"
+done
+SANDBOX_IDS=()
+info "Waiting 30s for worker counts to update..."
+sleep 30
+worker_table
+
+info "Waiting for scale-down (up to 5 min)..."
+for i in $(seq 10 10 300); do
+ sleep 10
+ n=$(worker_count)
+ echo -e " ${i}s workers=$n"
+ if [[ "$n" -le "$INITIAL_WORKERS" ]]; then
+ ok "Scaled down at ${i}s"
+ break
+ fi
+done
+
+header "DONE"
+worker_table
diff --git a/scripts/test-vsock.sh b/scripts/test-vsock.sh
new file mode 100644
index 00000000..f4c7dfe1
--- /dev/null
+++ b/scripts/test-vsock.sh
@@ -0,0 +1,77 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+TEST_DIR="/data/sandboxes/sandboxes/test-conn"
+mkdir -p "$TEST_DIR"
+cp --reflink=auto /data/sandboxes/firecracker/images/ubuntu.ext4 "$TEST_DIR/rootfs.ext4"
+truncate -s 1G "$TEST_DIR/workspace.ext4"
+mkfs.ext4 -q -F -L workspace "$TEST_DIR/workspace.ext4"
+
+ip tuntap add dev tap-conn0 mode tap 2>/dev/null || true
+ip addr flush dev tap-conn0 2>/dev/null || true
+ip addr add 172.16.0.1/30 dev tap-conn0
+ip link set tap-conn0 up
+
+cat > "$TEST_DIR/vm-config.json" << 'CFGEOF'
+{
+ "boot-source": {
+ "kernel_image_path": "/data/sandboxes/firecracker/vmlinux-arm64",
+ "boot_args": "keep_bootcon console=ttyS0 reboot=k panic=1 pci=off ip=172.16.0.2::172.16.0.1:255.255.255.252::eth0:off init=/sbin/init osb.gateway=172.16.0.1"
+ },
+ "drives": [
+ {"drive_id": "rootfs", "path_on_host": "/data/sandboxes/sandboxes/test-conn/rootfs.ext4", "is_root_device": true, "is_read_only": false},
+ {"drive_id": "workspace", "path_on_host": "/data/sandboxes/sandboxes/test-conn/workspace.ext4", "is_root_device": false, "is_read_only": false}
+ ],
+ "network-interfaces": [
+ {"iface_id": "eth0", "guest_mac": "AA:FC:00:00:01:02", "host_dev_name": "tap-conn0"}
+ ],
+ "vsock": {"guest_cid": 4, "uds_path": "/data/sandboxes/sandboxes/test-conn/vsock.sock"},
+ "machine-config": {"vcpu_count": 2, "mem_size_mib": 512, "smt": false}
+}
+CFGEOF
+
+echo "Starting Firecracker..."
+/usr/local/bin/firecracker --config-file "$TEST_DIR/vm-config.json" --no-api > "$TEST_DIR/firecracker.log" 2>&1 &
+FC_PID=$!
+echo "PID=$FC_PID"
+
+sleep 3
+
+echo "=== vsock.sock check ==="
+ls -la "$TEST_DIR"/vsock.sock* 2>/dev/null || echo "NO vsock files"
+
+echo "=== Agent output (tail of FC log) ==="
+tail -10 "$TEST_DIR/firecracker.log"
+
+echo "=== Try connecting to vsock_1024 via python ==="
+python3 << 'PYEOF'
+import socket
+import sys
+try:
+ s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+ s.settimeout(3)
+ s.connect("/data/sandboxes/sandboxes/test-conn/vsock.sock_1024")
+ print("Connected via python!")
+ # Try to send HTTP/2 preface (gRPC uses HTTP/2)
+ s.sendall(b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n")
+ try:
+ data = s.recv(1024)
+ print(f"Received {len(data)} bytes: {data[:50]}")
+ except socket.timeout:
+ print("Recv timed out (normal if gRPC)")
+ s.close()
+except Exception as e:
+ print(f"Connect failed: {e}")
+ sys.exit(1)
+PYEOF
+
+echo "=== Try grpcurl if available ==="
+which grpcurl 2>/dev/null && grpcurl -plaintext -unix "$TEST_DIR/vsock.sock_1024" list 2>&1 || echo "grpcurl not available"
+
+# Cleanup
+echo "=== Cleanup ==="
+kill $FC_PID 2>/dev/null
+wait $FC_PID 2>/dev/null || true
+ip link del tap-conn0 2>/dev/null || true
+rm -rf "$TEST_DIR"
+echo "DONE"
diff --git a/scripts/test-vsock2.sh b/scripts/test-vsock2.sh
new file mode 100644
index 00000000..7a9c564b
--- /dev/null
+++ b/scripts/test-vsock2.sh
@@ -0,0 +1,99 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+TEST_DIR="/data/sandboxes/sandboxes/test-conn2"
+mkdir -p "$TEST_DIR"
+cp --reflink=auto /data/sandboxes/firecracker/images/ubuntu.ext4 "$TEST_DIR/rootfs.ext4"
+truncate -s 1G "$TEST_DIR/workspace.ext4"
+mkfs.ext4 -q -F -L workspace "$TEST_DIR/workspace.ext4"
+
+ip tuntap add dev tap-conn1 mode tap 2>/dev/null || true
+ip addr flush dev tap-conn1 2>/dev/null || true
+ip addr add 172.16.0.9/30 dev tap-conn1
+ip link set tap-conn1 up
+
+cat > "$TEST_DIR/vm-config.json" << 'CFGEOF'
+{
+ "boot-source": {
+ "kernel_image_path": "/data/sandboxes/firecracker/vmlinux-arm64",
+ "boot_args": "keep_bootcon console=ttyS0 reboot=k panic=1 pci=off ip=172.16.0.10::172.16.0.9:255.255.255.252::eth0:off init=/sbin/init osb.gateway=172.16.0.9"
+ },
+ "drives": [
+ {"drive_id": "rootfs", "path_on_host": "/data/sandboxes/sandboxes/test-conn2/rootfs.ext4", "is_root_device": true, "is_read_only": false},
+ {"drive_id": "workspace", "path_on_host": "/data/sandboxes/sandboxes/test-conn2/workspace.ext4", "is_root_device": false, "is_read_only": false}
+ ],
+ "network-interfaces": [
+ {"iface_id": "eth0", "guest_mac": "AA:FC:00:00:01:03", "host_dev_name": "tap-conn1"}
+ ],
+ "vsock": {"guest_cid": 5, "uds_path": "/data/sandboxes/sandboxes/test-conn2/vsock.sock"},
+ "machine-config": {"vcpu_count": 2, "mem_size_mib": 512, "smt": false}
+}
+CFGEOF
+
+echo "Starting Firecracker..."
+/usr/local/bin/firecracker --config-file "$TEST_DIR/vm-config.json" --no-api > "$TEST_DIR/firecracker.log" 2>&1 &
+FC_PID=$!
+echo "PID=$FC_PID"
+
+# Monitor for files appearing
+for i in $(seq 1 20); do
+ sleep 0.5
+ echo "=== Check $i ($(date +%H:%M:%S.%N)) ==="
+ ls "$TEST_DIR"/vsock.sock* 2>/dev/null || echo "nothing yet"
+done
+
+echo "=== Full directory listing ==="
+ls -la "$TEST_DIR"/ 2>/dev/null
+
+echo "=== FC log tail ==="
+tail -15 "$TEST_DIR/firecracker.log"
+
+echo "=== Try connecting to vsock.sock (not _1024) via python ==="
+python3 << 'PYEOF'
+import socket
+import os
+
+# Check what vsock.sock actually is
+path = "/data/sandboxes/sandboxes/test-conn2/vsock.sock"
+print(f"vsock.sock exists: {os.path.exists(path)}")
+print(f"is socket: {os.path.exists(path) and not os.path.isfile(path)}")
+
+# Try connecting directly to vsock.sock (it's the Firecracker vsock multiplexer)
+try:
+ s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+ s.settimeout(3)
+ s.connect(path)
+ print("Connected to vsock.sock directly!")
+ # Send CONNECT command (Firecracker protocol)
+ # In Firecracker, host-initiated connections go through the UDS
+ # Protocol: connect to vsock.sock, then tell it which port
+ s.sendall(b"CONNECT 1024\n")
+ try:
+ data = s.recv(1024)
+ print(f"Response: {data}")
+ except socket.timeout:
+ print("No response (timeout)")
+ s.close()
+except Exception as e:
+ print(f"Connect to vsock.sock failed: {e}")
+
+# Try vsock.sock_1024
+path2 = path + "_1024"
+print(f"\nvsock.sock_1024 exists: {os.path.exists(path2)}")
+try:
+ s2 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+ s2.settimeout(3)
+ s2.connect(path2)
+ print("Connected to vsock.sock_1024!")
+ s2.close()
+except Exception as e:
+ print(f"Connect to vsock.sock_1024 failed: {e}")
+PYEOF
+
+# Cleanup
+echo "=== Cleanup ==="
+kill $FC_PID 2>/dev/null
+wait $FC_PID 2>/dev/null || true
+ip link del tap-conn1 2>/dev/null || true
+rm -rf "$TEST_DIR"
+echo "DONE"
diff --git a/sdks/typescript/examples/run-all-tests.ts b/sdks/typescript/examples/run-all-tests.ts
index 562666c5..c5ea47a6 100644
--- a/sdks/typescript/examples/run-all-tests.ts
+++ b/sdks/typescript/examples/run-all-tests.ts
@@ -44,6 +44,7 @@ interface TestSuite {
}
const SUITES: TestSuite[] = [
+ { name: "Environment", file: "test-environment.ts", description: "HOME=/workspace, npm/pip cache dirs, dotfiles" },
{ name: "Commands", file: "test-commands.ts", description: "Shell commands, stderr, exit codes, pipes, concurrency" },
{ name: "File Ops", file: "test-file-ops.ts", description: "Large files, special chars, nested dirs, deletion" },
{ name: "Python SDK", file: "test-python-sdk.ts", description: "Python template, stdlib, file ops from Python" },
diff --git a/sdks/typescript/examples/test-environment.ts b/sdks/typescript/examples/test-environment.ts
new file mode 100644
index 00000000..93fa60c0
--- /dev/null
+++ b/sdks/typescript/examples/test-environment.ts
@@ -0,0 +1,165 @@
+/**
+ * Environment & HOME Directory Test
+ *
+ * Verifies that HOME=/workspace inside sandboxes so that tools like npm, pip,
+ * git etc. use the NVMe-backed workspace drive for caches and config instead
+ * of /root on the small rootfs.
+ *
+ * Tests:
+ * 1. HOME is set to /workspace
+ * 2. Tilde (~) expands to /workspace
+ * 3. npm cache dir is under /workspace
+ * 4. npm install writes cache to /workspace (not /root or /dev/root)
+ * 5. pip cache dir is under /workspace
+ * 6. git config home is /workspace
+ *
+ * Usage:
+ * npx tsx examples/test-environment.ts
+ */
+
+import { Sandbox } from "../src/index";
+
+function green(msg: string) { console.log(`\x1b[32m✓ ${msg}\x1b[0m`); }
+function red(msg: string) { console.log(`\x1b[31m✗ ${msg}\x1b[0m`); }
+function bold(msg: string) { console.log(`\x1b[1m${msg}\x1b[0m`); }
+function dim(msg: string) { console.log(`\x1b[2m ${msg}\x1b[0m`); }
+
+let passed = 0;
+let failed = 0;
+
+function check(desc: string, condition: boolean, detail?: string) {
+ if (condition) {
+ green(desc);
+ passed++;
+ } else {
+ red(`${desc}${detail ? ` (${detail})` : ""}`);
+ failed++;
+ }
+}
+
+async function main() {
+ bold("\n╔══════════════════════════════════════════════════╗");
+ bold("║ Environment & HOME Directory Test ║");
+ bold("╚══════════════════════════════════════════════════╝\n");
+
+ let sandbox: Sandbox | null = null;
+
+ try {
+ sandbox = await Sandbox.create({ template: "node", timeout: 120 });
+ green(`Created sandbox: ${sandbox.sandboxId}`);
+ console.log();
+
+ // ── Test 1: HOME is /workspace ─────────────────────────────────
+ bold("━━━ Test 1: HOME environment variable ━━━\n");
+
+ const homeResult = await sandbox.commands.run("echo $HOME");
+ check("HOME is /workspace", homeResult.stdout.trim() === "/workspace",
+ `got "${homeResult.stdout.trim()}"`);
+
+ // ── Test 2: Tilde expansion ────────────────────────────────────
+ bold("━━━ Test 2: Tilde (~) expansion ━━━\n");
+
+ const tildeResult = await sandbox.commands.run("echo ~");
+ check("~ expands to /workspace", tildeResult.stdout.trim() === "/workspace",
+ `got "${tildeResult.stdout.trim()}"`);
+
+ const tildeSlash = await sandbox.commands.run("echo ~/test");
+ check("~/test expands to /workspace/test", tildeSlash.stdout.trim() === "/workspace/test",
+ `got "${tildeSlash.stdout.trim()}"`);
+ console.log();
+
+ // ── Test 3: npm cache directory ────────────────────────────────
+ bold("━━━ Test 3: npm cache directory ━━━\n");
+
+ const npmCache = await sandbox.commands.run("npm config get cache");
+ const npmCachePath = npmCache.stdout.trim();
+ check("npm cache is under /workspace", npmCachePath.startsWith("/workspace"),
+ `got "${npmCachePath}"`);
+ check("npm cache is NOT under /root", !npmCachePath.startsWith("/root"),
+ `got "${npmCachePath}"`);
+ dim(`npm cache dir: ${npmCachePath}`);
+ console.log();
+
+ // ── Test 4: npm install writes to workspace ────────────────────
+ bold("━━━ Test 4: npm install uses workspace for cache ━━━\n");
+
+ // Create a minimal package.json and install a small package
+ await sandbox.commands.run("mkdir -p /workspace/npm-test");
+ await sandbox.files.write("/workspace/npm-test/package.json", JSON.stringify({
+ name: "test",
+ version: "1.0.0",
+ dependencies: { "is-odd": "3.0.1" }
+ }));
+
+ const installResult = await sandbox.commands.run(
+ "cd /workspace/npm-test && npm install --prefer-offline 2>&1",
+ { timeout: 30 }
+ );
+ dim(`npm install exit code: ${installResult.exitCode}`);
+
+ // Verify nothing was written to /root
+ const rootCheck = await sandbox.commands.run(
+ "du -sh /root/.npm 2>/dev/null || echo 'no /root/.npm'"
+ );
+ check("No npm cache in /root/.npm", rootCheck.stdout.includes("no /root/.npm"),
+ `got "${rootCheck.stdout.trim()}"`);
+
+ // Verify cache was written under /workspace
+ const workspaceCache = await sandbox.commands.run(
+ "test -d /workspace/.npm && echo 'exists' || echo 'missing'"
+ );
+ check("npm cache exists at /workspace/.npm", workspaceCache.stdout.trim() === "exists",
+ `got "${workspaceCache.stdout.trim()}"`);
+ console.log();
+
+ // ── Test 5: Dotfiles go to workspace ───────────────────────────
+ bold("━━━ Test 5: Dotfiles and configs use /workspace ━━━\n");
+
+ // Test that .bashrc would be read from /workspace
+ const bashrcPath = await sandbox.commands.run("bash -c 'echo $HOME/.bashrc'");
+ check(".bashrc path is /workspace/.bashrc", bashrcPath.stdout.trim() === "/workspace/.bashrc",
+ `got "${bashrcPath.stdout.trim()}"`);
+
+ // Git global config would go to /workspace/.gitconfig
+ await sandbox.commands.run("git config --global user.name 'Test User'");
+ const gitConfigPath = await sandbox.commands.run("git config --global --list --show-origin 2>/dev/null | head -1");
+ check("git config is under /workspace", gitConfigPath.stdout.includes("/workspace"),
+ `got "${gitConfigPath.stdout.trim()}"`);
+ console.log();
+
+ // ── Test 6: /workspace is on the right filesystem ──────────────
+ bold("━━━ Test 6: /workspace is NVMe-backed ━━━\n");
+
+ const dfResult = await sandbox.commands.run("df -h /workspace | tail -1");
+ const dfLine = dfResult.stdout.trim();
+ dim(`df output: ${dfLine}`);
+ // /workspace should be on /dev/vdb (the workspace drive), not /dev/root
+ check("/workspace is NOT on /dev/root", !dfLine.startsWith("/dev/root"),
+ `got "${dfLine}"`);
+ console.log();
+
+ // Clean up the test directory
+ await sandbox.commands.run("rm -rf /workspace/npm-test");
+
+ } catch (err: any) {
+ red(`Fatal error: ${err.message}`);
+ if (err.stack) dim(err.stack);
+ failed++;
+ } finally {
+ if (sandbox) {
+ await sandbox.kill();
+ green("Sandbox killed");
+ }
+ }
+
+ // --- Summary ---
+ bold("========================================");
+ bold(` Results: ${passed} passed, ${failed} failed`);
+ bold("========================================\n");
+ if (failed > 0) process.exit(1);
+}
+
+main().catch((err) => {
+ console.error("Fatal error:", err);
+ process.exit(1);
+});