Skip to content

An open-source, faster Devin alternative

TypeScript

remove podman legacy runtime

Brian Reardona17d6de8940f
diff --git a/HANDOFF.md b/HANDOFF.md
index ae53d5ef..cbe89480 100644
--- a/HANDOFF.md
+++ b/HANDOFF.md
@@ -82,8 +82,8 @@ ASYNC SYNC (background):
| File | What it does |
|------|-------------|
-| `cmd/server/main.go` | Wires up: Podman, sandbox/PTY managers, templates, PG + migrations, JWT, SQLite, NATS consumer |
-| `cmd/worker/main.go` | Wires up: Podman, sandbox/PTY managers, SQLite, JWT, gRPC (:9090), HTTP (cfg.Port), NATS publisher, metrics (:9091), image pre-pulling |
+| `cmd/server/main.go` | Wires up: control plane, PG + migrations, JWT, SQLite, NATS consumer |
+| `cmd/worker/main.go` | Wires up: Firecracker VM manager, PTY manager, SQLite, JWT, gRPC (:9090), HTTP (cfg.Port), NATS publisher, metrics (:9091) |
---
@@ -127,7 +127,6 @@ No frontend exists. The plan calls for a web dashboard with:
### Prerequisites
- Go 1.23+
-- Podman installed and running
- Docker (for infrastructure containers)
### Tier 1 — Simplest (no PG, no auth)
@@ -229,8 +228,9 @@ internal/
event_publisher.go — NATS publisher (events + heartbeats)
sandbox/
- manager.go — Container lifecycle (Podman)
- pty.go — PTY session management
+ interface.go — Manager interface + types
+ router.go — Sandbox routing, auto-wake, rolling timeouts
+ pty.go — PTY session management (Firecracker agent gRPC)
sqlite.go — Per-sandbox SQLite
compute/
diff --git a/cmd/server/main.go b/cmd/server/main.go
index 6d7c7b3e..f4c6f2cf 100644
--- a/cmd/server/main.go
+++ b/cmd/server/main.go
@@ -5,7 +5,6 @@ import (
"fmt"
"log"
"os"
- "os/exec"
"os/signal"
"syscall"
@@ -19,7 +18,6 @@ import (
"github.com/opensandbox/opensandbox/internal/controlplane"
"github.com/opensandbox/opensandbox/internal/db"
"github.com/opensandbox/opensandbox/internal/ecr"
- "github.com/opensandbox/opensandbox/internal/podman"
"github.com/opensandbox/opensandbox/internal/proxy"
"github.com/opensandbox/opensandbox/internal/sandbox"
"github.com/opensandbox/opensandbox/internal/storage"
@@ -33,34 +31,11 @@ func main() {
ctx := context.Background()
- // Initialize Podman (skipped in server mode — server delegates to workers via gRPC)
+ // Server mode delegates sandbox management to workers via gRPC.
+ // There is no local sandbox manager on the server.
var mgr sandbox.Manager
var ptyMgr *sandbox.PTYManager
- if cfg.Mode == "server" {
- log.Printf("opensandbox: server mode — skipping local podman/sandbox manager (delegating to workers)")
- } else {
- podmanClient, err := podman.NewClient()
- if err != nil {
- log.Fatalf("failed to initialize podman: %v", err)
- }
- version, err := podmanClient.Version(ctx)
- if err != nil {
- log.Fatalf("failed to get podman version: %v", err)
- }
- log.Printf("opensandbox: using podman %s", version)
-
- mgr = sandbox.NewManager(podmanClient,
- sandbox.WithDataDir(cfg.DataDir),
- sandbox.WithDefaultMemoryMB(cfg.DefaultSandboxMemoryMB),
- sandbox.WithDefaultCPUs(cfg.DefaultSandboxCPUs),
- sandbox.WithDefaultDiskMB(cfg.DefaultSandboxDiskMB),
- )
- defer mgr.Close()
-
- podmanPath, _ := exec.LookPath("podman")
- ptyMgr = sandbox.NewPTYManager(podmanPath, podmanClient.AuthFile())
- defer ptyMgr.CloseAll()
- }
+ log.Printf("opensandbox: server mode — delegating sandbox management to workers via gRPC")
// Build server options
opts := &api.ServerOpts{
@@ -144,45 +119,7 @@ func main() {
log.Printf("opensandbox: ECR configured (registry=%s, repo=%s)", cfg.ECRRegistry, cfg.ECRRepository)
}
- // Initialize SandboxRouter for rolling timeouts, auto-wake, and command routing
- if mgr != nil {
- workerID := cfg.WorkerID
- if workerID == "" {
- workerID = "w-local-1"
- }
- sbRouter := sandbox.NewSandboxRouter(sandbox.RouterConfig{
- Manager: mgr,
- CheckpointStore: opts.CheckpointStore,
- Store: opts.Store,
- WorkerID: workerID,
- OnHibernate: func(sandboxID string, result *sandbox.HibernateResult) {
- log.Printf("opensandbox: sandbox %s auto-hibernated (key=%s, size=%d bytes)",
- sandboxID, result.HibernationKey, result.SizeBytes)
- if opts.Store != nil {
- _ = opts.Store.UpdateSandboxSessionStatus(context.Background(), sandboxID, "hibernated", nil)
- }
- },
- OnKill: func(sandboxID string) {
- log.Printf("opensandbox: sandbox %s killed on timeout", sandboxID)
- if opts.Store != nil {
- _ = opts.Store.UpdateSandboxSessionStatus(context.Background(), sandboxID, "stopped", nil)
- }
- },
- })
- defer sbRouter.Close()
- opts.Router = sbRouter
- log.Println("opensandbox: sandbox router initialized (rolling timeouts, auto-wake)")
-
- // Initialize subdomain reverse proxy
- if cfg.SandboxDomain != "" {
- sbProxy := proxy.New(cfg.SandboxDomain, mgr, sbRouter)
- opts.SandboxProxy = sbProxy
- opts.SandboxDomain = cfg.SandboxDomain
- log.Printf("opensandbox: subdomain proxy configured (*.%s)", cfg.SandboxDomain)
- }
- }
-
- // Set sandbox domain for API responses (works in both server and combined mode)
+ // Set sandbox domain for API responses
if cfg.SandboxDomain != "" && cfg.SandboxDomain != "localhost" {
opts.SandboxDomain = cfg.SandboxDomain
log.Printf("opensandbox: sandbox domain configured (%s)", cfg.SandboxDomain)
diff --git a/deploy/ec2/README.md b/deploy/ec2/README.md
index 4146ad24..07685591 100644
--- a/deploy/ec2/README.md
+++ b/deploy/ec2/README.md
@@ -4,9 +4,7 @@
| Component | Version | Notes |
|-----------|---------|-------|
-| Podman | 5.8.0 | Rootful, used for sandbox containers |
-| CRIU | 4.2 | Checkpoint/restore for hibernation |
-| crun | 1.26 | OCI runtime with +CRIU support |
+| Firecracker | latest | MicroVM hypervisor for sandbox isolation |
| Caddy | latest | Wildcard TLS for `*.workers.opencomputer.dev` (DNS-01 via Route53) |
| Redis | 7.0.15 | Local, used for sandbox state/routing |
| Go worker | custom | `/usr/local/bin/opensandbox-worker` |
@@ -23,10 +21,10 @@ Caddy (port 443) -- wildcard TLS for *.workers.opencomputer.dev (DNS-01 via Rout
opensandbox-worker (port 8080) -- HTTP API + gRPC (9090)
|
v
-Podman containers (osb-*) -- one per sandbox
+Firecracker microVMs -- one per sandbox
|
v
-CRIU checkpoint/restore -- hibernate to S3, wake on demand
+Snapshot hibernate/wake -- pause to S3, resume on demand
```
## Scripts
@@ -54,7 +52,4 @@ sudo journalctl -u caddy -f
# Restart worker
sudo systemctl restart opensandbox-worker
-
-# List running sandboxes
-sudo podman ps --filter label=opensandbox.id
```
diff --git a/internal/ecr/auth.go b/internal/ecr/auth.go
index acf25038..64f16a13 100644
--- a/internal/ecr/auth.go
+++ b/internal/ecr/auth.go
@@ -28,7 +28,7 @@ func (c *Config) IsConfigured() bool {
}
// GetAuthToken retrieves a Docker-compatible auth token from ECR.
-// Returns (username, password) suitable for `podman login`.
+// 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
diff --git a/internal/metrics/metrics.go b/internal/metrics/metrics.go
index 722da2a5..4f714058 100644
--- a/internal/metrics/metrics.go
+++ b/internal/metrics/metrics.go
@@ -54,15 +54,6 @@ var (
[]string{"region", "worker_id"},
)
- PodmanOpDuration = prometheus.NewHistogramVec(
- prometheus.HistogramOpts{
- Name: "opensandbox_podman_op_duration_seconds",
- Help: "Time for podman operations",
- Buckets: []float64{0.01, 0.05, 0.1, 0.5, 1.0, 5.0},
- },
- []string{"operation"},
- )
-
DirectConnectionsActive = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "opensandbox_direct_connections_active",
@@ -131,7 +122,6 @@ func init() {
ExecDuration,
PTYSessionsActive,
WorkerUtilization,
- PodmanOpDuration,
DirectConnectionsActive,
SQLiteSyncLag,
HTTPRequestsTotal,
diff --git a/internal/podman/client.go b/internal/podman/client.go
index 5375addb..b0c6a9c7 100644
--- a/internal/podman/client.go
+++ b/internal/podman/client.go
@@ -5,20 +5,18 @@ import (
"context"
"encoding/json"
"fmt"
- "io"
- "net"
"os"
"os/exec"
"path/filepath"
- "runtime"
"strings"
)
-// Client wraps the podman CLI for container operations.
+// 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
- useSSH bool // true when checkpoint/restore must run inside a Podman machine VM (macOS)
}
// NewClient creates a new Podman client. It verifies podman is available.
@@ -35,15 +33,7 @@ func NewClient() (*Client, error) {
return nil, fmt.Errorf("failed to set up podman auth: %w", err)
}
- client := &Client{binaryPath: path, authFile: authFile}
-
- // Detect if we're on macOS (remote podman). Checkpoint/restore requires
- // running inside the VM via "podman machine ssh".
- if runtime.GOOS == "darwin" {
- client.useSSH = true
- }
-
- return client, nil
+ return &Client{binaryPath: path, authFile: authFile}, nil
}
// AuthFile returns the path to the dedicated auth file.
@@ -118,219 +108,6 @@ func (c *Client) RunJSON(ctx context.Context, dest interface{}, args ...string)
return nil
}
-// runSSH executes a command inside the Podman machine VM via "podman machine ssh".
-func (c *Client) runSSH(ctx context.Context, sshCmd string) (*ExecResult, error) {
- cmd := exec.CommandContext(ctx, c.binaryPath, "machine", "ssh", sshCmd)
- 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 machine ssh failed: %w", err)
- }
-
- return result, nil
-}
-
-// CheckpointContainer checkpoints a running container and exports to a tar archive.
-// Uses zstd compression for optimized checkpoint size.
-// On macOS, checkpoint runs inside the Podman machine VM via SSH because
-// the remote podman client doesn't support CRIU checkpoint operations.
-func (c *Client) CheckpointContainer(ctx context.Context, nameOrID, exportPath string) error {
- if c.useSSH {
- // exportPath is a VM-local path (e.g. /tmp/...) since we'll copy it out separately
- sshCmd := fmt.Sprintf("podman container checkpoint --tcp-established --export %s --compress zstd %s", exportPath, nameOrID)
- result, err := c.runSSH(ctx, sshCmd)
- if err != nil {
- return fmt.Errorf("failed to checkpoint container %s: %w", nameOrID, err)
- }
- if result.ExitCode != 0 {
- return fmt.Errorf("podman checkpoint failed (exit %d): %s", result.ExitCode, strings.TrimSpace(result.Stderr))
- }
- return nil
- }
-
- result, err := c.Run(ctx, "container", "checkpoint", "--tcp-established", "--export", exportPath, "--compress", "zstd", nameOrID)
- if err != nil {
- return fmt.Errorf("failed to checkpoint container %s: %w", nameOrID, err)
- }
- if result.ExitCode != 0 {
- return fmt.Errorf("podman checkpoint failed (exit %d): %s", result.ExitCode, strings.TrimSpace(result.Stderr))
- }
- return nil
-}
-
-// RestoreContainer restores a container from a checkpoint archive on disk.
-// On macOS, restore runs inside the Podman machine VM via SSH.
-// It force-removes any existing container with the same name first to avoid
-// "that ID is already in use" errors from previous restore cycles.
-func (c *Client) RestoreContainer(ctx context.Context, importPath, name string) error {
- // Pre-cleanup: remove any existing container with this name to avoid ID conflicts.
- // This is best-effort — the container may not exist, which is fine.
- _ = c.RemoveContainer(ctx, name, true)
-
- if c.useSSH {
- sshCmd := fmt.Sprintf("podman container restore --tcp-established --import %s", importPath)
- result, err := c.runSSH(ctx, sshCmd)
- if err != nil {
- return fmt.Errorf("failed to restore container %s: %w", name, err)
- }
- if result.ExitCode != 0 {
- return fmt.Errorf("podman restore failed (exit %d): %s", result.ExitCode, strings.TrimSpace(result.Stderr))
- }
- return nil
- }
-
- result, err := c.Run(ctx, "container", "restore", "--tcp-established", "--import", importPath)
- if err != nil {
- return fmt.Errorf("failed to restore container %s: %w", name, err)
- }
- if result.ExitCode != 0 {
- return fmt.Errorf("podman restore failed (exit %d): %s", result.ExitCode, strings.TrimSpace(result.Stderr))
- }
- return nil
-}
-
-// CopyFromVM copies a file from the Podman machine VM to the local host (macOS only).
-func (c *Client) CopyFromVM(ctx context.Context, vmPath, localPath string) error {
- // podman machine ssh "cat <vmPath>" > localPath
- cmd := exec.CommandContext(ctx, c.binaryPath, "machine", "ssh", "cat "+vmPath)
- outFile, err := os.Create(localPath)
- if err != nil {
- return fmt.Errorf("failed to create local file %s: %w", localPath, err)
- }
- defer outFile.Close()
- cmd.Stdout = outFile
- var stderr bytes.Buffer
- cmd.Stderr = &stderr
- if err := cmd.Run(); err != nil {
- return fmt.Errorf("failed to copy from VM: %s", strings.TrimSpace(stderr.String()))
- }
- return nil
-}
-
-// CopyToVM copies a file from the local host to the Podman machine VM (macOS only).
-func (c *Client) CopyToVM(ctx context.Context, localPath, vmPath string) error {
- // cat localPath | podman machine ssh "cat > <vmPath>"
- inFile, err := os.Open(localPath)
- if err != nil {
- return fmt.Errorf("failed to open local file %s: %w", localPath, err)
- }
- defer inFile.Close()
- cmd := exec.CommandContext(ctx, c.binaryPath, "machine", "ssh", "cat > "+vmPath)
- cmd.Stdin = inFile
- var stderr bytes.Buffer
- cmd.Stderr = &stderr
- if err := cmd.Run(); err != nil {
- return fmt.Errorf("failed to copy to VM: %s", strings.TrimSpace(stderr.String()))
- }
- return nil
-}
-
-// RemoveVMFile removes a file inside the Podman machine VM (macOS only).
-func (c *Client) RemoveVMFile(ctx context.Context, vmPath string) error {
- _, err := c.runSSH(ctx, "rm -f "+vmPath)
- return err
-}
-
-// UseSSH returns whether the client routes checkpoint/restore through VM SSH.
-func (c *Client) UseSSH() bool {
- return c.useSSH
-}
-
-// RestoreContainerFromStream restores a container by piping a checkpoint archive
-// from an io.Reader (e.g., S3 download body) into podman via a named FIFO pipe.
-// This avoids writing the full checkpoint to local disk.
-// On macOS, streams through the VM: write to local temp file, copy to VM, restore from VM path.
-func (c *Client) RestoreContainerFromStream(ctx context.Context, reader io.Reader, name string) error {
- if c.useSSH {
- // On macOS, we can't use FIFOs across the VM boundary.
- // Write to local temp, copy into VM, restore from VM path.
- tmpFile, err := os.CreateTemp("", "osb-restore-*.tar.zst")
- if err != nil {
- return fmt.Errorf("failed to create temp file: %w", err)
- }
- localPath := tmpFile.Name()
- defer os.Remove(localPath)
-
- if _, err := io.Copy(tmpFile, reader); err != nil {
- tmpFile.Close()
- return fmt.Errorf("failed to write checkpoint to temp file: %w", err)
- }
- tmpFile.Close()
-
- vmPath := "/tmp/osb-restore-" + filepath.Base(localPath)
- if err := c.CopyToVM(ctx, localPath, vmPath); err != nil {
- return fmt.Errorf("failed to copy checkpoint to VM: %w", err)
- }
- defer c.RemoveVMFile(ctx, vmPath)
-
- return c.RestoreContainer(ctx, vmPath, name)
- }
-
- // Download to temp file, then restore from file
- tmpFile, err := os.CreateTemp("", "osb-restore-*.tar.zst")
- if err != nil {
- return fmt.Errorf("failed to create temp file: %w", err)
- }
- localPath := tmpFile.Name()
- defer os.Remove(localPath)
-
- if _, err := io.Copy(tmpFile, reader); err != nil {
- tmpFile.Close()
- return fmt.Errorf("failed to write checkpoint to temp file: %w", err)
- }
- tmpFile.Close()
-
- return c.RestoreContainer(ctx, localPath, name)
-}
-
-// FindFreePort asks the OS for a free TCP port by listening on :0.
-func FindFreePort() (int, error) {
- l, err := net.Listen("tcp", ":0")
- if err != nil {
- return 0, fmt.Errorf("failed to find free port: %w", err)
- }
- port := l.Addr().(*net.TCPAddr).Port
- l.Close()
- return port, nil
-}
-
-// TagImage tags a local image with a new name/reference.
-func (c *Client) TagImage(ctx context.Context, source, target string) error {
- result, err := c.Run(ctx, "tag", source, target)
- if err != nil {
- return fmt.Errorf("failed to tag image: %w", err)
- }
- if result.ExitCode != 0 {
- return fmt.Errorf("podman tag failed (exit %d): %s", result.ExitCode, strings.TrimSpace(result.Stderr))
- }
- return nil
-}
-
-// PushImage pushes an image to a remote registry.
-func (c *Client) PushImage(ctx context.Context, imageRef string) error {
- result, err := c.Run(ctx, "push", imageRef)
- if err != nil {
- return fmt.Errorf("failed to push image %s: %w", imageRef, err)
- }
- if result.ExitCode != 0 {
- return fmt.Errorf("podman push failed (exit %d): %s", result.ExitCode, strings.TrimSpace(result.Stderr))
- }
- 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)
diff --git a/internal/podman/container.go b/internal/podman/container.go
deleted file mode 100644
index bb90f413..00000000
--- a/internal/podman/container.go
+++ /dev/null
@@ -1,417 +0,0 @@
-package podman
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "strconv"
- "strings"
-)
-
-// ContainerConfig defines how to create a container.
-type ContainerConfig struct {
- Name string
- Image string
- Labels map[string]string
- Env map[string]string
- Memory string // e.g. "512m"
- CPUs string // e.g. "1"
- PidsLimit int
- NetworkMode string // "none", "slirp4netns", "bridge"
- ReadOnly bool
- TmpFS map[string]string // mount -> options
- Volumes []string // bind mounts, e.g. ["/host/path:/container/path"]
- CapDrop []string
- SecurityOpts []string
- UserNS string
- Publish []string // port mappings, e.g. ["12345:80/tcp"]
- CapAdd []string
- Entrypoint []string
- Command []string
-}
-
-// DefaultContainerConfig returns a security-hardened container config.
-// We drop ALL capabilities then add back only those needed for normal dev
-// workflows (apt install, pip install, npm, chmod/chown, etc.).
-// Dangerous caps like SYS_ADMIN, SYS_PTRACE, NET_ADMIN remain dropped.
-func DefaultContainerConfig(name, image string) ContainerConfig {
- return ContainerConfig{
- Name: name,
- Image: image,
- Labels: make(map[string]string),
- Env: make(map[string]string),
- Memory: "512m",
- CPUs: "1",
- PidsLimit: 256,
- NetworkMode: "none",
- ReadOnly: false,
- TmpFS: map[string]string{},
- CapDrop: []string{"ALL"},
- CapAdd: []string{
- "CHOWN", // chown files (apt, npm)
- "DAC_OVERRIDE", // bypass file permission checks (apt, pip)
- "FOWNER", // bypass ownership checks on files (apt)
- "FSETID", // set SGID bit (apt, dpkg)
- "KILL", // send signals to processes
- "SETGID", // set group ID (apt, su)
- "SETUID", // set user ID (apt, su)
- "SETPCAP", // modify process capabilities
- "SETFCAP", // set file capabilities (dpkg)
- "NET_BIND_SERVICE", // bind to ports < 1024 (web servers on port 80)
- "SYS_CHROOT", // chroot (dpkg, debootstrap)
- "AUDIT_WRITE", // write to audit log (login-related utils)
- },
- SecurityOpts: []string{},
- UserNS: "",
- Entrypoint: []string{"/bin/sleep"},
- Command: []string{"infinity"},
- }
-}
-
-// CreateContainer creates a container with the given config. Returns the container ID.
-func (c *Client) CreateContainer(ctx context.Context, cfg ContainerConfig) (string, error) {
- args := []string{"create", "--name", cfg.Name}
-
- for k, v := range cfg.Labels {
- args = append(args, "--label", fmt.Sprintf("%s=%s", k, v))
- }
-
- for k, v := range cfg.Env {
- args = append(args, "--env", fmt.Sprintf("%s=%s", k, v))
- }
-
- if cfg.Memory != "" {
- args = append(args, "--memory", cfg.Memory)
- }
- if cfg.CPUs != "" {
- args = append(args, "--cpus", cfg.CPUs)
- }
- if cfg.PidsLimit > 0 {
- args = append(args, "--pids-limit", fmt.Sprintf("%d", cfg.PidsLimit))
- }
- if cfg.NetworkMode != "" {
- args = append(args, "--network", cfg.NetworkMode)
- }
- if cfg.ReadOnly {
- args = append(args, "--read-only")
- }
- for mount, opts := range cfg.TmpFS {
- args = append(args, "--tmpfs", fmt.Sprintf("%s:%s", mount, opts))
- }
- for _, vol := range cfg.Volumes {
- args = append(args, "--volume", vol)
- }
- for _, cap := range cfg.CapDrop {
- args = append(args, "--cap-drop", cap)
- }
- for _, opt := range cfg.SecurityOpts {
- args = append(args, "--security-opt", opt)
- }
- if cfg.UserNS != "" {
- args = append(args, "--userns", cfg.UserNS)
- }
- for _, pub := range cfg.Publish {
- args = append(args, "--publish", pub)
- }
- for _, cap := range cfg.CapAdd {
- args = append(args, "--cap-add", cap)
- }
-
- if len(cfg.Entrypoint) > 0 {
- args = append(args, "--entrypoint", cfg.Entrypoint[0])
- }
-
- args = append(args, cfg.Image)
- args = append(args, cfg.Command...)
-
- result, err := c.Run(ctx, args...)
- if err != nil {
- return "", fmt.Errorf("failed to create container %s: %w", cfg.Name, err)
- }
- if result.ExitCode != 0 {
- return "", fmt.Errorf("podman create failed (exit %d): %s",
- result.ExitCode, strings.TrimSpace(result.Stderr))
- }
-
- return strings.TrimSpace(result.Stdout), nil
-}
-
-// StartContainer starts a container by name or ID.
-func (c *Client) StartContainer(ctx context.Context, nameOrID string) error {
- result, err := c.Run(ctx, "start", nameOrID)
- if err != nil {
- return fmt.Errorf("failed to start container %s: %w", nameOrID, err)
- }
- if result.ExitCode != 0 {
- return fmt.Errorf("podman start failed (exit %d): %s",
- result.ExitCode, strings.TrimSpace(result.Stderr))
- }
- return nil
-}
-
-// StopContainer stops a container by name or ID.
-func (c *Client) StopContainer(ctx context.Context, nameOrID string, timeoutSec int) error {
- args := []string{"stop"}
- if timeoutSec > 0 {
- args = append(args, "--time", fmt.Sprintf("%d", timeoutSec))
- }
- args = append(args, nameOrID)
-
- result, err := c.Run(ctx, args...)
- if err != nil {
- return fmt.Errorf("failed to stop container %s: %w", nameOrID, err)
- }
- if result.ExitCode != 0 {
- return fmt.Errorf("podman stop failed (exit %d): %s",
- result.ExitCode, strings.TrimSpace(result.Stderr))
- }
- return nil
-}
-
-// RemoveContainer removes a container by name or ID. Force=true kills running containers.
-func (c *Client) RemoveContainer(ctx context.Context, nameOrID string, force bool) error {
- args := []string{"rm"}
- if force {
- args = append(args, "--force", "--time", "0")
- }
- args = append(args, nameOrID)
-
- result, err := c.Run(ctx, args...)
- if err != nil {
- return fmt.Errorf("failed to remove container %s: %w", nameOrID, err)
- }
- if result.ExitCode != 0 {
- return fmt.Errorf("podman rm failed (exit %d): %s",
- result.ExitCode, strings.TrimSpace(result.Stderr))
- }
- return nil
-}
-
-// ContainerInfo holds inspect output for a container.
-type ContainerInfo struct {
- ID string `json:"Id"`
- Name string `json:"Name"`
- State struct {
- Status string `json:"Status"`
- Running bool `json:"Running"`
- StartedAt string `json:"StartedAt"`
- } `json:"State"`
- Config struct {
- Labels map[string]string `json:"Labels"`
- Image string `json:"Image"`
- } `json:"Config"`
- NetworkSettings struct {
- Networks map[string]struct {
- IPAddress string `json:"IPAddress"`
- } `json:"Networks"`
- } `json:"NetworkSettings"`
-}
-
-// InspectContainer returns detailed info about a container.
-func (c *Client) InspectContainer(ctx context.Context, nameOrID string) (*ContainerInfo, error) {
- var infos []ContainerInfo
- if err := c.RunJSON(ctx, &infos, "inspect", nameOrID); err != nil {
- return nil, fmt.Errorf("failed to inspect container %s: %w", nameOrID, err)
- }
- if len(infos) == 0 {
- return nil, fmt.Errorf("container %s not found", nameOrID)
- }
- return &infos[0], nil
-}
-
-// PSEntry represents a container from podman ps.
-type PSEntry struct {
- ID string `json:"Id"`
- Names []string `json:"Names"`
- State string `json:"State"`
- Labels map[string]string `json:"Labels"`
- Image string `json:"Image"`
-}
-
-// ListContainers lists containers matching the given label filter.
-func (c *Client) ListContainers(ctx context.Context, labelFilter string) ([]PSEntry, error) {
- args := []string{"ps", "-a", "--format", "json"}
- if labelFilter != "" {
- args = append(args, "--filter", fmt.Sprintf("label=%s", labelFilter))
- }
-
- result, err := c.Run(ctx, args...)
- if err != nil {
- return nil, err
- }
- if result.ExitCode != 0 {
- return nil, fmt.Errorf("podman ps failed (exit %d): %s",
- result.ExitCode, strings.TrimSpace(result.Stderr))
- }
-
- output := strings.TrimSpace(result.Stdout)
- if output == "" {
- return nil, nil
- }
-
- var entries []PSEntry
- if err := parseJSONOutput(output, &entries); err != nil {
- return nil, fmt.Errorf("failed to parse podman ps output: %w", err)
- }
- return entries, nil
-}
-
-// parseJSONOutput handles both JSON array and newline-delimited JSON.
-func parseJSONOutput(output string, dest *[]PSEntry) error {
- output = strings.TrimSpace(output)
- if output == "" || output == "[]" {
- return nil
- }
-
- // Try array first (newer podman versions)
- if strings.HasPrefix(output, "[") {
- return json.Unmarshal([]byte(output), dest)
- }
-
- // Newline-delimited JSON (older podman versions)
- for _, line := range strings.Split(output, "\n") {
- line = strings.TrimSpace(line)
- if line == "" {
- continue
- }
- var entry PSEntry
- if err := json.Unmarshal([]byte(line), &entry); err != nil {
- return err
- }
- *dest = append(*dest, entry)
- }
- return nil
-}
-
-// ContainerStats holds resource usage stats for a running container.
-type ContainerStats 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"`
-}
-
-// podmanStatsEntry matches the JSON output of podman stats --format json.
-// Note: podman outputs pids as a string (e.g. "1") and mem_usage includes both
-// usage and limit combined (e.g. "303.1kB / 536.9MB").
-type podmanStatsEntry struct {
- CPU string `json:"cpu_percent"`
- MemUsage string `json:"mem_usage"` // "usage / limit" combined
- NetIO string `json:"net_io"`
- PIDs string `json:"pids"` // podman outputs as string
-}
-
-// ContainerStats returns live resource usage stats for a running container.
-func (c *Client) ContainerStats(ctx context.Context, nameOrID string) (*ContainerStats, error) {
- result, err := c.Run(ctx, "stats", "--no-stream", "--no-reset", "--format", "json", nameOrID)
- if err != nil {
- return nil, fmt.Errorf("failed to get stats for %s: %w", nameOrID, err)
- }
- if result.ExitCode != 0 {
- return nil, fmt.Errorf("podman stats failed (exit %d): %s",
- result.ExitCode, strings.TrimSpace(result.Stderr))
- }
-
- output := strings.TrimSpace(result.Stdout)
- if output == "" {
- return nil, fmt.Errorf("no stats output for %s", nameOrID)
- }
-
- var entries []podmanStatsEntry
- if err := json.Unmarshal([]byte(output), &entries); err != nil {
- return nil, fmt.Errorf("failed to parse stats JSON: %w", err)
- }
- if len(entries) == 0 {
- return nil, fmt.Errorf("no stats entries for %s", nameOrID)
- }
-
- e := entries[0]
- stats := &ContainerStats{}
-
- // Parse PIDs: podman outputs as string (e.g. "1")
- if v, err := strconv.Atoi(strings.TrimSpace(e.PIDs)); err == nil {
- stats.PIDs = v
- }
-
- // Parse CPU percent: "12.5%" -> 12.5
- cpu := strings.TrimSpace(strings.TrimSuffix(e.CPU, "%"))
- if v, err := strconv.ParseFloat(cpu, 64); err == nil {
- stats.CPUPercent = v
- }
-
- // Parse memory: podman combines usage and limit as "303.1kB / 536.9MB"
- if parts := strings.SplitN(e.MemUsage, "/", 2); len(parts) == 2 {
- stats.MemUsage = parseBytes(strings.TrimSpace(parts[0]))
- stats.MemLimit = parseBytes(strings.TrimSpace(parts[1]))
- } else {
- stats.MemUsage = parseBytes(e.MemUsage)
- }
-
- // Parse net I/O: "1.2kB / 3.4kB"
- if parts := strings.SplitN(e.NetIO, "/", 2); len(parts) == 2 {
- stats.NetInput = parseBytes(strings.TrimSpace(parts[0]))
- stats.NetOutput = parseBytes(strings.TrimSpace(parts[1]))
- }
-
- return stats, nil
-}
-
-// parseBytes converts human-readable byte strings like "45.2MB", "1.5GiB", "512kB" to bytes.
-func parseBytes(s string) uint64 {
- s = strings.TrimSpace(s)
- if s == "" || s == "--" {
- return 0
- }
-
- multipliers := map[string]float64{
- "B": 1,
- "kB": 1000,
- "KB": 1000,
- "MB": 1000 * 1000,
- "GB": 1000 * 1000 * 1000,
- "TB": 1000 * 1000 * 1000 * 1000,
- "KiB": 1024,
- "MiB": 1024 * 1024,
- "GiB": 1024 * 1024 * 1024,
- "TiB": 1024 * 1024 * 1024 * 1024,
- }
-
- for suffix, mult := range multipliers {
- if strings.HasSuffix(s, suffix) {
- numStr := strings.TrimSpace(strings.TrimSuffix(s, suffix))
- if v, err := strconv.ParseFloat(numStr, 64); err == nil {
- return uint64(v * mult)
- }
- }
- }
-
- // Try as plain number
- if v, err := strconv.ParseUint(s, 10, 64); err == nil {
- return v
- }
- return 0
-}
-
-// PullImage pulls a container image.
-func (c *Client) PullImage(ctx context.Context, image string) error {
- result, err := c.Run(ctx, "pull", image)
- if err != nil {
- return fmt.Errorf("failed to pull image %s: %w", image, err)
- }
- if result.ExitCode != 0 {
- return fmt.Errorf("podman pull failed (exit %d): %s",
- result.ExitCode, strings.TrimSpace(result.Stderr))
- }
- return nil
-}
-
-// ImageExists checks whether an image is available locally.
-func (c *Client) ImageExists(ctx context.Context, image string) (bool, error) {
- result, err := c.Run(ctx, "image", "exists", image)
- if err != nil {
- return false, err
- }
- return result.ExitCode == 0, nil
-}
diff --git a/internal/podman/exec.go b/internal/podman/exec.go
deleted file mode 100644
index 72bc0ff9..00000000
--- a/internal/podman/exec.go
+++ /dev/null
@@ -1,85 +0,0 @@
-package podman
-
-import (
- "bytes"
- "context"
- "fmt"
- "io"
- "os"
- "os/exec"
- "strings"
-)
-
-// ExecConfig defines options for executing a command inside a container.
-type ExecConfig struct {
- Container string
- Command []string
- Env map[string]string
- Cwd string
- Stdin io.Reader
- TTY bool
-}
-
-// ExecInContainer runs a command inside a running container and returns the result.
-func (c *Client) ExecInContainer(ctx context.Context, cfg ExecConfig) (*ExecResult, error) {
- args := []string{"exec"}
-
- if cfg.TTY {
- args = append(args, "-it")
- } else if cfg.Stdin != nil {
- args = append(args, "-i")
- }
-
- for k, v := range cfg.Env {
- args = append(args, "--env", fmt.Sprintf("%s=%s", k, v))
- }
- if cfg.Cwd != "" {
- args = append(args, "--workdir", cfg.Cwd)
- }
-
- args = append(args, cfg.Container)
- args = append(args, cfg.Command...)
-
- 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
-
- if cfg.Stdin != nil {
- cmd.Stdin = cfg.Stdin
- }
-
- 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
-}
-
-// ExecSimple runs a simple command inside a container and returns stdout.
-func (c *Client) ExecSimple(ctx context.Context, container string, command ...string) (string, error) {
- result, err := c.ExecInContainer(ctx, ExecConfig{
- Container: container,
- Command: command,
- })
- if err != nil {
- return "", err
- }
- if result.ExitCode != 0 {
- return "", fmt.Errorf("command %v failed (exit %d): %s",
- command, result.ExitCode, strings.TrimSpace(result.Stderr))
- }
- return result.Stdout, nil
-}
diff --git a/internal/sandbox/exec.go b/internal/sandbox/exec.go
deleted file mode 100644
index 21e4d795..00000000
--- a/internal/sandbox/exec.go
+++ /dev/null
@@ -1,64 +0,0 @@
-package sandbox
-
-import (
- "context"
- "fmt"
- "strings"
- "time"
-
- "github.com/opensandbox/opensandbox/internal/podman"
- "github.com/opensandbox/opensandbox/pkg/types"
-)
-
-// Exec runs a command inside a sandbox and returns the result.
-func (m *PodmanManager) Exec(ctx context.Context, sandboxID string, cfg types.ProcessConfig) (*types.ProcessResult, error) {
- container := m.ContainerName(sandboxID)
-
- timeout := cfg.Timeout
- if timeout <= 0 {
- timeout = 60
- }
-
- execCtx, cancel := context.WithTimeout(ctx, time.Duration(timeout)*time.Second)
- defer cancel()
-
- command := buildCommand(cfg.Command, cfg.Args)
-
- cwd := cfg.Cwd
- if cwd == "" {
- cwd = "/workspace"
- }
-
- result, err := m.podman.ExecInContainer(execCtx, podman.ExecConfig{
- Container: container,
- Command: command,
- Env: cfg.Env,
- Cwd: cwd,
- })
- if err != nil {
- if execCtx.Err() == context.DeadlineExceeded {
- return &types.ProcessResult{
- ExitCode: 124,
- Stderr: fmt.Sprintf("command timed out after %ds", timeout),
- }, nil
- }
- return nil, fmt.Errorf("exec in sandbox %s failed: %w", sandboxID, err)
- }
-
- return &types.ProcessResult{
- ExitCode: result.ExitCode,
- Stdout: result.Stdout,
- Stderr: result.Stderr,
- }, nil
-}
-
-func buildCommand(cmd string, args []string) []string {
- if len(args) > 0 {
- return append([]string{cmd}, args...)
- }
- // If no args, use shell to interpret the command string
- if strings.Contains(cmd, " ") || strings.Contains(cmd, "|") || strings.Contains(cmd, ";") {
- return []string{"/bin/sh", "-c", cmd}
- }
- return []string{cmd}
-}
diff --git a/internal/sandbox/filesystem.go b/internal/sandbox/filesystem.go
deleted file mode 100644
index 1ab460e5..00000000
--- a/internal/sandbox/filesystem.go
+++ /dev/null
@@ -1,160 +0,0 @@
-package sandbox
-
-import (
- "context"
- "fmt"
- "strconv"
- "strings"
-
- "github.com/opensandbox/opensandbox/internal/podman"
- "github.com/opensandbox/opensandbox/pkg/types"
-)
-
-// ReadFile reads a file from inside the sandbox.
-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 {
- return "", fmt.Errorf("failed to read %s in sandbox %s: %w", path, sandboxID, err)
- }
- return content, nil
-}
-
-// WriteFile writes content to a file inside the sandbox.
-func (m *PodmanManager) WriteFile(ctx context.Context, sandboxID, path, content string) error {
- container := m.ContainerName(sandboxID)
-
- // Ensure parent directory exists
- dir := path[:strings.LastIndex(path, "/")]
- if dir != "" {
- _, _ = m.podman.ExecSimple(ctx, container, "mkdir", "-p", dir)
- }
-
- result, err := m.podman.ExecInContainer(ctx, podman.ExecConfig{
- Container: container,
- Command: []string{"/bin/sh", "-c", fmt.Sprintf("cat > %s", shellQuote(path))},
- Stdin: strings.NewReader(content),
- })
- if err != nil {
- return fmt.Errorf("failed to write %s in sandbox %s: %w", path, sandboxID, err)
- }
- if result.ExitCode != 0 {
- return fmt.Errorf("write to %s failed: %s", path, strings.TrimSpace(result.Stderr))
- }
- return nil
-}
-
-// ListDir lists directory contents inside the sandbox.
-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
- script := fmt.Sprintf(
- `find %s -maxdepth 1 -mindepth 1 -printf '%%y\t%%s\t%%f\n' 2>/dev/null || ls -1a %s`,
- shellQuote(path), shellQuote(path),
- )
- output, err := m.podman.ExecSimple(ctx, container, "/bin/sh", "-c", script)
- if err != nil {
- return nil, fmt.Errorf("failed to list %s in sandbox %s: %w", path, sandboxID, err)
- }
-
- var entries []types.EntryInfo
- for _, line := range strings.Split(strings.TrimSpace(output), "\n") {
- if line == "" {
- continue
- }
-
- parts := strings.SplitN(line, "\t", 3)
- if len(parts) == 3 {
- // find -printf output: type\tsize\tname
- isDir := parts[0] == "d"
- size, _ := strconv.ParseInt(parts[1], 10, 64)
- name := parts[2]
- entryPath := path + "/" + name
- if strings.HasSuffix(path, "/") {
- entryPath = path + name
- }
- entries = append(entries, types.EntryInfo{
- Name: name,
- IsDir: isDir,
- Size: size,
- Path: entryPath,
- })
- } else {
- // Fallback: ls output (just names)
- name := strings.TrimSpace(line)
- if name == "." || name == ".." {
- continue
- }
- entries = append(entries, types.EntryInfo{
- Name: name,
- Path: path + "/" + name,
- })
- }
- }
- return entries, nil
-}
-
-// MakeDir creates a directory inside the sandbox.
-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 {
- return fmt.Errorf("failed to mkdir %s in sandbox %s: %w", path, sandboxID, err)
- }
- return nil
-}
-
-// Remove removes a file or directory inside the sandbox.
-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 {
- return fmt.Errorf("failed to remove %s in sandbox %s: %w", path, sandboxID, err)
- }
- return nil
-}
-
-// Exists checks if a path exists inside the sandbox.
-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,
- Command: []string{"test", "-e", path},
- })
- if err != nil {
- return false, err
- }
- return result.ExitCode == 0, nil
-}
-
-// Stat returns file info for a path inside the sandbox.
-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)
- if err != nil {
- return nil, fmt.Errorf("failed to stat %s in sandbox %s: %w", path, sandboxID, err)
- }
-
- parts := strings.SplitN(strings.TrimSpace(output), "\t", 5)
- if len(parts) < 5 {
- return nil, fmt.Errorf("unexpected stat output for %s", path)
- }
-
- size, _ := strconv.ParseInt(parts[2], 10, 64)
- isDir := strings.Contains(parts[1], "directory")
-
- return &types.FileInfo{
- Name: parts[0],
- IsDir: isDir,
- Size: size,
- Mode: parts[3],
- ModTime: parts[4],
- Path: path,
- }, nil
-}
-
-func shellQuote(s string) string {
- return "'" + strings.ReplaceAll(s, "'", "'\\''") + "'"
-}
diff --git a/internal/sandbox/hibernate.go b/internal/sandbox/hibernate.go
deleted file mode 100644
index b6fbfdc1..00000000
--- a/internal/sandbox/hibernate.go
+++ /dev/null
@@ -1,383 +0,0 @@
-package sandbox
-
-import (
- "archive/tar"
- "context"
- "fmt"
- "io"
- "log"
- "os"
- "path/filepath"
- "strings"
- "time"
-
- "github.com/klauspost/compress/zstd"
- "github.com/opensandbox/opensandbox/internal/podman"
- "github.com/opensandbox/opensandbox/internal/storage"
- "github.com/opensandbox/opensandbox/pkg/types"
-)
-
-// HibernateResult holds the result of a hibernate operation.
-type HibernateResult struct {
- SandboxID string `json:"sandboxId"`
- HibernationKey string `json:"hibernationKey"`
- SizeBytes int64 `json:"sizeBytes"`
-}
-
-// 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 *PodmanManager) Hibernate(ctx context.Context, sandboxID string, checkpointStore *storage.CheckpointStore) (*HibernateResult, error) {
- name := m.ContainerName(sandboxID)
-
- // 1. Trim memory before checkpoint (best-effort)
- m.trimBeforeCheckpoint(ctx, name)
-
- // 2. Generate S3 key upfront so we can use it for cache path
- s3Key := storage.HibernationKey(sandboxID)
-
- // 3. Checkpoint to local file
- // If NVMe cache is enabled, write directly to cache dir (stays after upload).
- // Otherwise use a temp dir (cleaned up after upload).
- var localPath string
- var cleanup func()
-
- cachePath := checkpointStore.CachePath(s3Key)
- if cachePath != "" && !m.podman.UseSSH() {
- // Linux with NVMe cache: checkpoint directly into cache dir
- localPath = cachePath
- cleanup = func() {} // keep the file — it's the cache
- } else {
- // macOS or no cache: use temp dir
- tmpDir, err := os.MkdirTemp("", "osb-checkpoint-")
- if err != nil {
- return nil, fmt.Errorf("failed to create temp dir: %w", err)
- }
- cleanup = func() { os.RemoveAll(tmpDir) }
- localPath = filepath.Join(tmpDir, "checkpoint.tar.zst")
- }
- defer cleanup()
-
- if m.podman.UseSSH() {
- // On macOS: checkpoint inside VM, then copy archive to host
- vmPath := fmt.Sprintf("/tmp/osb-checkpoint-%s.tar.zst", sandboxID)
- if err := m.podman.CheckpointContainer(ctx, name, vmPath); err != nil {
- return nil, fmt.Errorf("checkpoint failed for sandbox %s: %w", sandboxID, err)
- }
- defer m.podman.RemoveVMFile(ctx, vmPath)
-
- if err := m.podman.CopyFromVM(ctx, vmPath, localPath); err != nil {
- return nil, fmt.Errorf("failed to copy checkpoint from VM for sandbox %s: %w", sandboxID, err)
- }
- } else {
- // On Linux: checkpoint directly to local path (NVMe cache or temp)
- if err := m.podman.CheckpointContainer(ctx, name, localPath); err != nil {
- return nil, fmt.Errorf("checkpoint failed for sandbox %s: %w", sandboxID, err)
- }
- }
-
- // 4. Upload CRIU checkpoint to S3 (source of truth)
- sizeBytes, err := checkpointStore.Upload(ctx, s3Key, localPath)
- if err != nil {
- return nil, fmt.Errorf("failed to upload checkpoint for sandbox %s: %w", sandboxID, err)
- }
-
- // 5. Remove the container (checkpoint --export already stopped it)
- _ = m.podman.RemoveContainer(ctx, name, true)
-
- // 6. Archive workspace to S3 in background (for cross-machine wake).
- // The workspace directory stays on local NVMe for fast same-machine wake.
- if m.dataDir != "" {
- workspaceDir := filepath.Join(m.dataDir, sandboxID, "workspace")
- if dirExists(workspaceDir) {
- go func() {
- bgCtx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
- defer cancel()
- if err := m.archiveWorkspaceToS3(bgCtx, sandboxID, workspaceDir, checkpointStore); err != nil {
- log.Printf("hibernate: workspace backup failed for %s: %v (workspace still on local disk)", sandboxID, err)
- } else {
- log.Printf("hibernate: workspace backed up to S3 for %s", sandboxID)
- }
- }()
- }
- }
-
- return &HibernateResult{
- SandboxID: sandboxID,
- HibernationKey: s3Key,
- SizeBytes: sizeBytes,
- }, nil
-}
-
-// 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 *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
- if m.dataDir != "" {
- workspaceDir := filepath.Join(m.dataDir, sandboxID, "workspace")
- if !dirExists(workspaceDir) {
- log.Printf("wake: workspace not found locally for %s, downloading from S3", sandboxID)
- if err := m.restoreWorkspaceFromS3(ctx, sandboxID, workspaceDir, checkpointStore); err != nil {
- log.Printf("wake: workspace restore failed for %s: %v (creating empty workspace)", sandboxID, err)
- if mkErr := os.MkdirAll(workspaceDir, 0755); mkErr != nil {
- return nil, fmt.Errorf("failed to create workspace dir for sandbox %s: %w", sandboxID, mkErr)
- }
- }
- } else {
- log.Printf("wake: workspace found locally for %s", sandboxID)
- }
- }
-
- // 2. Restore CRIU checkpoint — local NVMe fast path or S3 fallback
- if checkpointStore.CacheHit(checkpointKey) {
- // Fast path: restore directly from NVMe file — no S3, no temp file copy
- cachePath := checkpointStore.CachePath(checkpointKey)
- log.Printf("wake: restoring %s from local NVMe cache", sandboxID)
- if err := m.podman.RestoreContainer(ctx, cachePath, name); err != nil {
- return nil, fmt.Errorf("failed to restore sandbox %s from cache: %w", sandboxID, err)
- }
- } else {
- // Slow path: download from S3 (Download() will cache it for next time)
- log.Printf("wake: checkpoint not cached locally for %s, downloading from S3", sandboxID)
- reader, err := checkpointStore.Download(ctx, checkpointKey)
- if err != nil {
- return nil, fmt.Errorf("failed to download checkpoint for sandbox %s: %w", sandboxID, err)
- }
- defer reader.Close()
-
- if err := m.podman.RestoreContainerFromStream(ctx, reader, name); err != nil {
- return nil, fmt.Errorf("failed to restore sandbox %s: %w", sandboxID, err)
- }
- }
-
- // 3. Get sandbox info
- info, err := m.podman.InspectContainer(ctx, name)
- if err != nil {
- return nil, fmt.Errorf("failed to inspect restored sandbox %s: %w", sandboxID, err)
- }
-
- return containerInfoToSandbox(info), nil
-}
-
-// trimBeforeCheckpoint reduces the container's memory footprint before checkpointing.
-func (m *PodmanManager) trimBeforeCheckpoint(ctx context.Context, containerName string) {
- trimCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
- defer cancel()
-
- commands := [][]string{
- {"/bin/sh", "-c", "sync"},
- {"/bin/sh", "-c", "echo 3 > /proc/sys/vm/drop_caches 2>/dev/null || true"},
- }
-
- for _, cmd := range commands {
- _, _ = m.podman.ExecInContainer(trimCtx, podman.ExecConfig{
- Container: containerName,
- Command: cmd,
- })
- }
-}
-
-// WorkspaceS3Key returns the S3 key for a sandbox's workspace archive.
-func WorkspaceS3Key(sandboxID string) string {
- return fmt.Sprintf("workspaces/%s/workspace.tar.zst", sandboxID)
-}
-
-// archiveWorkspaceToS3 creates a tar.zst archive of the workspace directory and uploads it to S3.
-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)
- }
- defer os.Remove(archivePath)
-
- s3Key := WorkspaceS3Key(sandboxID)
- if _, err := store.Upload(ctx, s3Key, archivePath); err != nil {
- return fmt.Errorf("failed to upload workspace archive: %w", err)
- }
- return nil
-}
-
-// restoreWorkspaceFromS3 downloads a workspace archive from S3 and extracts it.
-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 {
- return fmt.Errorf("workspace archive not found in S3: %w", err)
- }
- defer reader.Close()
-
- if err := os.MkdirAll(workspaceDir, 0755); err != nil {
- return fmt.Errorf("failed to create workspace dir: %w", err)
- }
-
- return extractTarZstd(reader, workspaceDir)
-}
-
-// createTarZstd creates a zstd-compressed tar archive of a directory.
-// Returns the path to the temp file containing the archive.
-func createTarZstd(srcDir string) (string, error) {
- tmpFile, err := os.CreateTemp("", "osb-workspace-*.tar.zst")
- if err != nil {
- return "", err
- }
- tmpPath := tmpFile.Name()
-
- zw, err := zstd.NewWriter(tmpFile, zstd.WithEncoderLevel(zstd.SpeedDefault))
- if err != nil {
- tmpFile.Close()
- os.Remove(tmpPath)
- return "", err
- }
-
- tw := tar.NewWriter(zw)
-
- err = filepath.Walk(srcDir, func(path string, info os.FileInfo, walkErr error) error {
- if walkErr != nil {
- return walkErr
- }
-
- relPath, err := filepath.Rel(srcDir, path)
- if err != nil {
- return err
- }
-
- header, err := tar.FileInfoHeader(info, "")
- if err != nil {
- return err
- }
- header.Name = relPath
-
- // Handle symlinks
- if info.Mode()&os.ModeSymlink != 0 {
- link, err := os.Readlink(path)
- if err != nil {
- return err
- }
- header.Linkname = link
- }
-
- if err := tw.WriteHeader(header); err != nil {
- return err
- }
-
- if !info.Mode().IsRegular() {
- return nil
- }
-
- f, err := os.Open(path)
- if err != nil {
- return err
- }
- defer f.Close()
-
- _, err = io.Copy(tw, f)
- return err
- })
-
- // Close in reverse order: tar → zstd → file
- tw.Close()
- zw.Close()
- tmpFile.Close()
-
- if err != nil {
- os.Remove(tmpPath)
- return "", err
- }
-
- return tmpPath, nil
-}
-
-// extractTarZstd extracts a zstd-compressed tar archive from a reader into destDir.
-func extractTarZstd(reader io.Reader, destDir string) error {
- zr, err := zstd.NewReader(reader)
- if err != nil {
- return fmt.Errorf("failed to create zstd reader: %w", err)
- }
- defer zr.Close()
-
- tr := tar.NewReader(zr)
-
- for {
- header, err := tr.Next()
- if err == io.EOF {
- break
- }
- if err != nil {
- return fmt.Errorf("tar read error: %w", err)
- }
-
- // Sanitize the path to prevent directory traversal
- target := filepath.Join(destDir, header.Name)
- if !strings.HasPrefix(filepath.Clean(target), filepath.Clean(destDir)) {
- return fmt.Errorf("tar entry %q attempts path traversal", header.Name)
- }
-
- switch header.Typeflag {
- case tar.TypeDir:
- if err := os.MkdirAll(target, os.FileMode(header.Mode)); err != nil {
- return err
- }
- case tar.TypeReg:
- if err := os.MkdirAll(filepath.Dir(target), 0755); err != nil {
- return err
- }
- f, err := os.OpenFile(target, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.FileMode(header.Mode))
- if err != nil {
- return err
- }
- if _, err := io.Copy(f, tr); err != nil {
- f.Close()
- return err
- }
- f.Close()
- case tar.TypeSymlink:
- if err := os.MkdirAll(filepath.Dir(target), 0755); err != nil {
- return err
- }
- if err := os.Symlink(header.Linkname, target); err != nil {
- return err
- }
- }
- }
-
- return nil
-}
-
-// dirExists returns true if the path exists and is a directory.
-func dirExists(path string) bool {
- info, err := os.Stat(path)
- return err == nil && info.IsDir()
-}
-
-// SaveAsTemplate is not supported on the Podman backend (Firecracker only).
-func (m *PodmanManager) SaveAsTemplate(_ context.Context, _, _ string, _ *storage.CheckpointStore, _ func()) (string, string, error) {
- return "", "", fmt.Errorf("save-as-template is only supported on Firecracker backend")
-}
-
-// TemplateCachePath always returns "" on the Podman backend (Firecracker only).
-func (m *PodmanManager) TemplateCachePath(_, _ string) string {
- return ""
-}
-
-// CreateCheckpoint is not supported on the Podman backend (Firecracker only).
-func (m *PodmanManager) CreateCheckpoint(_ context.Context, _, _ string, _ *storage.CheckpointStore, _ func()) (string, string, error) {
- return "", "", fmt.Errorf("checkpoints are only supported on Firecracker backend")
-}
-
-// RestoreFromCheckpoint is not supported on the Podman backend (Firecracker only).
-func (m *PodmanManager) RestoreFromCheckpoint(_ context.Context, _, _ string) error {
- return fmt.Errorf("checkpoints are only supported on Firecracker backend")
-}
-
-// ForkFromCheckpoint is not supported on the Podman backend (Firecracker only).
-func (m *PodmanManager) ForkFromCheckpoint(_ context.Context, _ string, _ types.SandboxConfig) (*types.Sandbox, error) {
- return nil, fmt.Errorf("checkpoints are only supported on Firecracker backend")
-}
-
-// CheckpointCachePath always returns "" on the Podman backend (Firecracker only).
-func (m *PodmanManager) CheckpointCachePath(_, _ string) string {
- return ""
-}
diff --git a/internal/sandbox/interface.go b/internal/sandbox/interface.go
index 85477977..2a178d1c 100644
--- a/internal/sandbox/interface.go
+++ b/internal/sandbox/interface.go
@@ -7,8 +7,15 @@ import (
"github.com/opensandbox/opensandbox/pkg/types"
)
+// HibernateResult holds the result of a hibernate operation.
+type HibernateResult struct {
+ SandboxID string `json:"sandboxId"`
+ HibernationKey string `json:"hibernationKey"`
+ SizeBytes int64 `json:"sizeBytes"`
+}
+
// SandboxStats holds live resource usage for a sandbox.
-// Runtime-agnostic: both Podman and Firecracker backends populate these fields.
+// Runtime-agnostic interface for sandbox resource stats.
type SandboxStats struct {
CPUPercent float64 `json:"cpuPercent"`
MemUsage uint64 `json:"memUsage"` // bytes
@@ -21,7 +28,7 @@ type SandboxStats struct {
// 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.
+// Currently implemented by the Firecracker backend.
type Manager interface {
// Lifecycle
Create(ctx context.Context, cfg types.SandboxConfig) (*types.Sandbox, error)
diff --git a/internal/sandbox/manager.go b/internal/sandbox/manager.go
deleted file mode 100644
index ae90de0f..00000000
--- a/internal/sandbox/manager.go
+++ /dev/null
@@ -1,351 +0,0 @@
-package sandbox
-
-import (
- "context"
- "fmt"
- "os"
- "path/filepath"
- "strconv"
- "time"
-
- "github.com/google/uuid"
- "github.com/opensandbox/opensandbox/internal/podman"
- "github.com/opensandbox/opensandbox/pkg/types"
-)
-
-const (
- labelPrefix = "opensandbox"
- labelID = labelPrefix + ".id"
- labelTemplate = labelPrefix + ".template"
- labelCreated = labelPrefix + ".created"
- labelTimeout = labelPrefix + ".timeout"
- labelHostPort = labelPrefix + ".host_port"
- containerName = "osb"
-
- defaultTimeout = 300 // 5 minutes
- defaultImage = "docker.io/library/ubuntu:22.04"
- maxMemoryMB = 2048
- maxCPU = 4
-)
-
-// 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 PodmanManager struct {
- podman *podman.Client
- dataDir string // base directory for per-sandbox persistent data (workspace, sqlite)
- defaultMemoryMB int
- defaultCPU int
- defaultDiskMB int // per-sandbox disk quota (0 = no quota)
-}
-
-// 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 *PodmanManager) { m.dataDir = dir }
-}
-
-// WithDefaultMemoryMB sets the default memory per sandbox (in MB).
-func WithDefaultMemoryMB(mb int) ManagerOption {
- return func(m *PodmanManager) { m.defaultMemoryMB = mb }
-}
-
-// WithDefaultCPUs sets the default vCPU count per sandbox.
-func WithDefaultCPUs(cpus int) ManagerOption {
- 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 *PodmanManager) { m.defaultDiskMB = mb }
-}
-
-// NewManager creates a new sandbox manager.
-func NewManager(client *podman.Client, opts ...ManagerOption) *PodmanManager {
- m := &PodmanManager{
- podman: client,
- defaultMemoryMB: 1024,
- defaultCPU: 1,
- }
- for _, opt := range opts {
- opt(m)
- }
- return m
-}
-
-// DataDir returns the base data directory for sandbox storage.
-func (m *PodmanManager) DataDir() string {
- return m.dataDir
-}
-
-// Create creates a new sandbox container and starts it.
-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)
-
- timeout := cfg.Timeout
- if timeout <= 0 {
- timeout = defaultTimeout
- }
-
- image := defaultImage
- if cfg.ImageRef != "" {
- // DB-resolved ECR URI takes precedence
- image = cfg.ImageRef
- } else if cfg.Template != "" {
- image = resolveTemplateImage(cfg.Template)
- }
-
- memoryMB := cfg.MemoryMB
- if memoryMB <= 0 {
- memoryMB = m.defaultMemoryMB
- }
- cpuCount := cfg.CpuCount
- if cpuCount <= 0 {
- cpuCount = m.defaultCPU
- }
-
- now := time.Now()
-
- ccfg := podman.DefaultContainerConfig(name, image)
- ccfg.Labels[labelID] = id
- ccfg.Labels[labelTemplate] = cfg.Template
- ccfg.Labels[labelCreated] = now.Format(time.RFC3339)
- ccfg.Labels[labelTimeout] = strconv.Itoa(timeout)
- ccfg.Memory = fmt.Sprintf("%dm", memoryMB)
- ccfg.CPUs = fmt.Sprintf("%d", cpuCount)
-
- for k, v := range cfg.Envs {
- ccfg.Env[k] = v
- }
-
- // Always use bridge networking for subdomain proxy access.
- // Container port defaults to 80 but can be overridden (e.g., 3000, 8080).
- ccfg.NetworkMode = "bridge"
-
- containerPort := cfg.Port
- if containerPort <= 0 {
- containerPort = 80
- }
-
- hostPort, err := podman.FindFreePort()
- if err != nil {
- return nil, fmt.Errorf("failed to allocate host port for sandbox %s: %w", id, err)
- }
- ccfg.Publish = []string{fmt.Sprintf("%d:%d/tcp", hostPort, containerPort)}
- ccfg.Labels[labelHostPort] = strconv.Itoa(hostPort)
-
- // Make /tmp writable for sandbox use (scratch space, not persisted)
- ccfg.TmpFS["/tmp"] = "rw,size=100m"
-
- // Workspace: bind-mount from host disk if dataDir is configured,
- // otherwise fall back to tmpfs (e.g., dev mode without NVMe).
- if m.dataDir != "" {
- workspaceDir := filepath.Join(m.dataDir, id, "workspace")
- if err := os.MkdirAll(workspaceDir, 0755); err != nil {
- return nil, fmt.Errorf("failed to create workspace dir for sandbox %s: %w", id, err)
- }
- ccfg.Volumes = append(ccfg.Volumes, workspaceDir+":/workspace")
- // Enforce disk quota on the sandbox's data directory (best-effort, requires XFS + prjquota)
- if m.defaultDiskMB > 0 {
- m.SetDiskQuota(id, m.defaultDiskMB)
- }
- } else {
- ccfg.TmpFS["/workspace"] = "rw,size=200m"
- }
-
- if _, err := m.podman.CreateContainer(ctx, ccfg); err != nil {
- return nil, fmt.Errorf("failed to create sandbox %s: %w", id, err)
- }
-
- if err := m.podman.StartContainer(ctx, name); err != nil {
- // Clean up the created container on start failure
- _ = m.podman.RemoveContainer(ctx, name, true)
- return nil, fmt.Errorf("failed to start sandbox %s: %w", id, err)
- }
-
- sandbox := &types.Sandbox{
- ID: id,
- Template: cfg.Template,
- Alias: cfg.Alias,
- Status: types.SandboxStatusRunning,
- StartedAt: now,
- EndAt: now.Add(time.Duration(timeout) * time.Second),
- Metadata: cfg.Metadata,
- CpuCount: cpuCount,
- MemoryMB: memoryMB,
- HostPort: hostPort,
- }
-
- return sandbox, nil
-}
-
-// Get returns sandbox info by ID.
-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 {
- return nil, fmt.Errorf("sandbox %s not found: %w", id, err)
- }
- return containerInfoToSandbox(info), nil
-}
-
-// Kill forcefully removes a sandbox and cleans up its on-disk workspace.
-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)
- }
- // Clean up persistent workspace directory (best-effort)
- if m.dataDir != "" {
- _ = os.RemoveAll(filepath.Join(m.dataDir, id))
- }
- return nil
-}
-
-// List returns all sandboxes.
-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)
- }
-
- sandboxes := make([]types.Sandbox, 0, len(entries))
- for _, e := range entries {
- sandboxes = append(sandboxes, psEntryToSandbox(e))
- }
- return sandboxes, nil
-}
-
-// Count returns the number of active sandbox containers.
-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)
- }
- return len(entries), nil
-}
-
-// ContainerName returns the podman container name for a sandbox ID.
-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 *PodmanManager) HostPort(ctx context.Context, sandboxID string) (int, error) {
- name := m.ContainerName(sandboxID)
- info, err := m.podman.InspectContainer(ctx, name)
- if err != nil {
- return 0, fmt.Errorf("sandbox %s not found: %w", sandboxID, err)
- }
- portStr := info.Config.Labels[labelHostPort]
- if portStr == "" {
- return 0, fmt.Errorf("sandbox %s has no host port mapping", sandboxID)
- }
- port, err := strconv.Atoi(portStr)
- if err != nil {
- return 0, fmt.Errorf("invalid host port label for sandbox %s: %w", sandboxID, err)
- }
- return port, nil
-}
-
-// ContainerAddr returns the container's bridge IP and the requested port as "ip:port".
-// Used by the proxy to route preview URL traffic directly to a specific container port.
-func (m *PodmanManager) ContainerAddr(ctx context.Context, sandboxID string, port int) (string, error) {
- name := m.ContainerName(sandboxID)
- info, err := m.podman.InspectContainer(ctx, name)
- if err != nil {
- return "", fmt.Errorf("sandbox %s not found: %w", sandboxID, err)
- }
- // Find bridge IP from network settings
- for _, net := range info.NetworkSettings.Networks {
- if net.IPAddress != "" {
- return fmt.Sprintf("%s:%d", net.IPAddress, port), nil
- }
- }
- return "", fmt.Errorf("sandbox %s has no network IP", sandboxID)
-}
-
-// Stats returns live CPU/memory stats for a running sandbox.
-func (m *PodmanManager) Stats(ctx context.Context, sandboxID string) (*SandboxStats, error) {
- name := m.ContainerName(sandboxID)
- 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 *PodmanManager) Close() {}
-
-func resolveTemplateImage(template string) string {
- switch template {
- case "base", "":
- return "docker.io/library/ubuntu:22.04"
- case "python":
- return "docker.io/library/python:3.12-slim"
- case "node":
- return "docker.io/library/node:20-slim"
- default:
- // Custom template: assume it's an image name tagged by the template system
- return fmt.Sprintf("localhost/opensandbox-template/%s:latest", template)
- }
-}
-
-func containerInfoToSandbox(info *podman.ContainerInfo) *types.Sandbox {
- status := types.SandboxStatusStopped
- if info.State.Running {
- status = types.SandboxStatusRunning
- }
-
- id := info.Config.Labels[labelID]
-
- startedAt, _ := time.Parse(time.RFC3339, info.Config.Labels[labelCreated])
- timeoutSec, _ := strconv.Atoi(info.Config.Labels[labelTimeout])
- endAt := startedAt.Add(time.Duration(timeoutSec) * time.Second)
- hostPort, _ := strconv.Atoi(info.Config.Labels[labelHostPort])
-
- return &types.Sandbox{
- ID: id,
- Template: info.Config.Labels[labelTemplate],
- Status: status,
- StartedAt: startedAt,
- EndAt: endAt,
- HostPort: hostPort,
- }
-}
-
-func psEntryToSandbox(entry podman.PSEntry) types.Sandbox {
- status := types.SandboxStatusStopped
- if entry.State == "running" {
- status = types.SandboxStatusRunning
- }
-
- id := entry.Labels[labelID]
-
- startedAt, _ := time.Parse(time.RFC3339, entry.Labels[labelCreated])
- timeoutSec, _ := strconv.Atoi(entry.Labels[labelTimeout])
- endAt := startedAt.Add(time.Duration(timeoutSec) * time.Second)
- hostPort, _ := strconv.Atoi(entry.Labels[labelHostPort])
-
- return types.Sandbox{
- ID: id,
- Template: entry.Labels[labelTemplate],
- Status: status,
- StartedAt: startedAt,
- EndAt: endAt,
- HostPort: hostPort,
- }
-}
diff --git a/internal/sandbox/pty.go b/internal/sandbox/pty.go
index 669aa9f9..2409b915 100644
--- a/internal/sandbox/pty.go
+++ b/internal/sandbox/pty.go
@@ -3,27 +3,19 @@ package sandbox
import (
"fmt"
"io"
- "os"
"os/exec"
"sync"
- ptylib "github.com/creack/pty"
"github.com/google/uuid"
"github.com/opensandbox/opensandbox/pkg/types"
)
-// 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.
+// PTYManager manages PTY sessions via Firecracker agent gRPC.
type PTYManager struct {
- podmanPath string
- authFile string
- mu sync.RWMutex
- sessions map[string]*PTYSessionHandle
+ 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 creates PTY sessions via the Firecracker agent.
createFunc func(sandboxID string, req types.PTYCreateRequest) (*PTYSessionHandle, error)
}
@@ -31,25 +23,16 @@ type PTYManager struct {
type PTYSessionHandle struct {
ID string
SandboxID string
- Cmd *exec.Cmd // Podman mode only (nil for Firecracker)
- PTY io.ReadWriteCloser // PTY I/O stream (*os.File for Podman, net.Conn for Firecracker)
+ Cmd *exec.Cmd // unused (kept for interface compat), nil for Firecracker
+ PTY io.ReadWriteCloser // PTY I/O stream (net.Conn for Firecracker)
Done chan struct{}
- // onKill is called when the session is killed (Firecracker: sends gRPC PTYKill).
+ // onKill is called when the session is killed (sends gRPC PTYKill).
onKill func()
- // onResize is called when the session is resized (Firecracker: sends gRPC PTYResize).
+ // onResize is called when the session is resized (sends gRPC PTYResize).
onResize func(cols, rows int) error
}
-// NewPTYManager creates a new Podman-based PTY manager.
-func NewPTYManager(podmanPath, authFile string) *PTYManager {
- return &PTYManager{
- podmanPath: podmanPath,
- authFile: authFile,
- sessions: make(map[string]*PTYSessionHandle),
- }
-}
-
// 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 {
@@ -61,78 +44,23 @@ func NewAgentPTYManager(createFunc func(sandboxID string, req types.PTYCreateReq
// 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)
-
- shell := req.Shell
- if shell == "" {
- shell = "/bin/bash"
- }
-
- cols := req.Cols
- if cols <= 0 {
- cols = 80
- }
- rows := req.Rows
- if rows <= 0 {
- rows = 24
- }
-
- args := []string{
- "exec", "-it",
- "--env", "TERM=xterm-256color",
- "--workdir", "/workspace",
- containerName,
- shell,
+ if pm.createFunc == nil {
+ return nil, fmt.Errorf("no PTY create function configured")
}
- cmd := exec.Command(pm.podmanPath, args...)
- cmd.Env = append(os.Environ(), "REGISTRY_AUTH_FILE="+pm.authFile)
-
- // Start with a real pseudo-terminal
- ptmx, err := ptylib.StartWithSize(cmd, &ptylib.Winsize{
- Rows: uint16(rows),
- Cols: uint16(cols),
- })
+ handle, err := pm.createFunc(sandboxID, req)
if err != nil {
- return nil, fmt.Errorf("failed to start PTY session: %w", err)
+ return nil, err
}
- handle := &PTYSessionHandle{
- ID: sessionID,
- SandboxID: sandboxID,
- Cmd: cmd,
- PTY: ptmx,
- Done: make(chan struct{}),
+ // Assign a session ID if one wasn't set by the create function
+ if handle.ID == "" {
+ handle.ID = uuid.New().String()[:8]
}
- go func() {
- _ = cmd.Wait()
- close(handle.Done)
- }()
-
pm.mu.Lock()
- pm.sessions[sessionID] = handle
+ pm.sessions[handle.ID] = handle
pm.mu.Unlock()
-
return handle, nil
}
@@ -146,18 +74,10 @@ func (pm *PTYManager) Resize(sessionID string, cols, rows int) error {
return fmt.Errorf("PTY session %s not found", sessionID)
}
- // 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")
}
@@ -186,7 +106,6 @@ 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()
}
diff --git a/internal/sandbox/quota.go b/internal/sandbox/quota.go
deleted file mode 100644
index ea8a976f..00000000
--- a/internal/sandbox/quota.go
+++ /dev/null
@@ -1,139 +0,0 @@
-package sandbox
-
-import (
- "fmt"
- "hash/fnv"
- "log"
- "os"
- "os/exec"
- "path/filepath"
- "strconv"
- "strings"
-)
-
-// 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 *PodmanManager) SetDiskQuota(sandboxID string, limitMB int) {
- if m.dataDir == "" || limitMB <= 0 {
- return
- }
-
- projectID := sandboxProjectID(sandboxID)
- sandboxDir := filepath.Join(m.dataDir, sandboxID)
-
- // Register the project in /etc/projects and /etc/projid (idempotent)
- if err := registerXFSProject(projectID, sandboxDir, sandboxID); err != nil {
- log.Printf("quota: failed to register project for %s: %v (quotas disabled for this sandbox)", sandboxID, err)
- return
- }
-
- // Initialize the project directory
- initCmd := exec.Command("xfs_quota", "-x", "-c",
- fmt.Sprintf("project -s %d", projectID),
- m.dataDir)
- if out, err := initCmd.CombinedOutput(); err != nil {
- log.Printf("quota: failed to init project %d for %s: %v (%s)", projectID, sandboxID, err, strings.TrimSpace(string(out)))
- return
- }
-
- // Set the hard block limit
- limitCmd := exec.Command("xfs_quota", "-x", "-c",
- fmt.Sprintf("limit -p bhard=%dm %d", limitMB, projectID),
- m.dataDir)
- if out, err := limitCmd.CombinedOutput(); err != nil {
- log.Printf("quota: failed to set limit for %s: %v (%s)", sandboxID, err, strings.TrimSpace(string(out)))
- return
- }
-
- log.Printf("quota: set %dMB disk limit for sandbox %s (project %d)", limitMB, sandboxID, projectID)
-}
-
-// RemoveDiskQuota removes the XFS project quota entries for a sandbox.
-func (m *PodmanManager) RemoveDiskQuota(sandboxID string) {
- if m.dataDir == "" {
- return
- }
-
- projectID := sandboxProjectID(sandboxID)
-
- // Remove limit (set to 0 = unlimited)
- limitCmd := exec.Command("xfs_quota", "-x", "-c",
- fmt.Sprintf("limit -p bhard=0 %d", projectID),
- m.dataDir)
- _ = limitCmd.Run()
-
- // Clean up /etc/projects and /etc/projid entries
- removeXFSProject(projectID, sandboxID)
-}
-
-// sandboxProjectID generates a stable project ID from a sandbox ID.
-// XFS project IDs are uint32; we use FNV-1a hash and avoid 0 (reserved).
-func sandboxProjectID(sandboxID string) uint32 {
- h := fnv.New32a()
- h.Write([]byte(sandboxID))
- id := h.Sum32()
- if id == 0 {
- id = 1
- }
- return id
-}
-
-// registerXFSProject adds entries to /etc/projects and /etc/projid if not already present.
-func registerXFSProject(projectID uint32, dir, sandboxID string) error {
- idStr := strconv.FormatUint(uint64(projectID), 10)
- projectLine := fmt.Sprintf("%s:%s", idStr, dir)
- projidLine := fmt.Sprintf("%s:sandbox-%s", idStr, sandboxID)
-
- if err := appendLineIfMissing("/etc/projects", projectLine); err != nil {
- return fmt.Errorf("failed to update /etc/projects: %w", err)
- }
- if err := appendLineIfMissing("/etc/projid", projidLine); err != nil {
- return fmt.Errorf("failed to update /etc/projid: %w", err)
- }
- return nil
-}
-
-// removeXFSProject removes entries from /etc/projects and /etc/projid.
-func removeXFSProject(projectID uint32, sandboxID string) {
- idStr := strconv.FormatUint(uint64(projectID), 10)
- removeLineByPrefix("/etc/projects", idStr+":")
- removeLineByPrefix("/etc/projid", idStr+":")
-}
-
-func appendLineIfMissing(filePath, line string) error {
- data, err := os.ReadFile(filePath)
- if err != nil && !os.IsNotExist(err) {
- return err
- }
-
- content := string(data)
- if strings.Contains(content, line) {
- return nil
- }
-
- f, err := os.OpenFile(filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
- if err != nil {
- return err
- }
- defer f.Close()
-
- _, err = f.WriteString(line + "\n")
- return err
-}
-
-func removeLineByPrefix(filePath, prefix string) {
- data, err := os.ReadFile(filePath)
- if err != nil {
- return
- }
-
- var kept []string
- for _, line := range strings.Split(string(data), "\n") {
- if !strings.HasPrefix(line, prefix) {
- kept = append(kept, line)
- }
- }
-
- _ = os.WriteFile(filePath, []byte(strings.Join(kept, "\n")), 0644)
-}
diff --git a/internal/sandbox/router.go b/internal/sandbox/router.go
index 3bd3051c..031feb8f 100644
--- a/internal/sandbox/router.go
+++ b/internal/sandbox/router.go
@@ -409,7 +409,6 @@ func (r *SandboxRouter) ensureRunning(ctx context.Context, sandboxID string) err
func (r *SandboxRouter) discoverAndEnsure(ctx context.Context, sandboxID string) error {
if r.store == nil || r.checkpointStore == nil {
// No DB/S3 — can't auto-wake, let the operation proceed
- // (podman will return an error if the container doesn't exist)
return nil
}
diff --git a/scripts/test-hibernation.sh b/scripts/test-hibernation.sh
index 6c2368c9..15bb3e1e 100755
--- a/scripts/test-hibernation.sh
+++ b/scripts/test-hibernation.sh
@@ -109,8 +109,6 @@ else
red " Hibernate failed: $HIB_RESP"
fi
-CONTAINER_CHECK=$(podman ps --format '{{.Names}}' 2>/dev/null | grep "osb-${SANDBOX_ID}" || true)
-check "Container removed after hibernate" "" "$CONTAINER_CHECK"
echo ""
# --- Explicit Wake ---
@@ -162,10 +160,6 @@ else
green " Hibernated (second time)"
fi
-# Verify container is gone
-CONTAINER_CHECK2=$(podman ps --format '{{.Names}}' 2>/dev/null | grep "osb-${SANDBOX_ID}" || true)
-check "Container removed after second hibernate" "" "$CONTAINER_CHECK2"
-
# Now send a command WITHOUT calling /wake — the router should auto-wake
AUTOWAKE_START=$(python3 -c 'import time; print(time.time())')
AUTOWAKE_RESP=$(run_cmd "$SANDBOX_ID" "cat /tmp/autowake.txt")