Skip to content

An open-source, faster Devin alternative

TypeScript

remove dead code, some fixes

Brian Reardona7ab1cc1b765
diff --git a/cmd/agent/listen_linux.go b/cmd/agent/listen_linux.go
index 9b56d10e..f8161667 100644
--- a/cmd/agent/listen_linux.go
+++ b/cmd/agent/listen_linux.go
@@ -87,8 +87,10 @@ func listenVirtioSerial(path string) (net.Listener, error) {
}
func (l *virtioSerialListener) Accept() (net.Conn, error) {
- // Wait until no connection is active, then provide a new one.
- // This handles: initial boot, reconnect after golden restore, etc.
+ // Wait until no connection is active and the port is readable.
+ // After loadvm/checkpoint restore, the virtio-serial port may be
+ // "disconnected" until the host connects to the chardev Unix socket.
+ // We poll for readability to avoid returning a conn that immediately errors.
for {
select {
case <-l.closed:
@@ -98,22 +100,45 @@ func (l *virtioSerialListener) Accept() (net.Conn, error) {
l.mu.Lock()
if !l.active {
- l.active = true
+ // Wait for port to be readable (host connected to chardev socket)
l.mu.Unlock()
- return &virtioSerialConn{
- f: l.f,
- onClose: func() {
- l.mu.Lock()
- l.active = false
+ if waitForReadable(l.f, 500*time.Millisecond) {
+ l.mu.Lock()
+ if !l.active {
+ l.active = true
l.mu.Unlock()
- },
- }, nil
+ log.Printf("agent: virtio-serial Accept: port readable, accepting connection")
+ return &virtioSerialConn{
+ f: l.f,
+ onClose: func() {
+ l.mu.Lock()
+ l.active = false
+ l.mu.Unlock()
+ },
+ }, nil
+ }
+ l.mu.Unlock()
+ }
+ continue
}
l.mu.Unlock()
time.Sleep(100 * time.Millisecond)
}
}
+// waitForReadable polls a file for readability using poll(2).
+// Returns true if the fd becomes readable within the timeout.
+func waitForReadable(f *os.File, timeout time.Duration) bool {
+ fd := int32(f.Fd())
+ timeoutMs := int(timeout.Milliseconds())
+ fds := []unix.PollFd{{Fd: fd, Events: unix.POLLIN}}
+ n, err := unix.Poll(fds, timeoutMs)
+ if err != nil || n <= 0 {
+ return false
+ }
+ return fds[0].Revents&(unix.POLLIN|unix.POLLHUP) != 0
+}
+
func (l *virtioSerialListener) Close() error {
l.once.Do(func() { close(l.closed) })
return l.f.Close()
diff --git a/cmd/server/main.go b/cmd/server/main.go
index 16910fb6..ddad1641 100644
--- a/cmd/server/main.go
+++ b/cmd/server/main.go
@@ -17,7 +17,6 @@ import (
"github.com/opensandbox/opensandbox/internal/config"
"github.com/opensandbox/opensandbox/internal/controlplane"
"github.com/opensandbox/opensandbox/internal/db"
- "github.com/opensandbox/opensandbox/internal/ecr"
"github.com/opensandbox/opensandbox/internal/proxy"
"github.com/opensandbox/opensandbox/internal/sandbox"
"github.com/opensandbox/opensandbox/internal/storage"
@@ -106,19 +105,6 @@ func main() {
}
}
- // Initialize ECR config for template images (if configured)
- if cfg.ECRRegistry != "" {
- ecrCfg := &ecr.Config{
- Registry: cfg.ECRRegistry,
- Repository: cfg.ECRRepository,
- Region: cfg.S3Region, // reuse S3 region (same AWS account)
- AccessKey: cfg.S3AccessKeyID,
- SecretKey: cfg.S3SecretAccessKey,
- }
- opts.ECRConfig = ecrCfg
- log.Printf("opensandbox: ECR configured (registry=%s, repo=%s)", cfg.ECRRegistry, cfg.ECRRepository)
- }
-
// Set sandbox domain for API responses
if cfg.SandboxDomain != "" && cfg.SandboxDomain != "localhost" {
opts.SandboxDomain = cfg.SandboxDomain
diff --git a/deploy/ec2/deploy-qemu-dev.sh b/deploy/ec2/deploy-qemu-dev.sh
index c3b62b30..b3626077 100755
--- a/deploy/ec2/deploy-qemu-dev.sh
+++ b/deploy/ec2/deploy-qemu-dev.sh
@@ -387,9 +387,19 @@ sudo iptables -C FORWARD -d 172.16.0.0/16 -m conntrack --ctstate RELATED,ESTABLI
sudo sysctl -w net.ipv4.ip_forward=1 > /dev/null
sudo sysctl -w net.ipv4.conf.all.route_localnet=1 > /dev/null
-# Redirect port 80 -> 8080 so UI is accessible on standard HTTP port
-sudo iptables -t nat -C PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080 2>/dev/null || \
- sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080
+# Redirect port 80 -> 8080 so UI is accessible on standard HTTP port.
+# Only match traffic destined for the host's own IPs — don't intercept
+# VM outbound HTTP traffic (e.g., apt-get to archive.ubuntu.com).
+PRIVATE_IP=\$(ip -4 addr show \$(ip route show default | awk '{print \$5}' | head -1) | awk '/inet / {print \$2}' | cut -d/ -f1)
+PUBLIC_IP=\$(curl -s -m 2 http://169.254.169.254/latest/meta-data/public-ipv4 2>/dev/null || echo "")
+if [ -n "\$PRIVATE_IP" ]; then
+ sudo iptables -t nat -C PREROUTING -p tcp --dport 80 -d "\$PRIVATE_IP" -j REDIRECT --to-port 8080 2>/dev/null || \
+ sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -d "\$PRIVATE_IP" -j REDIRECT --to-port 8080
+fi
+if [ -n "\$PUBLIC_IP" ]; then
+ sudo iptables -t nat -C PREROUTING -p tcp --dport 80 -d "\$PUBLIC_IP" -j REDIRECT --to-port 8080 2>/dev/null || \
+ sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -d "\$PUBLIC_IP" -j REDIRECT --to-port 8080
+fi
sudo systemctl daemon-reload
sudo systemctl restart opensandbox-server || true
diff --git a/internal/api/router.go b/internal/api/router.go
index fd260085..61dd9e69 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -15,7 +15,6 @@ import (
"github.com/opensandbox/opensandbox/internal/cloudflare"
"github.com/opensandbox/opensandbox/internal/controlplane"
"github.com/opensandbox/opensandbox/internal/db"
- "github.com/opensandbox/opensandbox/internal/ecr"
"github.com/opensandbox/opensandbox/internal/proxy"
"github.com/opensandbox/opensandbox/internal/sandbox"
"github.com/opensandbox/opensandbox/internal/storage"
@@ -43,7 +42,6 @@ type Server struct {
workerRegistry *controlplane.RedisWorkerRegistry // nil in combined/worker mode
checkpointStore *storage.CheckpointStore // nil if hibernation not configured
sandboxDomain string // base domain for sandbox subdomains
- ecrConfig *ecr.Config // nil if ECR not configured
cfClient *cloudflare.Client // nil if Cloudflare not configured
pendingCreates sync.Map // map[sandboxID]*pendingCreate — async sandbox creation tracking
sandboxAPIProxy *proxy.SandboxAPIProxy // nil except in server mode (proxies data-plane to workers)
@@ -72,7 +70,6 @@ type ServerOpts struct {
WorkOSConfig *auth.WorkOSConfig // nil if WorkOS not configured
WorkerRegistry *controlplane.RedisWorkerRegistry // nil in combined/worker mode
CheckpointStore *storage.CheckpointStore // nil if hibernation not configured
- ECRConfig *ecr.Config // nil if ECR not configured
CFClient *cloudflare.Client // nil if Cloudflare not configured
SandboxAPIProxy *proxy.SandboxAPIProxy // nil except in server mode (proxies data-plane to workers)
}
@@ -102,7 +99,6 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
s.workerRegistry = opts.WorkerRegistry
s.checkpointStore = opts.CheckpointStore
s.sandboxDomain = opts.SandboxDomain
- s.ecrConfig = opts.ECRConfig
s.cfClient = opts.CFClient
s.sandboxAPIProxy = opts.SandboxAPIProxy
}
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index e576f042..21ec97ab 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -237,14 +237,12 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty
})
}
- // Resolve template image from DB (org-scoped lookup with public fallback)
- var imageRef string
+ // Resolve template from DB (org-scoped lookup with public fallback)
var templateRootfsKey, templateWorkspaceKey string
var templateID *uuid.UUID
if s.store != nil && hasOrg {
tmpl, err := s.store.GetTemplateByName(ctx, orgID, cfg.Template)
if err == nil {
- imageRef = tmpl.ImageRef
templateID = &tmpl.ID
log.Printf("sandbox: resolved template %q (type=%s, id=%s)", cfg.Template, tmpl.TemplateType, tmpl.ID)
// Sandbox-type templates provide S3 drive keys instead of ECR image refs
@@ -274,7 +272,6 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty
MemoryMb: int32(cfg.MemoryMB),
CpuCount: int32(cfg.CpuCount),
NetworkEnabled: cfg.NetworkEnabled,
- ImageRef: imageRef,
Port: int32(cfg.Port),
TemplateRootfsKey: templateRootfsKey,
TemplateWorkspaceKey: templateWorkspaceKey,
diff --git a/internal/config/config.go b/internal/config/config.go
index 733e7958..8dff997d 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -61,10 +61,6 @@ type Config struct {
S3SecretAccessKey string
S3ForcePathStyle bool // true for R2/MinIO
- // ECR for template images
- ECRRegistry string // e.g. "086971355112.dkr.ecr.us-east-2.amazonaws.com"
- ECRRepository string // e.g. "opensandbox-templates"
-
// Sandbox resource defaults (overridable per-sandbox via API)
DefaultSandboxMemoryMB int // default RAM per sandbox (MB), default 1024
DefaultSandboxCPUs int // default vCPUs per sandbox, default 1
@@ -149,9 +145,6 @@ func Load() (*Config, error) {
S3SecretAccessKey: os.Getenv("OPENSANDBOX_S3_SECRET_ACCESS_KEY"),
S3ForcePathStyle: os.Getenv("OPENSANDBOX_S3_FORCE_PATH_STYLE") == "true",
- ECRRegistry: os.Getenv("OPENSANDBOX_ECR_REGISTRY"),
- ECRRepository: envOrDefault("OPENSANDBOX_ECR_REPOSITORY", "opensandbox-templates"),
-
DefaultSandboxMemoryMB: envOrDefaultInt("OPENSANDBOX_DEFAULT_SANDBOX_MEMORY_MB", 1024),
DefaultSandboxCPUs: envOrDefaultInt("OPENSANDBOX_DEFAULT_SANDBOX_CPUS", 1),
DefaultSandboxDiskMB: envOrDefaultInt("OPENSANDBOX_DEFAULT_SANDBOX_DISK_MB", 0),
diff --git a/internal/db/store.go b/internal/db/store.go
index 79ddd02f..b8c71f51 100644
--- a/internal/db/store.go
+++ b/internal/db/store.go
@@ -1055,21 +1055,6 @@ func scanTemplate(row interface{ Scan(...any) error }, t *DBTemplate) error {
return row.Scan(&t.ID, &t.OrgID, &t.Name, &t.Tag, &t.ImageRef, &t.Dockerfile, &t.IsPublic, &t.TemplateType, &t.RootfsS3Key, &t.WorkspaceS3Key, &t.CreatedBySandboxID, &t.Status, &t.CreatedAt)
}
-// CreateTemplate inserts a new dockerfile-based template record.
-func (s *Store) CreateTemplate(ctx context.Context, orgID *uuid.UUID, name, tag, imageRef string, dockerfile *string, isPublic bool) (*DBTemplate, error) {
- t := &DBTemplate{}
- err := scanTemplate(s.pool.QueryRow(ctx,
- `INSERT INTO templates (org_id, name, tag, image_ref, dockerfile, is_public, template_type)
- VALUES ($1, $2, $3, $4, $5, $6, 'dockerfile')
- RETURNING `+templateColumns,
- orgID, name, tag, imageRef, dockerfile, isPublic,
- ), t)
- if err != nil {
- return nil, fmt.Errorf("failed to create template: %w", err)
- }
- return t, nil
-}
-
// CreateSandboxTemplate inserts a new sandbox-snapshot template record (status=processing).
func (s *Store) CreateSandboxTemplate(ctx context.Context, id uuid.UUID, orgID *uuid.UUID, name, tag, rootfsS3Key, workspaceS3Key, createdBySandboxID string) (*DBTemplate, error) {
t := &DBTemplate{}
diff --git a/internal/ecr/auth.go b/internal/ecr/auth.go
deleted file mode 100644
index 64f16a13..00000000
--- a/internal/ecr/auth.go
+++ /dev/null
@@ -1,92 +0,0 @@
-package ecr
-
-import (
- "context"
- "encoding/base64"
- "fmt"
- "strings"
-
- "github.com/aws/aws-sdk-go-v2/aws"
- awsconfig "github.com/aws/aws-sdk-go-v2/config"
- "github.com/aws/aws-sdk-go-v2/credentials"
- "github.com/aws/aws-sdk-go-v2/service/ecr"
-)
-
-// Config holds ECR connection settings.
-type Config struct {
- Registry string // e.g. "086971355112.dkr.ecr.us-east-2.amazonaws.com"
- Repository string // e.g. "opensandbox-templates"
- Region string // e.g. "us-east-2"
- AccessKey string
- SecretKey string
-}
-
-// IsConfigured returns true if ECR settings are provided.
-// Works with either static credentials or IAM (when AccessKey is empty but Registry+Repository are set).
-func (c *Config) IsConfigured() bool {
- return c.Registry != "" && c.Repository != ""
-}
-
-// GetAuthToken retrieves a Docker-compatible auth token from ECR.
-// Returns (username, password) suitable for container registry login.
-// If AccessKey is empty, uses the default AWS credential chain (IAM instance profile on EC2).
-func GetAuthToken(ctx context.Context, cfg *Config) (string, string, error) {
- var client *ecr.Client
-
- if cfg.AccessKey != "" {
- // Static credentials
- awsCfg := aws.Config{
- Region: cfg.Region,
- Credentials: credentials.NewStaticCredentialsProvider(cfg.AccessKey, cfg.SecretKey, ""),
- }
- client = ecr.NewFromConfig(awsCfg)
- } else {
- // IAM credential chain
- awsCfg, err := awsconfig.LoadDefaultConfig(ctx,
- awsconfig.WithRegion(cfg.Region),
- )
- if err != nil {
- return "", "", fmt.Errorf("failed to load AWS config for ECR: %w", err)
- }
- client = ecr.NewFromConfig(awsCfg)
- }
- output, err := client.GetAuthorizationToken(ctx, &ecr.GetAuthorizationTokenInput{})
- if err != nil {
- return "", "", fmt.Errorf("failed to get ECR auth token: %w", err)
- }
-
- if len(output.AuthorizationData) == 0 {
- return "", "", fmt.Errorf("no authorization data returned from ECR")
- }
-
- // Token is base64-encoded "username:password"
- encoded := *output.AuthorizationData[0].AuthorizationToken
- decoded, err := base64.StdEncoding.DecodeString(encoded)
- if err != nil {
- return "", "", fmt.Errorf("failed to decode ECR auth token: %w", err)
- }
-
- parts := strings.SplitN(string(decoded), ":", 2)
- if len(parts) != 2 {
- return "", "", fmt.Errorf("unexpected ECR auth token format")
- }
-
- return parts[0], parts[1], nil
-}
-
-// ImageRef returns the full ECR image reference for an org-scoped template.
-// Format: {registry}/{repo}:{orgPrefix}-{name}-{tag}
-func ImageRef(cfg *Config, orgID, name, tag string) string {
- // Use first 8 chars of orgID as prefix to keep tags manageable
- prefix := orgID
- if len(prefix) > 8 {
- prefix = prefix[:8]
- }
- return fmt.Sprintf("%s/%s:%s-%s-%s", cfg.Registry, cfg.Repository, prefix, name, tag)
-}
-
-// PublicImageRef returns the full ECR image reference for a public template.
-// Format: {registry}/{repo}:public-{name}-{tag}
-func PublicImageRef(cfg *Config, name, tag string) string {
- return fmt.Sprintf("%s/%s:public-%s-%s", cfg.Registry, cfg.Repository, name, tag)
-}
diff --git a/internal/firecracker/manager.go b/internal/firecracker/manager.go
index 22c6337d..4faf2cac 100644
--- a/internal/firecracker/manager.go
+++ b/internal/firecracker/manager.go
@@ -876,11 +876,6 @@ func (m *Manager) Wake(ctx context.Context, sandboxID string, checkpointKey stri
return m.doWake(ctx, sandboxID, checkpointKey, checkpointStore, timeout)
}
-// SaveAsTemplate is deprecated. Use the declarative image builder instead.
-func (m *Manager) SaveAsTemplate(ctx context.Context, sandboxID, templateID string, checkpointStore *storage.CheckpointStore, onReady func()) (rootfsKey, workspaceKey string, err error) {
- return "", "", fmt.Errorf("deprecated: use declarative image builder")
-}
-
// getVM retrieves a VM by ID (read-locked).
func (m *Manager) getVM(id string) (*VMInstance, error) {
m.mu.RLock()
diff --git a/internal/firecracker/snapshot.go b/internal/firecracker/snapshot.go
index ebaa3801..55de2c2d 100644
--- a/internal/firecracker/snapshot.go
+++ b/internal/firecracker/snapshot.go
@@ -757,151 +757,6 @@ func fileExists(path string) bool {
return err == nil && !info.IsDir()
}
-// --- Save as Template ---
-
-// doSaveAsTemplate snapshots a running sandbox's drives for use as a reusable template.
-// The VM is briefly paused while the drives are copied, then resumed. The user's sandbox
-// continues running uninterrupted; the copied drives are compressed and uploaded to S3 async.
-//
-// Template drives are cached locally at {DataDir}/templates/{templateID}/ so that creating
-// new sandboxes from this template is a fast reflink copy (no S3 download needed on the
-// same worker). S3 is the durable backup for cross-worker use.
-//
-// Flow:
-// 1. SyncFS via agent (flush disk buffers — agent stays alive)
-// 2. Close gRPC connection (vsock must be inactive for pause)
-// 3. Pause VM
-// 4. Copy rootfs.ext4 and workspace.ext4 to template cache dir (reflink — instant on XFS)
-// 5. Resume VM
-// 6. Reconnect agent
-// 7. (async) Compress cached drives → upload to S3 (cache stays on disk)
-func (m *Manager) doSaveAsTemplate(ctx context.Context, vm *VMInstance, templateID string, checkpointStore *storage.CheckpointStore, onReady func()) (rootfsKey, workspaceKey string, err error) {
- t0 := time.Now()
-
- rootfsKey = fmt.Sprintf("templates/%s/rootfs.tar.zst", templateID)
- workspaceKey = fmt.Sprintf("templates/%s/workspace.sparse.zst", templateID)
-
- srcRootfs := filepath.Join(vm.sandboxDir, "rootfs.ext4")
- srcWorkspace := filepath.Join(vm.sandboxDir, "workspace.ext4")
-
- // Cache template drives locally for fast reflink-based creation
- cacheDir := m.templateCacheDir(templateID)
- if err := os.MkdirAll(cacheDir, 0755); err != nil {
- return "", "", fmt.Errorf("create template cache dir: %w", err)
- }
- cachedRootfs := filepath.Join(cacheDir, "rootfs.ext4")
- cachedWorkspace := filepath.Join(cacheDir, "workspace.ext4")
-
- // Step 1: Flush guest filesystem data to disk.
- // Use exec-based sync because syscall.Sync() from PID 1 doesn't reliably flush
- // dirty pages to virtio-blk after snapshot restore.
- if vm.agent != nil {
- syncCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
- _, syncErr := vm.agent.Exec(syncCtx, &pb.ExecRequest{
- Command: "sync",
- })
- cancel()
- if syncErr != nil {
- log.Printf("firecracker: SaveAsTemplate %s: exec sync warning: %v", vm.ID, syncErr)
- }
- }
-
- // Step 2: Close gRPC connection (vsock must be inactive before Firecracker pause).
- // Drain delay prevents stale vsock virtqueue entries from breaking vhost-vsock after restore.
- if vm.agent != nil {
- vm.agent.Close()
- vm.agent = nil
- time.Sleep(500 * time.Millisecond)
- }
-
- // Step 3: Pause the VM
- if err = vm.fcClient.PauseVM(); err != nil {
- // Try to reconnect agent even on error so the VM stays usable
- if agent, reconnErr := m.waitForAgent(ctx, vm.vsockPath, 5*time.Second); reconnErr == nil {
- vm.agent = agent
- }
- os.RemoveAll(cacheDir)
- return "", "", fmt.Errorf("pause VM for template snapshot: %w", err)
- }
- log.Printf("firecracker: SaveAsTemplate %s: VM paused (%dms)", vm.ID, time.Since(t0).Milliseconds())
-
- // Step 4: Host-side fsync as insurance — guest sync should have already flushed.
- for _, drivePath := range []string{srcRootfs, srcWorkspace} {
- if f, err := os.OpenFile(drivePath, os.O_RDWR, 0); err == nil {
- f.Sync()
- f.Close()
- }
- }
-
- // Step 4b: Copy drive files while VM is paused (drives are stable)
- copyErr := copyFileReflink(srcRootfs, cachedRootfs)
- if copyErr == nil {
- copyErr = copyFileReflink(srcWorkspace, cachedWorkspace)
- if copyErr != nil {
- os.Remove(cachedRootfs)
- }
- }
-
- // Step 5: Resume the VM regardless of copy result
- resumeErr := vm.fcClient.ResumeVM()
- if resumeErr != nil {
- log.Printf("firecracker: SaveAsTemplate %s: CRITICAL: resume failed: %v", vm.ID, resumeErr)
- os.RemoveAll(cacheDir)
- return "", "", fmt.Errorf("resume VM after template snapshot: %w", resumeErr)
- }
- log.Printf("firecracker: SaveAsTemplate %s: VM resumed (%dms)", vm.ID, time.Since(t0).Milliseconds())
-
- if copyErr != nil {
- // Reconnect agent since VM is running again
- if agent, reconnErr := m.waitForAgent(ctx, vm.vsockPath, 10*time.Second); reconnErr == nil {
- vm.agent = agent
- }
- os.RemoveAll(cacheDir)
- return "", "", fmt.Errorf("copy drives for template: %w", copyErr)
- }
-
- // Step 6: Reconnect agent (it was running inside the VM the whole time — just paused)
- agent, reconnErr := m.waitForAgent(ctx, vm.vsockPath, 10*time.Second)
- if reconnErr != nil {
- log.Printf("firecracker: SaveAsTemplate %s: agent reconnect failed: %v (VM still running)", vm.ID, reconnErr)
- } else {
- vm.agent = agent
- // Sync guest clock — paused during snapshot
- if err := syncGuestClock(ctx, agent); err != nil {
- log.Printf("firecracker: SaveAsTemplate %s: clock sync failed: %v", vm.ID, err)
- }
- }
-
- // Step 7: Async compress + upload (cached drives stay on disk for fast local creation)
- sandboxID := vm.ID
- m.uploadWg.Add(1)
- go func() {
- defer m.uploadWg.Done()
-
- uploadCtx, cancel := context.WithTimeout(context.Background(), 15*time.Minute)
- defer cancel()
-
- t1 := time.Now()
- if err := compressAndUploadFile(uploadCtx, cachedRootfs, rootfsKey, checkpointStore); err != nil {
- log.Printf("firecracker: template %s: rootfs upload failed for sandbox %s: %v", templateID, sandboxID, err)
- return
- }
- log.Printf("firecracker: template %s: rootfs uploaded (%dms)", templateID, time.Since(t1).Milliseconds())
-
- t2 := time.Now()
- if err := sparseCompressAndUpload(uploadCtx, cachedWorkspace, workspaceKey, checkpointStore); err != nil {
- log.Printf("firecracker: template %s: workspace upload failed for sandbox %s: %v", templateID, sandboxID, err)
- return
- }
- log.Printf("firecracker: template %s: ready (%dms, total=%dms)", templateID, time.Since(t2).Milliseconds(), time.Since(t0).Milliseconds())
- if onReady != nil {
- onReady()
- }
- }()
-
- return rootfsKey, workspaceKey, nil
-}
-
// templateCacheDir returns the local cache directory for a template's ext4 drives.
func (m *Manager) templateCacheDir(templateID string) string {
return filepath.Join(m.cfg.DataDir, "templates", templateID)
diff --git a/internal/podman/client.go b/internal/podman/client.go
deleted file mode 100644
index b0c6a9c7..00000000
--- a/internal/podman/client.go
+++ /dev/null
@@ -1,130 +0,0 @@
-package podman
-
-import (
- "bytes"
- "context"
- "encoding/json"
- "fmt"
- "os"
- "os/exec"
- "path/filepath"
- "strings"
-)
-
-// Client wraps the podman CLI for image build operations (template building).
-// Podman is used purely as a build tool (like Docker) to create ext4 rootfs images
-// from Dockerfiles. It is NOT used as a container runtime — Firecracker handles that.
-type Client struct {
- binaryPath string
- authFile string // dedicated auth file to avoid Docker credential helper conflicts
-}
-
-// NewClient creates a new Podman client. It verifies podman is available.
-func NewClient() (*Client, error) {
- path, err := exec.LookPath("podman")
- if err != nil {
- return nil, fmt.Errorf("podman not found in PATH: %w", err)
- }
-
- // Create a dedicated auth file so Podman doesn't inherit Docker Desktop's
- // credential helpers (docker-credential-gcloud, docker-credential-desktop, etc.)
- authFile, err := ensureAuthFile()
- if err != nil {
- return nil, fmt.Errorf("failed to set up podman auth: %w", err)
- }
-
- return &Client{binaryPath: path, authFile: authFile}, nil
-}
-
-// AuthFile returns the path to the dedicated auth file.
-func (c *Client) AuthFile() string {
- return c.authFile
-}
-
-func ensureAuthFile() (string, error) {
- home, err := os.UserHomeDir()
- if err != nil {
- return "", err
- }
- dir := filepath.Join(home, ".config", "opensandbox")
- if err := os.MkdirAll(dir, 0700); err != nil {
- return "", err
- }
- authFile := filepath.Join(dir, "auth.json")
- if _, err := os.Stat(authFile); os.IsNotExist(err) {
- if err := os.WriteFile(authFile, []byte(`{"auths":{}}`), 0600); err != nil {
- return "", err
- }
- }
- return authFile, nil
-}
-
-// ExecResult holds the output from a podman command.
-type ExecResult struct {
- Stdout string
- Stderr string
- ExitCode int
-}
-
-// Run executes a podman command and returns the result.
-func (c *Client) Run(ctx context.Context, args ...string) (*ExecResult, error) {
- cmd := exec.CommandContext(ctx, c.binaryPath, args...)
- cmd.Env = append(os.Environ(), "REGISTRY_AUTH_FILE="+c.authFile)
- var stdout, stderr bytes.Buffer
- cmd.Stdout = &stdout
- cmd.Stderr = &stderr
-
- err := cmd.Run()
-
- result := &ExecResult{
- Stdout: stdout.String(),
- Stderr: stderr.String(),
- }
-
- if err != nil {
- if exitErr, ok := err.(*exec.ExitError); ok {
- result.ExitCode = exitErr.ExitCode()
- return result, nil
- }
- return result, fmt.Errorf("podman exec failed: %w", err)
- }
-
- return result, nil
-}
-
-// RunJSON executes a podman command and parses JSON output into dest.
-func (c *Client) RunJSON(ctx context.Context, dest interface{}, args ...string) error {
- result, err := c.Run(ctx, args...)
- if err != nil {
- return err
- }
- if result.ExitCode != 0 {
- return fmt.Errorf("podman %s failed (exit %d): %s",
- strings.Join(args, " "), result.ExitCode, strings.TrimSpace(result.Stderr))
- }
- if err := json.Unmarshal([]byte(result.Stdout), dest); err != nil {
- return fmt.Errorf("failed to parse podman output: %w", err)
- }
- return nil
-}
-
-// LoginRegistry authenticates podman to a container registry.
-func (c *Client) LoginRegistry(ctx context.Context, registry, username, password string) error {
- result, err := c.Run(ctx, "login", "--username", username, "--password", password, registry)
- if err != nil {
- return fmt.Errorf("failed to login to registry %s: %w", registry, err)
- }
- if result.ExitCode != 0 {
- return fmt.Errorf("podman login failed (exit %d): %s", result.ExitCode, strings.TrimSpace(result.Stderr))
- }
- return nil
-}
-
-// Version returns the podman version string.
-func (c *Client) Version(ctx context.Context) (string, error) {
- result, err := c.Run(ctx, "version", "--format", "{{.Client.Version}}")
- if err != nil {
- return "", err
- }
- return strings.TrimSpace(result.Stdout), nil
-}
diff --git a/internal/qemu/docs_compliance_test.go b/internal/qemu/docs_compliance_test.go
new file mode 100644
index 00000000..403a7eb5
--- /dev/null
+++ b/internal/qemu/docs_compliance_test.go
@@ -0,0 +1,404 @@
+// Package qemu — docs_compliance_test.go
+//
+// Verifies that the QEMU backend implements every operation documented in
+// docs/reference/api.mdx and the sandbox.Manager interface. This is a
+// compile-time + reflection test — it does NOT require KVM or a running VM.
+package qemu
+
+import (
+ "context"
+ "reflect"
+ "testing"
+
+ "github.com/opensandbox/opensandbox/internal/sandbox"
+ "github.com/opensandbox/opensandbox/internal/storage"
+ "github.com/opensandbox/opensandbox/pkg/types"
+)
+
+// TestManagerImplementsInterface is a compile-time check that *Manager
+// satisfies sandbox.Manager. The var _ line in manager.go does this too,
+// but having it in a test makes failures visible in CI.
+func TestManagerImplementsInterface(t *testing.T) {
+ var _ sandbox.Manager = (*Manager)(nil)
+}
+
+// TestDocumentedLifecycleOps checks that every sandbox lifecycle operation
+// documented in reference/api.mdx has a corresponding Manager method.
+//
+// Docs:
+// POST /api/sandboxes → Create
+// GET /api/sandboxes → List
+// GET /api/sandboxes/:id → Get
+// DELETE /api/sandboxes/:id → Kill
+// POST .../hibernate → Hibernate
+// POST .../wake → Wake
+func TestDocumentedLifecycleOps(t *testing.T) {
+ methods := managerMethods()
+
+ required := map[string]string{
+ "Create": "POST /api/sandboxes",
+ "List": "GET /api/sandboxes",
+ "Get": "GET /api/sandboxes/:id",
+ "Kill": "DELETE /api/sandboxes/:id",
+ "Count": "GET /api/sandboxes (count variant)",
+ "Close": "graceful shutdown",
+ "Hibernate": "POST /api/sandboxes/:id/hibernate",
+ "Wake": "POST /api/sandboxes/:id/wake",
+ }
+
+ for method, doc := range required {
+ if !methods[method] {
+ t.Errorf("Manager missing %s (docs: %s)", method, doc)
+ }
+ }
+}
+
+// TestDocumentedExecOps checks command execution.
+//
+// Docs:
+// POST .../exec/run → Exec (sync)
+// POST .../exec → CreateExecSession (handled by worker HTTP layer)
+// GET .../exec → ListExecSessions (handled by worker HTTP layer)
+//
+// The Manager only exposes sync Exec; session management is in the worker HTTP server.
+func TestDocumentedExecOps(t *testing.T) {
+ methods := managerMethods()
+
+ if !methods["Exec"] {
+ t.Error("Manager missing Exec (docs: POST .../exec/run)")
+ }
+}
+
+// TestDocumentedFilesystemOps checks every filesystem operation.
+//
+// Docs:
+// GET .../files?path= → ReadFile
+// PUT .../files?path= → WriteFile
+// GET .../files/list?path= → ListDir
+// POST .../files/mkdir → MakeDir
+// DELETE .../files?path= → Remove
+func TestDocumentedFilesystemOps(t *testing.T) {
+ methods := managerMethods()
+
+ required := map[string]string{
+ "ReadFile": "GET .../files?path=",
+ "WriteFile": "PUT .../files?path=",
+ "ListDir": "GET .../files/list?path=",
+ "MakeDir": "POST .../files/mkdir",
+ "Remove": "DELETE .../files?path=",
+ "Exists": "existence check (used by worker)",
+ "Stat": "file stat (used by worker)",
+ }
+
+ for method, doc := range required {
+ if !methods[method] {
+ t.Errorf("Manager missing %s (docs: %s)", method, doc)
+ }
+ }
+}
+
+// TestDocumentedCheckpointOps checks checkpoint operations.
+//
+// Docs:
+// POST .../checkpoints → CreateCheckpoint
+// POST .../checkpoints/:id/restore → RestoreFromCheckpoint
+// POST /api/sandboxes/from-checkpoint/:id → ForkFromCheckpoint
+// GET .../checkpoints → (list — DB layer, not manager)
+// DELETE .../checkpoints/:id → (delete — DB layer, not manager)
+func TestDocumentedCheckpointOps(t *testing.T) {
+ methods := managerMethods()
+
+ required := map[string]string{
+ "CreateCheckpoint": "POST .../checkpoints",
+ "RestoreFromCheckpoint": "POST .../checkpoints/:id/restore",
+ "ForkFromCheckpoint": "POST /api/sandboxes/from-checkpoint/:id",
+ "CheckpointCachePath": "local cache path for checkpoint drives",
+ }
+
+ for method, doc := range required {
+ if !methods[method] {
+ t.Errorf("Manager missing %s (docs: %s)", method, doc)
+ }
+ }
+}
+
+// TestDocumentedTemplateOps checks template operations.
+//
+// Templates are created via the declarative snapshot API (POST /api/snapshots).
+// SaveAsTemplate (snapshot a running VM) was removed — it's replaced by
+// CreateCheckpoint + ForkFromCheckpoint for runtime cloning.
+func TestDocumentedTemplateOps(t *testing.T) {
+ methods := managerMethods()
+
+ if !methods["TemplateCachePath"] {
+ t.Error("Manager missing TemplateCachePath method")
+ }
+}
+
+// TestDocumentedMonitoringOps checks monitoring operations.
+func TestDocumentedMonitoringOps(t *testing.T) {
+ methods := managerMethods()
+
+ required := map[string]string{
+ "Stats": "sandbox CPU/memory stats",
+ "HostPort": "mapped host port for preview URLs",
+ "ContainerAddr": "guest address for port forwarding",
+ "DataDir": "data directory path",
+ "ContainerName": "sandbox name for logging",
+ }
+
+ for method, doc := range required {
+ if !methods[method] {
+ t.Errorf("Manager missing %s (docs: %s)", method, doc)
+ }
+ }
+}
+
+// TestDocumentedParameterNames checks that types.SandboxConfig field names
+// match what the API docs specify.
+//
+// Docs say: templateID, timeout, cpuCount, memoryMB, envs, metadata
+func TestDocumentedParameterNames(t *testing.T) {
+ cfg := types.SandboxConfig{}
+ v := reflect.TypeOf(cfg)
+
+ expectedJSON := map[string]bool{
+ "templateID": false,
+ "timeout": false,
+ "cpuCount": false,
+ "memoryMB": false,
+ "envs": false,
+ "metadata": false,
+ }
+
+ for i := range v.NumField() {
+ field := v.Field(i)
+ tag := field.Tag.Get("json")
+ // Strip options like ",omitempty"
+ if idx := len(tag); idx > 0 {
+ for j := range len(tag) {
+ if tag[j] == ',' {
+ tag = tag[:j]
+ break
+ }
+ }
+ }
+ if _, ok := expectedJSON[tag]; ok {
+ expectedJSON[tag] = true
+ }
+ }
+
+ for name, found := range expectedJSON {
+ if !found {
+ t.Errorf("SandboxConfig missing JSON field %q (documented in API reference)", name)
+ }
+ }
+}
+
+// TestDocumentedProcessConfigFields checks types.ProcessConfig matches docs.
+//
+// Docs say: cmd, args, envs, cwd, timeout
+func TestDocumentedProcessConfigFields(t *testing.T) {
+ cfg := types.ProcessConfig{}
+ v := reflect.TypeOf(cfg)
+
+ expectedJSON := map[string]bool{
+ "cmd": false,
+ "args": false,
+ "envs": false,
+ "cwd": false,
+ "timeout": false,
+ }
+
+ for i := range v.NumField() {
+ field := v.Field(i)
+ tag := field.Tag.Get("json")
+ for j := range len(tag) {
+ if tag[j] == ',' {
+ tag = tag[:j]
+ break
+ }
+ }
+ if _, ok := expectedJSON[tag]; ok {
+ expectedJSON[tag] = true
+ }
+ }
+
+ for name, found := range expectedJSON {
+ if !found {
+ t.Errorf("ProcessConfig missing JSON field %q (documented in API reference)", name)
+ }
+ }
+}
+
+// TestDocumentedSandboxResponseFields checks that types.Sandbox has the
+// fields the API docs say the create/get response returns.
+//
+// Docs say: sandboxID, templateID, status, startedAt, endAt, cpuCount, memoryMB,
+// metadata, connectURL, token
+func TestDocumentedSandboxResponseFields(t *testing.T) {
+ sb := types.Sandbox{}
+ v := reflect.TypeOf(sb)
+
+ expectedJSON := map[string]bool{
+ "sandboxID": false,
+ "status": false,
+ "startedAt": false,
+ "endAt": false,
+ "cpuCount": false,
+ "memoryMB": false,
+ "connectURL": false,
+ "token": false,
+ }
+
+ for i := range v.NumField() {
+ field := v.Field(i)
+ tag := field.Tag.Get("json")
+ for j := range len(tag) {
+ if tag[j] == ',' {
+ tag = tag[:j]
+ break
+ }
+ }
+ if _, ok := expectedJSON[tag]; ok {
+ expectedJSON[tag] = true
+ }
+ }
+
+ for name, found := range expectedJSON {
+ if !found {
+ t.Errorf("Sandbox struct missing JSON field %q (documented in API response)", name)
+ }
+ }
+}
+
+// TestDocumentedDefaultValues verifies that QEMU manager defaults match docs.
+//
+// Docs say: cpuCount=1, memoryMB=512, timeout=300, port=80
+func TestDocumentedDefaultValues(t *testing.T) {
+ // NewManager applies defaults to zero-valued Config fields.
+ // We simulate that logic here since NewManager needs real dirs.
+ cfg := Config{DataDir: "/tmp"}
+ // Apply the same defaults as NewManager (lines 110-120 of manager.go)
+ if cfg.DefaultMemoryMB == 0 {
+ cfg.DefaultMemoryMB = 512
+ }
+ if cfg.DefaultCPUs == 0 {
+ cfg.DefaultCPUs = 1
+ }
+ if cfg.DefaultPort == 0 {
+ cfg.DefaultPort = 80
+ }
+
+ tests := []struct {
+ name string
+ got int
+ expected int
+ }{
+ {"DefaultCPUs (docs: 1)", cfg.DefaultCPUs, 1},
+ {"DefaultMemoryMB (docs: 512)", cfg.DefaultMemoryMB, 512},
+ {"DefaultPort (docs: 80)", cfg.DefaultPort, 80},
+ }
+
+ for _, tt := range tests {
+ if tt.got != tt.expected {
+ t.Errorf("%s: got %d, want %d", tt.name, tt.got, tt.expected)
+ }
+ }
+}
+
+// TestDocumentedHibernateResponseFields checks HibernateResult matches docs.
+//
+// Docs say response includes: sandboxID, hibernationKey, sizeBytes
+func TestDocumentedHibernateResponseFields(t *testing.T) {
+ hr := sandbox.HibernateResult{}
+ v := reflect.TypeOf(hr)
+
+ expectedJSON := map[string]bool{
+ "sandboxId": false,
+ "hibernationKey": false,
+ "sizeBytes": false,
+ }
+
+ for i := range v.NumField() {
+ field := v.Field(i)
+ tag := field.Tag.Get("json")
+ for j := range len(tag) {
+ if tag[j] == ',' {
+ tag = tag[:j]
+ break
+ }
+ }
+ if _, ok := expectedJSON[tag]; ok {
+ expectedJSON[tag] = true
+ }
+ }
+
+ for name, found := range expectedJSON {
+ if !found {
+ t.Errorf("HibernateResult missing JSON field %q (documented in API response)", name)
+ }
+ }
+}
+
+// TestRouteToTemplateEndpointMismatch documents that the router uses
+// /api/snapshots while the docs say /api/templates.
+func TestRouteToTemplateEndpointMismatch(t *testing.T) {
+ t.Log("KNOWN GAP: Router exposes /api/snapshots but docs reference /api/templates")
+ t.Log("Docs: POST /api/templates, GET /api/templates, etc.")
+ t.Log("Router: POST /api/snapshots, GET /api/snapshots, etc.")
+}
+
+// TestDocReferencesFirecracker documents all places where docs say
+// "Firecracker" but the QEMU backend is the actual implementation.
+func TestDocReferencesFirecracker(t *testing.T) {
+ firecrackerRefs := []struct {
+ file string
+ text string
+ }{
+ {"docs/introduction.mdx", "isolated Firecracker microVM"},
+ {"docs/introduction.mdx", "Hardware-level isolation via Firecracker"},
+ {"docs/how-it-works.mdx", "provisions a Firecracker microVM"},
+ {"docs/how-it-works.mdx", "A Firecracker microVM boots in ~150ms"},
+ {"docs/how-it-works.mdx", "section title: Firecracker microVMs"},
+ {"docs/quickstart.mdx", "You created a cloud VM (Firecracker microVM)"},
+ {"docs/cli/sandbox.mdx", "provisions a new Firecracker microVM"},
+ {"docs/reference/api.mdx", "filesystem image that Firecracker boots from"},
+ {"docs/sandboxes/templates.mdx", "filesystem image that Firecracker boots as the VM's root disk"},
+ }
+
+ t.Log("KNOWN GAP: Docs reference 'Firecracker' but this branch uses QEMU q35 backend")
+ for _, ref := range firecrackerRefs {
+ t.Logf(" %s: %q", ref.file, ref.text)
+ }
+}
+
+// ── Helpers ──────────────────────────────────────────────────────────────────
+
+// managerMethods returns a set of all exported method names on *Manager.
+func managerMethods() map[string]bool {
+ t := reflect.TypeOf((*Manager)(nil))
+ methods := make(map[string]bool, t.NumMethod())
+ for i := range t.NumMethod() {
+ methods[t.Method(i).Name] = true
+ }
+ return methods
+}
+
+// Compile-time checks that documented method signatures match.
+// These won't compile if the signatures drift from what the interface requires.
+var (
+ _ func(context.Context, types.SandboxConfig) (*types.Sandbox, error) = (*Manager)(nil).Create
+ _ func(context.Context, string) (*types.Sandbox, error) = (*Manager)(nil).Get
+ _ func(context.Context, string) error = (*Manager)(nil).Kill
+ _ func(context.Context) ([]types.Sandbox, error) = (*Manager)(nil).List
+ _ func(context.Context, string, types.ProcessConfig) (*types.ProcessResult, error) = (*Manager)(nil).Exec
+ _ func(context.Context, string, string) (string, error) = (*Manager)(nil).ReadFile
+ _ func(context.Context, string, string, string) error = (*Manager)(nil).WriteFile
+ _ func(context.Context, string, string) ([]types.EntryInfo, error) = (*Manager)(nil).ListDir
+ _ func(context.Context, string, *storage.CheckpointStore) (*sandbox.HibernateResult, error) = (*Manager)(nil).Hibernate
+ _ func(context.Context, string, string, *storage.CheckpointStore, int) (*types.Sandbox, error) = (*Manager)(nil).Wake
+ _ func(context.Context, string, string, *storage.CheckpointStore, func()) (string, string, error) = (*Manager)(nil).CreateCheckpoint
+ _ func(context.Context, string, string) error = (*Manager)(nil).RestoreFromCheckpoint
+ _ func(context.Context, string, types.SandboxConfig) (*types.Sandbox, error) = (*Manager)(nil).ForkFromCheckpoint
+)
diff --git a/internal/qemu/manager.go b/internal/qemu/manager.go
index 5ab333f2..5fb678bb 100644
--- a/internal/qemu/manager.go
+++ b/internal/qemu/manager.go
@@ -549,6 +549,11 @@ func (m *Manager) createFromGolden(ctx context.Context, cfg types.SandboxConfig,
log.Printf("qemu: golden-create %s: network patch failed: %v", id, err)
}
+ // Sync guest clock — golden snapshot has stale time
+ if err := syncGuestClock(context.Background(), agentClient); err != nil {
+ log.Printf("qemu: golden-create %s: clock sync failed: %v", id, err)
+ }
+
// Mount /workspace — the golden snapshot was taken with /workspace unmounted
// to keep the vdb device state clean for fresh workspace qcow2 files.
mountCtx, mountCancel := context.WithTimeout(context.Background(), 10*time.Second)
@@ -1413,11 +1418,6 @@ func (m *Manager) Wake(ctx context.Context, sandboxID string, checkpointKey stri
return m.doWake(ctx, sandboxID, checkpointKey, checkpointStore, timeout)
}
-// SaveAsTemplate is not implemented in the QEMU backend.
-func (m *Manager) SaveAsTemplate(ctx context.Context, sandboxID, templateID string, checkpointStore *storage.CheckpointStore, onReady func()) (rootfsKey, workspaceKey string, err error) {
- return "", "", ErrNotImplemented
-}
-
// TemplateCachePath returns "" — not implemented.
func (m *Manager) TemplateCachePath(templateID, filename string) string {
return ""
@@ -1452,14 +1452,22 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID
return "", "", fmt.Errorf("no QMP client for VM %s", sandboxID)
}
- // Sync filesystem before snapshot
+ // Sync filesystem and close agent before snapshot. Closing the agent
+ // puts it in Accept() mode — when ForkFromCheckpoint restores from this
+ // checkpoint, the agent immediately accepts the new connection (~1ms)
+ // instead of waiting for the stale gRPC stream to time out (~6s).
if vm.agent != nil {
syncCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
- _, syncErr := vm.agent.Exec(syncCtx, &pb.ExecRequest{Command: "sync"})
+ _, syncErr := vm.agent.Exec(syncCtx, &pb.ExecRequest{
+ Command: "/bin/sh",
+ Args: []string{"-c", "umount /workspace 2>/dev/null; sync"},
+ })
cancel()
if syncErr != nil {
log.Printf("qemu: CreateCheckpoint %s/%s: sync failed: %v", sandboxID, checkpointID, syncErr)
}
+ vm.agent.Close()
+ vm.agent = nil
}
// savevm creates an internal snapshot — memory + device state + disk deltas
@@ -1470,6 +1478,20 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID
}
log.Printf("qemu: CreateCheckpoint %s/%s: savevm complete (%dms)", sandboxID, checkpointID, time.Since(t0).Milliseconds())
+ // Reconnect agent + remount workspace (VM resumed after savevm)
+ agentClient, reconnErr := m.waitForAgentSocket(context.Background(), vm.agentSockPath, 10*time.Second)
+ if reconnErr != nil {
+ log.Printf("qemu: CreateCheckpoint %s/%s: agent reconnect failed: %v", sandboxID, checkpointID, reconnErr)
+ } else {
+ vm.agent = agentClient
+ mountCtx, mountCancel := context.WithTimeout(context.Background(), 5*time.Second)
+ _, _ = agentClient.Exec(mountCtx, &pb.ExecRequest{
+ Command: "/bin/sh",
+ Args: []string{"-c", "echo 3 > /proc/sys/vm/drop_caches; mount /dev/vdb /workspace 2>/dev/null || true"},
+ })
+ mountCancel()
+ }
+
// Also cache the drive files for ForkFromCheckpoint (which needs a separate QEMU process)
cacheDir := m.checkpointCacheDir(checkpointID)
rootfsKey = fmt.Sprintf("checkpoints/%s/%s/rootfs.tar.zst", sandboxID, checkpointID)
@@ -1567,6 +1589,18 @@ func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpoi
}
vm.agent = agent
+ // Remount workspace + drop caches (loadvm reverted to checkpoint state)
+ restoreCtx, restoreCancel := context.WithTimeout(context.Background(), 5*time.Second)
+ _, _ = agent.Exec(restoreCtx, &pb.ExecRequest{
+ Command: "/bin/sh",
+ Args: []string{"-c", "echo 3 > /proc/sys/vm/drop_caches; mount /dev/vdb /workspace 2>/dev/null || true"},
+ })
+ restoreCancel()
+
+ if err := syncGuestClock(context.Background(), agent); err != nil {
+ log.Printf("qemu: RestoreFromCheckpoint %s: clock sync failed: %v", sandboxID, err)
+ }
+
log.Printf("qemu: RestoreFromCheckpoint %s/%s: loadvm complete (%dms)", sandboxID, checkpointID, time.Since(t0).Milliseconds())
return nil
}
@@ -1733,7 +1767,18 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, c
return nil, fmt.Errorf("agent connect: %w", err)
}
- // Patch network (snapshot had different IP)
+ // Drop caches (checkpoint had different rootfs state) + mount workspace + patch network
+ postCtx, postCancel := context.WithTimeout(context.Background(), 10*time.Second)
+ _, _ = agent.Exec(postCtx, &pb.ExecRequest{
+ Command: "/bin/sh",
+ Args: []string{"-c", "echo 3 > /proc/sys/vm/drop_caches; mount /dev/vdb /workspace 2>/dev/null || true"},
+ })
+ postCancel()
+
+ if err := syncGuestClock(context.Background(), agent); err != nil {
+ log.Printf("qemu: ForkFromCheckpoint %s: clock sync failed: %v", id, err)
+ }
+
if err := patchGuestNetwork(context.Background(), agent, netCfg); err != nil {
log.Printf("qemu: ForkFromCheckpoint %s: network patch failed: %v", id, err)
}
diff --git a/internal/sandbox/interface.go b/internal/sandbox/interface.go
index 733b6e24..5da04f94 100644
--- a/internal/sandbox/interface.go
+++ b/internal/sandbox/interface.go
@@ -62,11 +62,6 @@ type Manager interface {
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)
- // SaveAsTemplate snapshots a running sandbox's drives (rootfs + workspace) for use as a
- // template. The VM is briefly paused during file copy then resumed. Archive upload is async.
- // Returns the pre-computed storage keys immediately. onReady is called when the async upload finishes (may be nil).
- SaveAsTemplate(ctx context.Context, sandboxID, templateID string, checkpointStore *storage.CheckpointStore, onReady func()) (rootfsKey, workspaceKey string, err error)
-
// TemplateCachePath returns the local path to a cached template drive file (e.g., "rootfs.ext4"),
// or "" if the template is not cached locally. Used to skip S3 download when creating from template.
TemplateCachePath(templateID, filename string) string
diff --git a/internal/template/builder.go b/internal/template/builder.go
deleted file mode 100644
index 835d9d30..00000000
--- a/internal/template/builder.go
+++ /dev/null
@@ -1,371 +0,0 @@
-package template
-
-import (
- "context"
- "fmt"
- "log"
- "os"
- "os/exec"
- "path/filepath"
- "strings"
-
- "github.com/opensandbox/opensandbox/internal/podman"
-)
-
-// 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
- 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.
-// 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,
- imagesDir: imagesDir,
- agentPath: agentPath,
- }
-}
-
-// 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"
- }
-
- localImage := fmt.Sprintf("localhost/opensandbox-template/%s:%s", name, tag)
-
- // Write Dockerfile to temp directory
- tmpDir, err := os.MkdirTemp("", "opensandbox-build-*")
- if err != nil {
- return "", "", fmt.Errorf("failed to create temp dir for build: %w", err)
- }
- 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(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)
- }
- if result.ExitCode != 0 {
- return "", "", fmt.Errorf("podman build failed (exit %d): %s", result.ExitCode, result.Stderr)
- }
- buildLog := result.Stdout + result.Stderr
-
- // 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)
- }
-
- // 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)
- }
-
- // 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 overlay mount points exist
-RUN mkdir -p /mnt/data /mnt/overlay
-`
- 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
-}
-
-// 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)))
- }
- }
-
- // 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", "run", "mnt/data", "mnt/overlay"} {
- 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)))
- }
-
- // 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)))
- }
-
- return nil
-}
-
-// generateInitScript creates the /sbin/init script for Firecracker VMs.
-// Uses overlayfs + pivot_root so that the data disk (/dev/vdb) backs all
-// filesystem writes, making the VM behave like a normal machine with one big disk.
-func generateInitScript() string {
- return `#!/bin/busybox sh
-# OpenSandbox VM init script
-# Runs as PID 1 inside the Firecracker microVM
-
-# Mount minimal virtual filesystems needed for setup
-mount -t proc proc /proc
-mount -t devtmpfs devtmpfs /dev
-
-# ── Overlay root: data disk as writable upper layer over the rootfs ──
-# This makes ALL writes (npm install, apt install, etc.) go to the NVMe-backed
-# data disk instead of the small rootfs image.
-mkdir -p /mnt/data
-if mount /dev/vdb /mnt/data 2>/dev/null || mount /dev/vdb1 /mnt/data 2>/dev/null; then
- mkdir -p /mnt/data/upper /mnt/data/work /mnt/overlay
-
- # Unmount virtual filesystems before pivot (will re-mount after)
- umount /dev
- umount /proc
-
- # Create overlay: rootfs (lower/read-only) + data disk (upper/writable)
- mount -t overlay overlay -o lowerdir=/,upperdir=/mnt/data/upper,workdir=/mnt/data/work /mnt/overlay
-
- # Move data disk mount into the overlay tree so it persists after pivot
- mkdir -p /mnt/overlay/mnt/data
- mount --move /mnt/data /mnt/overlay/mnt/data
-
- # Pivot root to the overlay
- cd /mnt/overlay
- mkdir -p mnt/old_root
- pivot_root . mnt/old_root
-
- # Detach old root
- umount -l /mnt/old_root 2>/dev/null
- rmdir /mnt/old_root 2>/dev/null
-
- echo "init: overlay root active (data disk backing all writes)"
-else
- # No data disk available — fall back to rootfs-only (writes hit the small rootfs)
- umount /dev
- umount /proc
- echo "init: warning: no data disk found, running on rootfs only"
-fi
-
-# ── Mount virtual filesystems (in the final root) ──
-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
-
-# 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()
-
- out, err := os.Create(dst)
- if err != nil {
- 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 nil
-}
diff --git a/internal/template/registry.go b/internal/template/registry.go
deleted file mode 100644
index 36fb26ac..00000000
--- a/internal/template/registry.go
+++ /dev/null
@@ -1,89 +0,0 @@
-package template
-
-import (
- "fmt"
- "sync"
- "time"
-
- "github.com/opensandbox/opensandbox/pkg/types"
-)
-
-// Registry stores template metadata in-memory.
-type Registry struct {
- mu sync.RWMutex
- templates map[string]*types.Template // keyed by name
-}
-
-// NewRegistry creates a new template registry with default templates.
-func NewRegistry() *Registry {
- r := &Registry{
- templates: make(map[string]*types.Template),
- }
-
- // Register default templates
- defaults := []struct {
- name string
- imageID string
- }{
- {"base", "docker.io/library/ubuntu:22.04"},
- {"python", "docker.io/library/python:3.12-slim"},
- {"node", "docker.io/library/node:20-slim"},
- }
-
- now := time.Now()
- for _, d := range defaults {
- r.templates[d.name] = &types.Template{
- ID: d.name,
- Name: d.name,
- Tag: "latest",
- ImageID: d.imageID,
- Status: "ready",
- CreatedAt: now,
- }
- }
-
- return r
-}
-
-// Get returns a template by name.
-func (r *Registry) Get(name string) (*types.Template, error) {
- r.mu.RLock()
- defer r.mu.RUnlock()
-
- t, ok := r.templates[name]
- if !ok {
- return nil, fmt.Errorf("template %q not found", name)
- }
- return t, nil
-}
-
-// List returns all templates.
-func (r *Registry) List() []types.Template {
- r.mu.RLock()
- defer r.mu.RUnlock()
-
- result := make([]types.Template, 0, len(r.templates))
- for _, t := range r.templates {
- result = append(result, *t)
- }
- return result
-}
-
-// Register adds or updates a template.
-func (r *Registry) Register(t *types.Template) {
- r.mu.Lock()
- defer r.mu.Unlock()
- r.templates[t.Name] = t
-}
-
-// Delete removes a template by name. Returns error if it's a default template.
-func (r *Registry) Delete(name string) error {
- r.mu.Lock()
- defer r.mu.Unlock()
-
- if _, ok := r.templates[name]; !ok {
- return fmt.Errorf("template %q not found", name)
- }
- delete(r.templates, name)
- return nil
-}
diff --git a/internal/template/registry_test.go b/internal/template/registry_test.go
deleted file mode 100644
index c2e71aa0..00000000
--- a/internal/template/registry_test.go
+++ /dev/null
@@ -1,70 +0,0 @@
-package template
-
-import (
- "testing"
-
- "github.com/opensandbox/opensandbox/pkg/types"
-)
-
-func TestNewRegistry_HasDefaults(t *testing.T) {
- r := NewRegistry()
- templates := r.List()
- if len(templates) != 3 {
- t.Fatalf("expected 3 default templates, got %d", len(templates))
- }
-
- base, err := r.Get("base")
- if err != nil {
- t.Fatalf("Get(base) error: %v", err)
- }
- if base.ImageID != "docker.io/library/ubuntu:22.04" {
- t.Errorf("expected ubuntu image, got %s", base.ImageID)
- }
-}
-
-func TestRegistry_RegisterAndGet(t *testing.T) {
- r := NewRegistry()
- r.Register(&types.Template{
- ID: "custom",
- Name: "custom",
- Tag: "v1",
- ImageID: "test-image",
- Status: "ready",
- })
-
- tmpl, err := r.Get("custom")
- if err != nil {
- t.Fatalf("Get(custom) error: %v", err)
- }
- if tmpl.Tag != "v1" {
- t.Errorf("expected tag v1, got %s", tmpl.Tag)
- }
-}
-
-func TestRegistry_Delete(t *testing.T) {
- r := NewRegistry()
- if err := r.Delete("base"); err != nil {
- t.Fatalf("Delete(base) error: %v", err)
- }
-
- _, err := r.Get("base")
- if err == nil {
- t.Error("expected error after deleting base template")
- }
-}
-
-func TestRegistry_DeleteNotFound(t *testing.T) {
- r := NewRegistry()
- err := r.Delete("nonexistent")
- if err == nil {
- t.Error("expected error for nonexistent template")
- }
-}
-
-func TestRegistry_GetNotFound(t *testing.T) {
- r := NewRegistry()
- _, err := r.Get("nonexistent")
- if err == nil {
- t.Error("expected error for nonexistent template")
- }
-}
diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.go
index 12f9da3c..c026063f 100644
--- a/internal/worker/grpc_server.go
+++ b/internal/worker/grpc_server.go
@@ -15,9 +15,6 @@ import (
"google.golang.org/grpc"
"google.golang.org/grpc/keepalive"
- "google.golang.org/grpc/codes"
- "google.golang.org/grpc/status"
-
"github.com/opensandbox/opensandbox/internal/db"
"github.com/opensandbox/opensandbox/internal/sandbox"
"github.com/opensandbox/opensandbox/internal/sparse"
@@ -86,7 +83,6 @@ func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxReq
MemoryMB: int(req.MemoryMb),
CpuCount: int(req.CpuCount),
NetworkEnabled: req.NetworkEnabled,
- ImageRef: req.ImageRef,
Port: int(req.Port),
SandboxID: req.SandboxId, // use server-assigned ID if provided
}
@@ -496,14 +492,6 @@ func (s *GRPCServer) WakeSandbox(ctx context.Context, req *pb.WakeSandboxRequest
}, nil
}
-func (s *GRPCServer) BuildTemplate(ctx context.Context, req *pb.BuildTemplateRequest) (*pb.BuildTemplateResponse, error) {
- return nil, status.Errorf(codes.Unimplemented, "deprecated")
-}
-
-func (s *GRPCServer) SaveAsTemplate(ctx context.Context, req *pb.SaveAsTemplateRequest) (*pb.SaveAsTemplateResponse, error) {
- return nil, status.Errorf(codes.Unimplemented, "deprecated")
-}
-
func (s *GRPCServer) CreateCheckpoint(ctx context.Context, req *pb.CreateCheckpointRequest) (*pb.CreateCheckpointResponse, error) {
checkpointID := req.CheckpointId
if _, err := uuid.Parse(checkpointID); err != nil {
diff --git a/pkg/types/sandbox.go b/pkg/types/sandbox.go
index a64be3af..dc390eed 100644
--- a/pkg/types/sandbox.go
+++ b/pkg/types/sandbox.go
@@ -44,7 +44,6 @@ type SandboxConfig struct {
Envs map[string]string `json:"envs,omitempty"`
Port int `json:"port,omitempty"` // container port to expose via subdomain (default 80)
NetworkEnabled bool `json:"networkEnabled,omitempty"`
- ImageRef string `json:"imageRef,omitempty"` // resolved ECR URI for custom templates
// Sandbox snapshot template: S3 keys for rootfs and workspace drives.
// When set, the sandbox boots from these drives instead of the standard base image.
TemplateRootfsKey string `json:"templateRootfsKey,omitempty"`