Skip to content

An open-source, faster Devin alternative

TypeScript

wip

Brian Reardon18f2fc65f585
diff --git a/HANDOFF.md b/HANDOFF.md
index c7b700c7..ae53d5ef 100644
--- a/HANDOFF.md
+++ b/HANDOFF.md
@@ -67,8 +67,7 @@ ASYNC SYNC (background):
|------|-------------|
| `internal/metrics/metrics.go` | 14 Prometheus metrics (gauges, counters, histograms) + Echo middleware + standalone /metrics server |
| `deploy/docker-compose.yml` | PostgreSQL 16 + NATS 2 (JetStream) for local dev |
-| `deploy/fly.toml` | Fly.io control plane deployment config |
-| `deploy/fly-worker.toml` | Fly.io worker deployment (HTTP :8080, gRPC :9090, metrics :9091) |
+| `deploy/ec2/` | EC2 bare-metal deployment (setup, deploy, Caddy, systemd) |
| `deploy/prometheus/prometheus.yml` | Scrape configs for CP and workers |
| `deploy/grafana/dashboards/opensandbox-overview.json` | Dashboard: active sandboxes, create latency, utilization, sync lag |
| `deploy/Dockerfile.server`, `Dockerfile.worker` | Both use CGO_ENABLED=1 (required by go-sqlite3) |
@@ -235,10 +234,9 @@ internal/
sqlite.go — Per-sandbox SQLite
compute/
- pool.go — Pool interface (extended)
- fly.go — Fly.io Machines API
+ pool.go — Pool interface
+ ec2.go — AWS EC2 bare-metal pool
local.go — Local/dev pool
- router.go — Region-aware routing
config/config.go — All env var config
metrics/metrics.go — Prometheus metrics + Echo middleware
@@ -253,8 +251,7 @@ sdks/
deploy/
docker-compose.yml — PG + NATS for local dev
- fly.toml — CP Fly.io config
- fly-worker.toml — Worker Fly.io config
+ ec2/ — EC2 bare-metal deployment
Dockerfile.server — CP Docker image
Dockerfile.worker — Worker Docker image
prometheus/prometheus.yml — Prometheus scrape config
diff --git a/Makefile b/Makefile
index 2c589270..d410a1f2 100644
--- a/Makefile
+++ b/Makefile
@@ -20,6 +20,14 @@ build-server:
build-worker:
CGO_ENABLED=1 go build -o $(BUILD_DIR)/$(BINARY_WORKER) ./cmd/worker
+## build-worker-arm64: Cross-compile worker for Linux ARM64 (Graviton bare-metal)
+build-worker-arm64:
+ CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -o $(BUILD_DIR)/$(BINARY_WORKER)-arm64 ./cmd/worker
+
+## build-server-arm64: Cross-compile server for Linux ARM64
+build-server-arm64:
+ CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -o $(BUILD_DIR)/$(BINARY_SERVER)-arm64 ./cmd/server
+
## --- Local Testing (3 tiers) ---
## run-dev: Tier 1 - Combined mode, no auth, no PG/NATS (simplest)
diff --git a/README.md b/README.md
index ba453ee4..8337eb33 100644
--- a/README.md
+++ b/README.md
@@ -100,8 +100,7 @@ Control Plane (Go/Echo)
├── Sandbox Router
└── Compute Pool
├── Local (development)
- ├── Fly.io (production)
- └── ... (extensible)
+ └── EC2 (production — bare-metal Graviton)
│ gRPC (internal)
▼
Sandbox Worker (Go)
@@ -143,7 +142,6 @@ Sandbox Worker (Go)
| `OPENSANDBOX_API_KEY` | (empty) | API key (empty = no auth) |
| `OPENSANDBOX_WORKER_ADDR` | `localhost:9090` | Worker address |
| `OPENSANDBOX_MODE` | `combined` | `server`, `worker`, or `combined` |
-| `FLY_API_TOKEN` | (empty) | Fly.io API token (for cloud deployment) |
## Security
diff --git a/cmd/server/main.go b/cmd/server/main.go
index 57d544df..26d08f43 100644
--- a/cmd/server/main.go
+++ b/cmd/server/main.go
@@ -9,8 +9,11 @@ import (
"os/signal"
"syscall"
+ "time"
+
"github.com/opensandbox/opensandbox/internal/api"
"github.com/opensandbox/opensandbox/internal/auth"
+ "github.com/opensandbox/opensandbox/internal/compute"
"github.com/opensandbox/opensandbox/internal/config"
"github.com/opensandbox/opensandbox/internal/controlplane"
"github.com/opensandbox/opensandbox/internal/db"
@@ -50,7 +53,12 @@ func main() {
} else {
log.Printf("opensandbox: using podman %s", version)
- mgr = sandbox.NewManager(podmanClient)
+ 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")
@@ -186,8 +194,10 @@ func main() {
}
// Initialize Redis worker registry in server mode
+ var redisRegistry *controlplane.RedisWorkerRegistry
if cfg.Mode == "server" && cfg.RedisURL != "" {
- redisRegistry, err := controlplane.NewRedisWorkerRegistry(cfg.RedisURL)
+ var err error
+ redisRegistry, err = controlplane.NewRedisWorkerRegistry(cfg.RedisURL)
if err != nil {
log.Fatalf("failed to connect to Redis: %v", err)
}
@@ -197,6 +207,35 @@ func main() {
log.Println("opensandbox: Redis worker registry started")
}
+ // Initialize EC2 compute pool + autoscaler (server mode with AWS configured)
+ if cfg.Mode == "server" && cfg.EC2AMI != "" && redisRegistry != nil {
+ ec2Pool, err := compute.NewEC2Pool(compute.EC2PoolConfig{
+ Region: cfg.S3Region, // reuse S3 region (same AWS account)
+ AccessKeyID: cfg.S3AccessKeyID,
+ SecretAccessKey: cfg.S3SecretAccessKey,
+ AMI: cfg.EC2AMI,
+ InstanceType: cfg.EC2InstanceType,
+ SubnetID: cfg.EC2SubnetID,
+ SecurityGroupID: cfg.EC2SecurityGroupID,
+ KeyName: cfg.EC2KeyName,
+ IAMInstanceProfile: cfg.EC2IAMInstanceProfile,
+ SecretsARN: cfg.SecretsARN,
+ })
+ if err != nil {
+ log.Fatalf("opensandbox: failed to create EC2 pool: %v", err)
+ }
+
+ scaler := controlplane.NewScaler(controlplane.ScalerConfig{
+ Pool: ec2Pool,
+ Registry: redisRegistry,
+ WorkerImage: cfg.EC2WorkerImage,
+ Cooldown: time.Duration(cfg.ScaleCooldownSec) * time.Second,
+ })
+ scaler.Start()
+ defer scaler.Stop()
+ log.Printf("opensandbox: EC2 autoscaler started (ami=%s, type=%s)", cfg.EC2AMI, cfg.EC2InstanceType)
+ }
+
// Create API server
server := api.NewServer(mgr, ptyMgr, cfg.APIKey, opts)
diff --git a/cmd/worker/main.go b/cmd/worker/main.go
index 58bcb7e0..034a611c 100644
--- a/cmd/worker/main.go
+++ b/cmd/worker/main.go
@@ -7,6 +7,7 @@ import (
"os"
"os/exec"
"os/signal"
+ "path/filepath"
"syscall"
"github.com/opensandbox/opensandbox/internal/auth"
@@ -43,7 +44,12 @@ func main() {
log.Printf("opensandbox-worker: using podman %s", version)
// Initialize sandbox manager
- mgr := sandbox.NewManager(client)
+ mgr := sandbox.NewManager(client,
+ sandbox.WithDataDir(cfg.DataDir),
+ sandbox.WithDefaultMemoryMB(cfg.DefaultSandboxMemoryMB),
+ sandbox.WithDefaultCPUs(cfg.DefaultSandboxCPUs),
+ sandbox.WithDefaultDiskMB(cfg.DefaultSandboxDiskMB),
+ )
defer mgr.Close()
// Initialize PTY manager
@@ -77,6 +83,14 @@ func main() {
log.Fatalf("failed to initialize checkpoint store: %v", err)
}
log.Printf("opensandbox-worker: S3 checkpoint store configured (bucket=%s, region=%s)", cfg.S3Bucket, cfg.S3Region)
+
+ // Enable local NVMe checkpoint cache if data dir is configured
+ if cfg.DataDir != "" {
+ cacheDir := filepath.Join(cfg.DataDir, "checkpoints")
+ if err := checkpointStore.SetCacheDir(cacheDir); err != nil {
+ log.Printf("opensandbox-worker: warning: checkpoint cache disabled: %v", err)
+ }
+ }
}
// Initialize PostgreSQL store for checkpoint lookups (auto-wake)
@@ -190,14 +204,17 @@ func main() {
grpcAdvertise := grpcAddr
if addr := os.Getenv("OPENSANDBOX_GRPC_ADVERTISE"); addr != "" {
grpcAdvertise = addr
- } else if allocID := os.Getenv("FLY_ALLOC_ID"); allocID != "" {
- grpcAdvertise = allocID + ".vm.opensandbox-worker.internal:9090"
}
hb, err := worker.NewRedisHeartbeat(cfg.RedisURL, cfg.WorkerID, cfg.Region, grpcAdvertise, cfg.HTTPAddr)
if err != nil {
log.Printf("opensandbox-worker: Redis heartbeat not available: %v", err)
} else {
+ // Try to get EC2 instance ID from IMDS for scaler drain/terminate
+ if machineID := worker.GetEC2InstanceID(); machineID != "" {
+ hb.SetMachineID(machineID)
+ log.Printf("opensandbox-worker: EC2 instance ID: %s", machineID)
+ }
hb.Start(func() (int, int, float64, float64) {
count, _ := mgr.Count(context.Background())
cpuPct, memPct := worker.SystemStats()
diff --git a/deploy/Dockerfile.worker b/deploy/Dockerfile.worker
index 7b6bf4c7..059b318d 100644
--- a/deploy/Dockerfile.worker
+++ b/deploy/Dockerfile.worker
@@ -101,35 +101,12 @@ COPY --from=criu-builder /usr/local/lib/libcriu.so* /usr/local/lib/
COPY --from=crun-builder /crun/crun /usr/bin/crun
RUN ldconfig
-# Configure podman to use cgroupfs (Fly VMs use cgroup v1 without systemd)
+# Configure podman to use crun
RUN mkdir -p /etc/containers && \
- printf '[engine]\ncgroup_manager = "cgroupfs"\nevents_logger = "file"\n' \
+ printf '[engine]\nruntime = "crun"\nevents_logger = "file"\n' \
> /etc/containers/containers.conf
COPY --from=builder /opensandbox-worker /usr/local/bin/opensandbox-worker
-# Entrypoint script fixes cgroup v1 symlinks on Fly.io before starting the worker.
-# Fly VMs mount "cpu,cpuacct" as the real cgroup controller but leave "cpu" as a
-# plain empty directory instead of a symlink. This breaks podman resource limits.
-RUN printf '#!/bin/sh\nset -e\n\
-# Ensure cgroup v1 combined controllers have single-name symlinks.\n\
-# Fly VMs may mount "cpu,cpuacct" without a "cpu" symlink, or leave\n\
-# "cpu" as an empty plain directory. Either case breaks podman.\n\
-fix_cgroup() {\n\
- combined="/sys/fs/cgroup/$2"\n\
- single="/sys/fs/cgroup/$1"\n\
- [ -d "$combined" ] || return 0\n\
- if [ -L "$single" ]; then return 0; fi\n\
- rm -rf "$single" 2>/dev/null || true\n\
- ln -s "$combined" "$single"\n\
-}\n\
-fix_cgroup cpu cpu,cpuacct\n\
-fix_cgroup cpuacct cpu,cpuacct\n\
-fix_cgroup net_cls net_cls,net_prio\n\
-fix_cgroup net_prio net_cls,net_prio\n\
-exec "$@"\n' > /usr/local/bin/worker-entrypoint.sh && \
- chmod +x /usr/local/bin/worker-entrypoint.sh
-
EXPOSE 8080 9090 9091
-ENTRYPOINT ["worker-entrypoint.sh"]
CMD ["opensandbox-worker"]
diff --git a/deploy/ec2/deploy-worker.sh b/deploy/ec2/deploy-worker.sh
index e65db3cc..82a90073 100755
--- a/deploy/ec2/deploy-worker.sh
+++ b/deploy/ec2/deploy-worker.sh
@@ -13,10 +13,11 @@ SSH_USER="${SSH_USER:-ubuntu}"
SSH="ssh -i $SSH_KEY $SSH_USER@$WORKER_IP"
SCP="scp -i $SSH_KEY"
-echo "==> Building opensandbox-worker (linux/amd64)..."
+GOARCH="${GOARCH:-arm64}"
+echo "==> Building opensandbox-worker (linux/${GOARCH})..."
cd "$REPO_ROOT"
-GOOS=linux GOARCH=amd64 go build -o opensandbox-worker ./cmd/worker/
-echo " Built: opensandbox-worker ($(du -h opensandbox-worker | cut -f1))"
+CGO_ENABLED=0 GOOS=linux GOARCH="$GOARCH" go build -o opensandbox-worker ./cmd/worker/
+echo " Built: opensandbox-worker ($(du -h opensandbox-worker | cut -f1), ${GOARCH})"
echo "==> Uploading to $WORKER_IP..."
$SCP opensandbox-worker "$SSH_USER@$WORKER_IP:/tmp/opensandbox-worker"
diff --git a/deploy/ec2/migrate-to-secrets.sh b/deploy/ec2/migrate-to-secrets.sh
new file mode 100755
index 00000000..fd12ad49
--- /dev/null
+++ b/deploy/ec2/migrate-to-secrets.sh
@@ -0,0 +1,324 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+# =============================================================================
+# OpenSandbox — Migrate running instances to use AWS Secrets Manager
+#
+# Current state (after setup-secrets.sh was run):
+# - opensandbox/worker secret exists (JWT, Redis, DB, S3) — needs ECR added
+# - opensandbox-ec2 instance profile is attached to both instances
+# - opensandbox-ec2 role only has ECR access — needs Secrets Manager + S3
+# - No server secret exists yet
+# - Both instances use inline secrets in systemd/env files
+#
+# This script:
+# 1. Updates the worker secret to include ECR values
+# 2. Creates a server secret with WorkOS values
+# 3. Updates the opensandbox-ec2 role with Secrets Manager + S3 + ECR policy
+# 4. SSHes into both instances and migrates them to OPENSANDBOX_SECRETS_ARN
+#
+# Prerequisites:
+# - AWS CLI v2 with "digger" profile configured
+# - SSH access via opensandbox-digger.pem
+# - jq installed
+# =============================================================================
+
+AWS_PROFILE="digger"
+REGION="us-east-2"
+SSH_KEY="$HOME/.ssh/opensandbox-digger.pem"
+
+# Existing infra
+WORKER_SECRET_NAME="opensandbox/worker"
+ROLE_NAME="opensandbox-ec2" # the role actually attached to instances
+S3_BUCKET="opensandbox-checkpoints-digger"
+ECR_REGISTRY="739940681129.dkr.ecr.us-east-2.amazonaws.com"
+ECR_REPOSITORY="opensandbox-templates"
+
+# Server secret (new)
+SERVER_SECRET_NAME="opensandbox/server"
+
+# Production values — from running worker systemd unit
+REDIS_URL="redis://opensandbox-redis.c1cbz5.0001.use2.cache.amazonaws.com:6379"
+RDS_HOST="opensandbox-pg.chwjcxjqzouh.us-east-2.rds.amazonaws.com"
+RDS_PASSWORD="OpnSbx2026SecurePG"
+JWT_SECRET="${JWT_SECRET}"
+DATABASE_URL="postgres://opensandbox:${RDS_PASSWORD}@${RDS_HOST}:5432/opensandbox?sslmode=require"
+
+# WorkOS (server only) — from /etc/opensandbox/server.env
+WORKOS_API_KEY="${WORKOS_API_KEY}"
+WORKOS_CLIENT_ID="${WORKOS_CLIENT_ID}"
+WORKOS_REDIRECT_URI="https://app.opensandbox.ai/auth/callback"
+WORKOS_COOKIE_DOMAIN="opensandbox.ai"
+
+# Instance IPs
+WORKER_IP="18.219.23.64"
+SERVER_IP="3.135.246.117"
+
+aws() { command aws --profile "$AWS_PROFILE" "$@"; }
+
+GREEN='\033[0;32m'
+YELLOW='\033[1;33m'
+RED='\033[0;31m'
+NC='\033[0m'
+
+echo -e "${GREEN}==> OpenSandbox: Migrate to Secrets Manager${NC}"
+echo ""
+
+# --- Step 1: Update worker secret to include ECR ---
+echo -e "${YELLOW}==> Step 1: Updating worker secret with ECR values...${NC}"
+
+WORKER_SECRET_JSON=$(jq -n \
+ --arg jwt "$JWT_SECRET" \
+ --arg redis "$REDIS_URL" \
+ --arg db "$DATABASE_URL" \
+ --arg s3bucket "$S3_BUCKET" \
+ --arg s3region "$REGION" \
+ --arg ecr_registry "$ECR_REGISTRY" \
+ --arg ecr_repo "$ECR_REPOSITORY" \
+ '{
+ "OPENSANDBOX_JWT_SECRET": $jwt,
+ "OPENSANDBOX_REDIS_URL": $redis,
+ "DATABASE_URL": $db,
+ "OPENSANDBOX_S3_BUCKET": $s3bucket,
+ "OPENSANDBOX_S3_REGION": $s3region,
+ "OPENSANDBOX_ECR_REGISTRY": $ecr_registry,
+ "OPENSANDBOX_ECR_REPOSITORY": $ecr_repo
+ }')
+
+aws secretsmanager put-secret-value \
+ --secret-id "$WORKER_SECRET_NAME" \
+ --region "$REGION" \
+ --secret-string "$WORKER_SECRET_JSON"
+
+WORKER_SECRET_ARN=$(aws secretsmanager describe-secret \
+ --secret-id "$WORKER_SECRET_NAME" \
+ --region "$REGION" \
+ --query 'ARN' --output text)
+
+echo -e "Worker Secret ARN: ${GREEN}${WORKER_SECRET_ARN}${NC}"
+echo ""
+
+# --- Step 2: Create server secret ---
+echo -e "${YELLOW}==> Step 2: Creating server secret...${NC}"
+
+SERVER_SECRET_JSON=$(jq -n \
+ --arg jwt "$JWT_SECRET" \
+ --arg redis "$REDIS_URL" \
+ --arg db "$DATABASE_URL" \
+ --arg s3bucket "$S3_BUCKET" \
+ --arg s3region "$REGION" \
+ --arg ecr_registry "$ECR_REGISTRY" \
+ --arg ecr_repo "$ECR_REPOSITORY" \
+ --arg workos_key "$WORKOS_API_KEY" \
+ --arg workos_client "$WORKOS_CLIENT_ID" \
+ --arg workos_redirect "$WORKOS_REDIRECT_URI" \
+ --arg workos_cookie "$WORKOS_COOKIE_DOMAIN" \
+ '{
+ "OPENSANDBOX_JWT_SECRET": $jwt,
+ "OPENSANDBOX_REDIS_URL": $redis,
+ "DATABASE_URL": $db,
+ "OPENSANDBOX_S3_BUCKET": $s3bucket,
+ "OPENSANDBOX_S3_REGION": $s3region,
+ "OPENSANDBOX_ECR_REGISTRY": $ecr_registry,
+ "OPENSANDBOX_ECR_REPOSITORY": $ecr_repo,
+ "WORKOS_API_KEY": $workos_key,
+ "WORKOS_CLIENT_ID": $workos_client,
+ "WORKOS_REDIRECT_URI": $workos_redirect,
+ "WORKOS_COOKIE_DOMAIN": $workos_cookie
+ }')
+
+if aws secretsmanager describe-secret --secret-id "$SERVER_SECRET_NAME" --region "$REGION" &>/dev/null; then
+ echo "Secret '$SERVER_SECRET_NAME' already exists — updating..."
+ aws secretsmanager put-secret-value \
+ --secret-id "$SERVER_SECRET_NAME" \
+ --region "$REGION" \
+ --secret-string "$SERVER_SECRET_JSON"
+else
+ aws secretsmanager create-secret \
+ --name "$SERVER_SECRET_NAME" \
+ --region "$REGION" \
+ --description "OpenSandbox server secrets (JWT, Redis, S3, DB, ECR, WorkOS)" \
+ --secret-string "$SERVER_SECRET_JSON"
+fi
+
+SERVER_SECRET_ARN=$(aws secretsmanager describe-secret \
+ --secret-id "$SERVER_SECRET_NAME" \
+ --region "$REGION" \
+ --query 'ARN' --output text)
+
+echo -e "Server Secret ARN: ${GREEN}${SERVER_SECRET_ARN}${NC}"
+echo ""
+
+# --- Step 3: Update opensandbox-ec2 role with Secrets Manager + S3 policy ---
+echo -e "${YELLOW}==> Step 3: Updating IAM role '${ROLE_NAME}' with Secrets Manager + S3 policy...${NC}"
+
+POLICY_NAME="opensandbox-secrets-s3-ecr"
+POLICY_DOC=$(cat <<EOF
+{
+ "Version": "2012-10-17",
+ "Statement": [
+ {
+ "Sid": "SecretsManagerAccess",
+ "Effect": "Allow",
+ "Action": "secretsmanager:GetSecretValue",
+ "Resource": [
+ "${WORKER_SECRET_ARN}",
+ "${SERVER_SECRET_ARN}"
+ ]
+ },
+ {
+ "Sid": "S3CheckpointAccess",
+ "Effect": "Allow",
+ "Action": [
+ "s3:GetObject",
+ "s3:PutObject",
+ "s3:DeleteObject",
+ "s3:ListBucket"
+ ],
+ "Resource": [
+ "arn:aws:s3:::${S3_BUCKET}",
+ "arn:aws:s3:::${S3_BUCKET}/*"
+ ]
+ },
+ {
+ "Sid": "ECRAccess",
+ "Effect": "Allow",
+ "Action": [
+ "ecr:GetAuthorizationToken",
+ "ecr:BatchCheckLayerAvailability",
+ "ecr:GetDownloadUrlForLayer",
+ "ecr:BatchGetImage"
+ ],
+ "Resource": "*"
+ }
+ ]
+}
+EOF
+)
+
+EXISTING_POLICY_ARN=$(aws iam list-policies \
+ --query "Policies[?PolicyName=='${POLICY_NAME}'].Arn" \
+ --output text 2>/dev/null || echo "")
+
+if [ -n "$EXISTING_POLICY_ARN" ] && [ "$EXISTING_POLICY_ARN" != "None" ]; then
+ echo "Policy '$POLICY_NAME' already exists — creating new version..."
+ OLD_VERSION=$(aws iam list-policy-versions \
+ --policy-arn "$EXISTING_POLICY_ARN" \
+ --query 'Versions[?IsDefaultVersion==`false`].VersionId | [0]' \
+ --output text 2>/dev/null || echo "None")
+ if [ -n "$OLD_VERSION" ] && [ "$OLD_VERSION" != "None" ]; then
+ aws iam delete-policy-version \
+ --policy-arn "$EXISTING_POLICY_ARN" \
+ --version-id "$OLD_VERSION" 2>/dev/null || true
+ fi
+ aws iam create-policy-version \
+ --policy-arn "$EXISTING_POLICY_ARN" \
+ --policy-document "$POLICY_DOC" \
+ --set-as-default
+ POLICY_ARN="$EXISTING_POLICY_ARN"
+else
+ POLICY_ARN=$(aws iam create-policy \
+ --policy-name "$POLICY_NAME" \
+ --description "OpenSandbox: Secrets Manager + S3 + ECR access" \
+ --policy-document "$POLICY_DOC" \
+ --query 'Policy.Arn' --output text)
+fi
+
+aws iam attach-role-policy \
+ --role-name "$ROLE_NAME" \
+ --policy-arn "$POLICY_ARN" 2>/dev/null || true
+
+echo -e "Policy ARN: ${GREEN}${POLICY_ARN}${NC}"
+echo "Attached to role '$ROLE_NAME'"
+echo ""
+
+# --- Step 4: Migrate worker instance ---
+echo -e "${YELLOW}==> Step 4: Migrating worker instance (${WORKER_IP})...${NC}"
+
+ssh -o StrictHostKeyChecking=no -i "$SSH_KEY" "ubuntu@${WORKER_IP}" bash <<REMOTE_WORKER
+set -euo pipefail
+
+# Write new minimal systemd unit that uses Secrets Manager
+sudo tee /etc/systemd/system/opensandbox-worker.service > /dev/null <<'UNIT'
+[Unit]
+Description=OpenSandbox Worker
+After=network-online.target
+Wants=network-online.target
+
+[Service]
+Type=simple
+ExecStartPre=/sbin/modprobe inet_diag
+ExecStartPre=/sbin/modprobe tcp_diag
+ExecStartPre=/sbin/modprobe udp_diag
+ExecStartPre=/sbin/modprobe unix_diag
+ExecStartPre=/sbin/modprobe netlink_diag
+ExecStart=/usr/local/bin/opensandbox-worker
+Restart=always
+RestartSec=5
+
+Environment=HOME=/root
+Environment=OPENSANDBOX_MODE=worker
+Environment=OPENSANDBOX_PORT=8080
+Environment=OPENSANDBOX_REGION=use2
+Environment=OPENSANDBOX_DATA_DIR=/data/sandboxes
+Environment=OPENSANDBOX_WORKER_ID=w-use2-1
+Environment=OPENSANDBOX_HTTP_ADDR=http://${WORKER_IP}:8080
+Environment=OPENSANDBOX_GRPC_ADVERTISE=10.10.1.54:9090
+Environment=OPENSANDBOX_SANDBOX_DOMAIN=workers.opensandbox.ai
+Environment=OPENSANDBOX_SECRETS_ARN=${WORKER_SECRET_ARN}
+
+[Install]
+WantedBy=multi-user.target
+UNIT
+
+sudo systemctl daemon-reload
+echo "Worker systemd unit updated. Secrets will be fetched from Secrets Manager at next restart."
+REMOTE_WORKER
+
+echo -e "${GREEN}Worker migrated.${NC}"
+echo ""
+
+# --- Step 5: Migrate server instance ---
+echo -e "${YELLOW}==> Step 5: Migrating server instance (${SERVER_IP})...${NC}"
+
+ssh -o StrictHostKeyChecking=no -i "$SSH_KEY" "ubuntu@${SERVER_IP}" bash <<REMOTE_SERVER
+set -euo pipefail
+
+# Write new minimal server.env that uses Secrets Manager
+sudo tee /etc/opensandbox/server.env > /dev/null <<'ENV'
+OPENSANDBOX_MODE=server
+OPENSANDBOX_PORT=8080
+OPENSANDBOX_REGION=use2
+OPENSANDBOX_DATA_DIR=/data/sandboxes
+OPENSANDBOX_WORKER_ID=cp-use2-1
+OPENSANDBOX_HTTP_ADDR=http://${SERVER_IP}:8080
+OPENSANDBOX_SANDBOX_DOMAIN=workers.opensandbox.ai
+OPENSANDBOX_SECRETS_ARN=${SERVER_SECRET_ARN}
+ENV
+
+echo "Server env file updated. Secrets will be fetched from Secrets Manager at next restart."
+REMOTE_SERVER
+
+echo -e "${GREEN}Server migrated.${NC}"
+echo ""
+
+# --- Done ---
+echo -e "${GREEN}============================================${NC}"
+echo -e "${GREEN} Migration complete!${NC}"
+echo ""
+echo "Worker Secret ARN: $WORKER_SECRET_ARN"
+echo "Server Secret ARN: $SERVER_SECRET_ARN"
+echo "IAM Policy: $POLICY_ARN"
+echo ""
+echo "Both instances are configured but NOT restarted."
+echo "Inline secrets have been replaced with OPENSANDBOX_SECRETS_ARN."
+echo ""
+echo "To apply (restart services):"
+echo " Worker: ssh -i $SSH_KEY ubuntu@${WORKER_IP} 'sudo systemctl restart opensandbox-worker'"
+echo " Server: ssh -i $SSH_KEY ubuntu@${SERVER_IP} 'sudo systemctl restart opensandbox-server'"
+echo ""
+echo "Or restart both:"
+echo " ssh -i $SSH_KEY ubuntu@${WORKER_IP} 'sudo systemctl restart opensandbox-worker' && \\"
+echo " ssh -i $SSH_KEY ubuntu@${SERVER_IP} 'sudo systemctl restart opensandbox-server'"
+echo ""
+echo -e "${GREEN}============================================${NC}"
diff --git a/deploy/ec2/setup-instance.sh b/deploy/ec2/setup-instance.sh
index 792ee222..8b1e637e 100755
--- a/deploy/ec2/setup-instance.sh
+++ b/deploy/ec2/setup-instance.sh
@@ -5,60 +5,78 @@ set -euo pipefail
# Run this ON the instance (ssh in first), or pipe via ssh:
# ssh -i key.pem ubuntu@<IP> 'bash -s' < deploy/ec2/setup-instance.sh
#
+# Supports both x86_64 (amd64) and aarch64 (arm64/Graviton) instances.
+#
# Prerequisites:
# - Ubuntu 24.04 LTS AMI
-# - t3.medium or larger
+# - t3.medium or larger (x86) / r7gd.medium or larger (arm64)
# - Security group: 443 (HTTPS), 9090 (gRPC) open inbound
# - SSH access
+# Detect architecture
+ARCH=$(uname -m)
+case "$ARCH" in
+ x86_64) GOARCH="amd64" ;;
+ aarch64) GOARCH="arm64" ;;
+ *) echo "ERROR: Unsupported architecture: $ARCH"; exit 1 ;;
+esac
+echo "==> Detected architecture: $ARCH ($GOARCH)"
+
echo "==> Updating packages..."
sudo apt-get update && sudo apt-get upgrade -y
# -------------------------------------------------------------------
-# Podman + crun (with CRIU support)
+# Podman (runtime will be configured after crun is built)
# -------------------------------------------------------------------
echo "==> Installing Podman..."
sudo apt-get install -y podman uidmap slirp4netns
-echo "==> Installing crun from source (with CRIU support)..."
-sudo apt-get install -y \
- make gcc pkg-config \
- libsystemd-dev libcap-dev libseccomp-dev \
- libyajl-dev go-md2man
-
-CRUN_VERSION="1.26"
-cd /tmp
-git clone --branch "$CRUN_VERSION" --depth 1 https://github.com/containers/crun.git
-cd crun
-./autogen.sh
-./configure --with-criu
-make -j"$(nproc)"
-sudo make install
-cd / && rm -rf /tmp/crun
-
-echo "==> Verifying crun has CRIU support..."
-crun --version | grep "+CRIU" || { echo "ERROR: crun built without CRIU"; exit 1; }
-
# -------------------------------------------------------------------
-# CRIU 4.2
+# CRIU 4.2 (must be installed BEFORE crun so headers are available)
# -------------------------------------------------------------------
echo "==> Installing CRIU 4.2 from source..."
sudo apt-get install -y \
+ make gcc pkg-config git \
libprotobuf-dev libprotobuf-c-dev protobuf-c-compiler protobuf-compiler \
libcap-dev libnl-3-dev libnet1-dev libbsd-dev \
python3-protobuf python3-yaml iproute2 \
- libdrm-dev libnftables-dev pkg-config
+ libdrm-dev libnftables-dev uuid-dev libaio-dev
cd /tmp
+rm -rf /tmp/criu
git clone --branch v4.2 --depth 1 https://github.com/checkpoint-restore/criu.git
cd criu
make -j"$(nproc)"
-sudo make install PREFIX=/usr/local
+sudo make install-criu PREFIX=/usr/local
+sudo make install-lib PREFIX=/usr/local
+sudo ldconfig
cd / && rm -rf /tmp/criu
echo "==> Verifying CRIU..."
criu --version
+# -------------------------------------------------------------------
+# crun 1.26 (with CRIU support — requires CRIU headers from above)
+# -------------------------------------------------------------------
+echo "==> Installing crun from source (with CRIU support)..."
+sudo apt-get install -y \
+ libsystemd-dev libseccomp-dev \
+ libyajl-dev go-md2man autoconf automake libtool
+
+cd /tmp
+rm -rf /tmp/crun
+git clone --branch "1.26" --depth 1 https://github.com/containers/crun.git
+cd crun
+export PKG_CONFIG_PATH="/usr/local/lib/pkgconfig:${PKG_CONFIG_PATH:-}"
+./autogen.sh
+./configure --with-criu
+make -j"$(nproc)"
+sudo make install
+cd / && rm -rf /tmp/crun
+
+echo "==> Verifying crun has CRIU support..."
+crun --version | grep "+CRIU" || { echo "ERROR: crun built without CRIU"; exit 1; }
+
# -------------------------------------------------------------------
# Configure Podman to use crun
# -------------------------------------------------------------------
@@ -75,18 +93,12 @@ EOF
echo "==> Installing Redis..."
sudo apt-get install -y redis-server
-echo "==> Configuring Redis..."
-# Set a password — replace <REDIS_PASSWORD> with your actual password
-# sudo sed -i 's/^# requirepass .*/requirepass <REDIS_PASSWORD>/' /etc/redis/redis.conf
-# sudo systemctl restart redis-server
-echo " NOTE: Set a Redis password in /etc/redis/redis.conf manually"
-
# -------------------------------------------------------------------
# Caddy (custom build with Route53 DNS module for wildcard certs)
# -------------------------------------------------------------------
echo "==> Installing Go (needed for xcaddy)..."
GO_VERSION="1.23.6"
-curl -sL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | sudo tar -C /usr/local -xzf -
+curl -sL "https://go.dev/dl/go${GO_VERSION}.linux-${GOARCH}.tar.gz" | sudo tar -C /usr/local -xzf -
export PATH=$PATH:/usr/local/go/bin:$HOME/go/bin
echo "==> Building Caddy with Route53 DNS module..."
@@ -108,20 +120,132 @@ sudo cp /tmp/deploy-ec2/caddy.service /etc/systemd/system/caddy.service 2>/dev/n
echo " NOTE: Copy deploy/ec2/caddy.service to /etc/systemd/system/ manually"
# -------------------------------------------------------------------
-# Worker setup
+# NVMe instance storage (handled at boot by opensandbox-nvme.service)
# -------------------------------------------------------------------
-echo "==> Creating data directory..."
-sudo mkdir -p /data/sandboxes
+echo "==> Installing NVMe boot service..."
+sudo apt-get install -y xfsprogs nvme-cli
+
+sudo tee /usr/local/bin/opensandbox-nvme-setup.sh > /dev/null << 'NVME'
+#!/usr/bin/env bash
+set -euo pipefail
+MOUNT_POINT="/data/sandboxes"
+mkdir -p "$MOUNT_POINT"
+if mountpoint -q "$MOUNT_POINT"; then
+ echo "opensandbox-nvme: $MOUNT_POINT already mounted"
+ exit 0
+fi
+NVME_DEV=""
+for dev in /dev/nvme1n1 /dev/nvme2n1 /dev/nvme3n1 /dev/nvme4n1; do
+ if [ -b "$dev" ]; then
+ NVME_DEV="$dev"
+ break
+ fi
+done
+if [ -z "$NVME_DEV" ]; then
+ echo "opensandbox-nvme: no NVMe instance storage found, using root disk"
+ exit 0
+fi
+echo "opensandbox-nvme: formatting $NVME_DEV as XFS with project quotas"
+mkfs.xfs -f "$NVME_DEV"
+mount -o prjquota "$NVME_DEV" "$MOUNT_POINT"
+echo "opensandbox-nvme: mounted $NVME_DEV at $MOUNT_POINT"
+NVME
+sudo chmod +x /usr/local/bin/opensandbox-nvme-setup.sh
+sudo tee /etc/systemd/system/opensandbox-nvme.service > /dev/null << 'SVC'
+[Unit]
+Description=OpenSandbox NVMe Instance Storage Setup
+DefaultDependencies=no
+Before=opensandbox-worker.service
+After=local-fs.target
+
+[Service]
+Type=oneshot
+RemainAfterExit=yes
+ExecStart=/usr/local/bin/opensandbox-nvme-setup.sh
+
+[Install]
+WantedBy=multi-user.target
+SVC
+
+# -------------------------------------------------------------------
+# Dynamic worker identity (from EC2 IMDS at boot)
+# -------------------------------------------------------------------
+echo "==> Installing identity service..."
+sudo tee /usr/local/bin/opensandbox-worker-identity.sh > /dev/null << 'IDENT'
+#!/usr/bin/env bash
+set -euo pipefail
+TOKEN=$(curl -s -X PUT "http://169.254.169.254/latest/api/token" \
+ -H "X-aws-ec2-metadata-token-ttl-seconds: 300")
+INSTANCE_ID=$(curl -s -H "X-aws-ec2-metadata-token: $TOKEN" \
+ http://169.254.169.254/latest/meta-data/instance-id)
+PRIVATE_IP=$(curl -s -H "X-aws-ec2-metadata-token: $TOKEN" \
+ http://169.254.169.254/latest/meta-data/local-ipv4)
+PUBLIC_IP=$(curl -s -H "X-aws-ec2-metadata-token: $TOKEN" \
+ http://169.254.169.254/latest/meta-data/public-ipv4 || echo "")
+SHORT_ID=$(echo "$INSTANCE_ID" | sed 's/^i-//' | cut -c1-8)
+WORKER_ID="w-use2-${SHORT_ID}"
+mkdir -p /etc/opensandbox
+cat > /etc/opensandbox/worker-identity.env << EOF
+OPENSANDBOX_WORKER_ID=${WORKER_ID}
+OPENSANDBOX_HTTP_ADDR=http://${PUBLIC_IP:-$PRIVATE_IP}:8080
+OPENSANDBOX_GRPC_ADVERTISE=${PRIVATE_IP}:9090
+EOF
+echo "opensandbox-identity: ${WORKER_ID} private=${PRIVATE_IP} public=${PUBLIC_IP:-none}"
+IDENT
+sudo chmod +x /usr/local/bin/opensandbox-worker-identity.sh
+
+sudo tee /etc/systemd/system/opensandbox-identity.service > /dev/null << 'SVC'
+[Unit]
+Description=OpenSandbox Worker Identity (from EC2 IMDS)
+After=network-online.target
+Wants=network-online.target
+Before=opensandbox-worker.service
+
+[Service]
+Type=oneshot
+RemainAfterExit=yes
+ExecStart=/usr/local/bin/opensandbox-worker-identity.sh
+
+[Install]
+WantedBy=multi-user.target
+SVC
+
+# -------------------------------------------------------------------
+# Worker systemd unit
+# -------------------------------------------------------------------
echo "==> Installing worker systemd unit..."
-sudo cp /tmp/deploy-ec2/opensandbox-worker.service /etc/systemd/system/ 2>/dev/null || \
- echo " NOTE: Copy deploy/ec2/opensandbox-worker.service to /etc/systemd/system/ manually"
+sudo tee /etc/systemd/system/opensandbox-worker.service > /dev/null << 'SVC'
+[Unit]
+Description=OpenSandbox Worker
+After=network-online.target opensandbox-nvme.service opensandbox-identity.service
+Wants=network-online.target
+Requires=opensandbox-nvme.service opensandbox-identity.service
-echo "==> Creating env file directory..."
-sudo mkdir -p /etc/opensandbox
-if [ ! -f /etc/opensandbox/worker.env ]; then
- echo " NOTE: Copy deploy/ec2/worker.env.example to /etc/opensandbox/worker.env and fill in secrets"
-fi
+[Service]
+Type=simple
+ExecStartPre=/sbin/modprobe inet_diag
+ExecStartPre=/sbin/modprobe tcp_diag
+ExecStartPre=/sbin/modprobe udp_diag
+ExecStartPre=/sbin/modprobe unix_diag
+ExecStartPre=/sbin/modprobe netlink_diag
+ExecStart=/usr/local/bin/opensandbox-worker
+Restart=always
+RestartSec=5
+Environment=HOME=/root
+Environment=OPENSANDBOX_MODE=worker
+Environment=OPENSANDBOX_PORT=8080
+Environment=OPENSANDBOX_REGION=use2
+Environment=OPENSANDBOX_DATA_DIR=/data/sandboxes
+Environment=OPENSANDBOX_SANDBOX_DOMAIN=workers.opensandbox.ai
+Environment=OPENSANDBOX_SECRETS_ARN=arn:aws:secretsmanager:us-east-2:739940681129:secret:opensandbox/worker-vtN2Ez
+EnvironmentFile=/etc/opensandbox/worker-identity.env
+
+[Install]
+WantedBy=multi-user.target
+SVC
+
+sudo mkdir -p /etc/opensandbox /data/sandboxes
# -------------------------------------------------------------------
# Kernel modules for CRIU (loaded at boot)
@@ -135,25 +259,30 @@ unix_diag
netlink_diag
EOF
-# Load them now
-sudo modprobe inet_diag tcp_diag udp_diag unix_diag netlink_diag
-
# -------------------------------------------------------------------
# Enable services
# -------------------------------------------------------------------
echo "==> Enabling services..."
sudo systemctl daemon-reload
-sudo systemctl enable caddy
+sudo systemctl enable opensandbox-nvme
+sudo systemctl enable opensandbox-identity
sudo systemctl enable opensandbox-worker
+sudo systemctl enable caddy 2>/dev/null || true
+
+# -------------------------------------------------------------------
+# Cleanup
+# -------------------------------------------------------------------
+echo "==> Cleaning up build tools..."
+sudo apt-get clean
+sudo rm -rf /usr/local/go $HOME/go
echo ""
echo "============================================"
-echo " Instance setup complete!"
+echo " Instance setup complete! ($ARCH)"
echo ""
-echo " Remaining manual steps:"
-echo " 1. Copy worker.env.example to /etc/opensandbox/worker.env and fill in secrets"
-echo " 2. Copy Caddyfile to /etc/caddy/Caddyfile (if not already done)"
-echo " 3. Deploy the worker binary: ./deploy/ec2/deploy-worker.sh"
-echo " 4. Start services: sudo systemctl start caddy opensandbox-worker"
-echo " 5. Set up wildcard DNS: *.workers.opensandbox.ai -> this instance IP"
+echo " Remaining steps:"
+echo " 1. Deploy the worker binary: ./deploy/ec2/deploy-worker.sh"
+echo " 2. Copy Caddyfile to /etc/caddy/Caddyfile"
+echo " 3. Start services: sudo systemctl start opensandbox-worker"
+echo " 4. Set up wildcard DNS: *.workers.opensandbox.ai -> this instance IP"
echo "============================================"
diff --git a/deploy/ec2/setup-secrets.sh b/deploy/ec2/setup-secrets.sh
new file mode 100755
index 00000000..2aae2609
--- /dev/null
+++ b/deploy/ec2/setup-secrets.sh
@@ -0,0 +1,333 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+# =============================================================================
+# OpenSandbox — AWS Secrets Manager + IAM Setup (Digger account)
+#
+# This script creates:
+# 1. Two Secrets Manager secrets (worker + server)
+# 2. An IAM policy for EC2 instances (Secrets Manager + S3 + ECR)
+# 3. An IAM role + instance profile for EC2 instances
+# 4. Attaches the instance profile to running instances
+#
+# Prerequisites:
+# - AWS CLI v2 with "digger" profile configured
+# - jq installed (brew install jq / apt install jq)
+#
+# Usage:
+# ./deploy/ec2/setup-secrets.sh
+# =============================================================================
+
+AWS_PROFILE="digger"
+REGION="us-east-2"
+WORKER_SECRET_NAME="opensandbox/worker"
+SERVER_SECRET_NAME="opensandbox/server"
+S3_BUCKET="opensandbox-checkpoints-digger"
+ROLE_NAME="opensandbox-worker-role"
+POLICY_NAME="opensandbox-worker-policy"
+INSTANCE_PROFILE_NAME="opensandbox-worker"
+ECR_REGISTRY="739940681129.dkr.ecr.us-east-2.amazonaws.com"
+ECR_REPOSITORY="opensandbox-templates"
+
+# Known infrastructure — pulled from running production instances
+REDIS_URL="redis://opensandbox-redis.c1cbz5.0001.use2.cache.amazonaws.com:6379"
+RDS_HOST="opensandbox-pg.chwjcxjqzouh.us-east-2.rds.amazonaws.com"
+RDS_PASSWORD="OpnSbx2026SecurePG"
+JWT_SECRET="${JWT_SECRET}"
+DATABASE_URL="postgres://opensandbox:${RDS_PASSWORD}@${RDS_HOST}:5432/opensandbox?sslmode=require"
+
+# WorkOS (server only)
+WORKOS_API_KEY="${WORKOS_API_KEY}"
+WORKOS_CLIENT_ID="${WORKOS_CLIENT_ID}"
+WORKOS_REDIRECT_URI="https://app.opensandbox.ai/auth/callback"
+WORKOS_COOKIE_DOMAIN="opensandbox.ai"
+
+# Shorthand — every aws call uses the digger profile
+aws() { command aws --profile "$AWS_PROFILE" "$@"; }
+
+# --- Colors ---
+GREEN='\033[0;32m'
+YELLOW='\033[1;33m'
+NC='\033[0m'
+
+echo -e "${GREEN}==> OpenSandbox Secrets Manager Setup (profile: ${AWS_PROFILE})${NC}"
+echo ""
+
+# --- Step 0: Verify credentials ---
+ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
+echo -e "AWS Account: ${GREEN}${ACCOUNT_ID}${NC}"
+echo -e "Region: ${GREEN}${REGION}${NC}"
+echo -e "Redis: ${GREEN}${REDIS_URL}${NC}"
+echo -e "RDS Host: ${GREEN}${RDS_HOST}${NC}"
+echo -e "S3 Bucket: ${GREEN}${S3_BUCKET}${NC}"
+echo -e "ECR: ${GREEN}${ECR_REGISTRY}/${ECR_REPOSITORY}${NC}"
+echo -e "S3 Auth: ${GREEN}IAM instance profile (no static keys)${NC}"
+echo ""
+
+# --- Step 1: Create worker secret ---
+echo -e "${YELLOW}==> Step 1: Creating worker secret (${WORKER_SECRET_NAME})...${NC}"
+
+WORKER_SECRET_JSON=$(jq -n \
+ --arg jwt "$JWT_SECRET" \
+ --arg redis "$REDIS_URL" \
+ --arg db "$DATABASE_URL" \
+ --arg s3bucket "$S3_BUCKET" \
+ --arg s3region "$REGION" \
+ --arg ecr_registry "$ECR_REGISTRY" \
+ --arg ecr_repo "$ECR_REPOSITORY" \
+ '{
+ "OPENSANDBOX_JWT_SECRET": $jwt,
+ "OPENSANDBOX_REDIS_URL": $redis,
+ "DATABASE_URL": $db,
+ "OPENSANDBOX_S3_BUCKET": $s3bucket,
+ "OPENSANDBOX_S3_REGION": $s3region,
+ "OPENSANDBOX_ECR_REGISTRY": $ecr_registry,
+ "OPENSANDBOX_ECR_REPOSITORY": $ecr_repo
+ }')
+
+if aws secretsmanager describe-secret --secret-id "$WORKER_SECRET_NAME" --region "$REGION" &>/dev/null; then
+ echo "Secret '$WORKER_SECRET_NAME' already exists — updating..."
+ aws secretsmanager put-secret-value \
+ --secret-id "$WORKER_SECRET_NAME" \
+ --region "$REGION" \
+ --secret-string "$WORKER_SECRET_JSON"
+else
+ aws secretsmanager create-secret \
+ --name "$WORKER_SECRET_NAME" \
+ --region "$REGION" \
+ --description "OpenSandbox worker secrets (JWT, Redis, S3, DB, ECR)" \
+ --secret-string "$WORKER_SECRET_JSON"
+fi
+
+WORKER_SECRET_ARN=$(aws secretsmanager describe-secret \
+ --secret-id "$WORKER_SECRET_NAME" \
+ --region "$REGION" \
+ --query 'ARN' --output text)
+
+echo -e "Worker Secret ARN: ${GREEN}${WORKER_SECRET_ARN}${NC}"
+echo ""
+
+# --- Step 2: Create server secret ---
+echo -e "${YELLOW}==> Step 2: Creating server secret (${SERVER_SECRET_NAME})...${NC}"
+
+SERVER_SECRET_JSON=$(jq -n \
+ --arg jwt "$JWT_SECRET" \
+ --arg redis "$REDIS_URL" \
+ --arg db "$DATABASE_URL" \
+ --arg s3bucket "$S3_BUCKET" \
+ --arg s3region "$REGION" \
+ --arg ecr_registry "$ECR_REGISTRY" \
+ --arg ecr_repo "$ECR_REPOSITORY" \
+ --arg workos_key "$WORKOS_API_KEY" \
+ --arg workos_client "$WORKOS_CLIENT_ID" \
+ --arg workos_redirect "$WORKOS_REDIRECT_URI" \
+ --arg workos_cookie "$WORKOS_COOKIE_DOMAIN" \
+ '{
+ "OPENSANDBOX_JWT_SECRET": $jwt,
+ "OPENSANDBOX_REDIS_URL": $redis,
+ "DATABASE_URL": $db,
+ "OPENSANDBOX_S3_BUCKET": $s3bucket,
+ "OPENSANDBOX_S3_REGION": $s3region,
+ "OPENSANDBOX_ECR_REGISTRY": $ecr_registry,
+ "OPENSANDBOX_ECR_REPOSITORY": $ecr_repo,
+ "WORKOS_API_KEY": $workos_key,
+ "WORKOS_CLIENT_ID": $workos_client,
+ "WORKOS_REDIRECT_URI": $workos_redirect,
+ "WORKOS_COOKIE_DOMAIN": $workos_cookie
+ }')
+
+if aws secretsmanager describe-secret --secret-id "$SERVER_SECRET_NAME" --region "$REGION" &>/dev/null; then
+ echo "Secret '$SERVER_SECRET_NAME' already exists — updating..."
+ aws secretsmanager put-secret-value \
+ --secret-id "$SERVER_SECRET_NAME" \
+ --region "$REGION" \
+ --secret-string "$SERVER_SECRET_JSON"
+else
+ aws secretsmanager create-secret \
+ --name "$SERVER_SECRET_NAME" \
+ --region "$REGION" \
+ --description "OpenSandbox server secrets (JWT, Redis, S3, DB, ECR, WorkOS)" \
+ --secret-string "$SERVER_SECRET_JSON"
+fi
+
+SERVER_SECRET_ARN=$(aws secretsmanager describe-secret \
+ --secret-id "$SERVER_SECRET_NAME" \
+ --region "$REGION" \
+ --query 'ARN' --output text)
+
+echo -e "Server Secret ARN: ${GREEN}${SERVER_SECRET_ARN}${NC}"
+echo ""
+
+# --- Step 3: Create IAM policy ---
+echo -e "${YELLOW}==> Step 3: Creating IAM policy...${NC}"
+
+POLICY_DOC=$(cat <<EOF
+{
+ "Version": "2012-10-17",
+ "Statement": [
+ {
+ "Sid": "SecretsManagerAccess",
+ "Effect": "Allow",
+ "Action": "secretsmanager:GetSecretValue",
+ "Resource": [
+ "${WORKER_SECRET_ARN}",
+ "${SERVER_SECRET_ARN}"
+ ]
+ },
+ {
+ "Sid": "S3CheckpointAccess",
+ "Effect": "Allow",
+ "Action": [
+ "s3:GetObject",
+ "s3:PutObject",
+ "s3:DeleteObject",
+ "s3:ListBucket"
+ ],
+ "Resource": [
+ "arn:aws:s3:::${S3_BUCKET}",
+ "arn:aws:s3:::${S3_BUCKET}/*"
+ ]
+ },
+ {
+ "Sid": "ECRAccess",
+ "Effect": "Allow",
+ "Action": [
+ "ecr:GetAuthorizationToken",
+ "ecr:BatchCheckLayerAvailability",
+ "ecr:GetDownloadUrlForLayer",
+ "ecr:BatchGetImage"
+ ],
+ "Resource": "*"
+ }
+ ]
+}
+EOF
+)
+
+EXISTING_POLICY_ARN=$(aws iam list-policies \
+ --query "Policies[?PolicyName=='${POLICY_NAME}'].Arn" \
+ --output text 2>/dev/null || echo "")
+
+if [ -n "$EXISTING_POLICY_ARN" ] && [ "$EXISTING_POLICY_ARN" != "None" ]; then
+ echo "Policy '$POLICY_NAME' already exists — creating new version..."
+ # Delete oldest non-default version if at limit (max 5 versions)
+ OLD_VERSION=$(aws iam list-policy-versions \
+ --policy-arn "$EXISTING_POLICY_ARN" \
+ --query 'Versions[?IsDefaultVersion==`false`].VersionId | [0]' \
+ --output text 2>/dev/null || echo "None")
+ if [ -n "$OLD_VERSION" ] && [ "$OLD_VERSION" != "None" ]; then
+ aws iam delete-policy-version \
+ --policy-arn "$EXISTING_POLICY_ARN" \
+ --version-id "$OLD_VERSION" 2>/dev/null || true
+ fi
+ aws iam create-policy-version \
+ --policy-arn "$EXISTING_POLICY_ARN" \
+ --policy-document "$POLICY_DOC" \
+ --set-as-default
+ POLICY_ARN="$EXISTING_POLICY_ARN"
+else
+ POLICY_ARN=$(aws iam create-policy \
+ --policy-name "$POLICY_NAME" \
+ --description "OpenSandbox: Secrets Manager + S3 + ECR access" \
+ --policy-document "$POLICY_DOC" \
+ --query 'Policy.Arn' --output text)
+fi
+
+echo -e "Policy ARN: ${GREEN}${POLICY_ARN}${NC}"
+echo ""
+
+# --- Step 4: Create IAM role + instance profile ---
+echo -e "${YELLOW}==> Step 4: Creating IAM role and instance profile...${NC}"
+
+TRUST_POLICY=$(cat <<'EOF'
+{
+ "Version": "2012-10-17",
+ "Statement": [
+ {
+ "Effect": "Allow",
+ "Principal": { "Service": "ec2.amazonaws.com" },
+ "Action": "sts:AssumeRole"
+ }
+ ]
+}
+EOF
+)
+
+if aws iam get-role --role-name "$ROLE_NAME" &>/dev/null; then
+ echo "Role '$ROLE_NAME' already exists"
+else
+ aws iam create-role \
+ --role-name "$ROLE_NAME" \
+ --assume-role-policy-document "$TRUST_POLICY" \
+ --description "OpenSandbox EC2 role (workers + server)"
+ echo "Created role '$ROLE_NAME'"
+fi
+
+aws iam attach-role-policy \
+ --role-name "$ROLE_NAME" \
+ --policy-arn "$POLICY_ARN" 2>/dev/null || true
+echo "Attached policy to role"
+
+if aws iam get-instance-profile --instance-profile-name "$INSTANCE_PROFILE_NAME" &>/dev/null; then
+ echo "Instance profile '$INSTANCE_PROFILE_NAME' already exists"
+else
+ aws iam create-instance-profile \
+ --instance-profile-name "$INSTANCE_PROFILE_NAME"
+ echo "Created instance profile '$INSTANCE_PROFILE_NAME'"
+
+ aws iam add-role-to-instance-profile \
+ --instance-profile-name "$INSTANCE_PROFILE_NAME" \
+ --role-name "$ROLE_NAME"
+ echo "Added role to instance profile"
+fi
+
+echo ""
+
+# --- Step 5: Attach to existing instances ---
+echo -e "${YELLOW}==> Step 5: Attaching instance profile to running instances...${NC}"
+
+ALL_INSTANCES=$(aws ec2 describe-instances \
+ --region "$REGION" \
+ --filters "Name=instance-state-name,Values=running" \
+ --query 'Reservations[].Instances[?Tags[?Key==`Name` && contains(Value, `opensandbox`)]].InstanceId' \
+ --output text 2>/dev/null || echo "")
+
+if [ -n "$ALL_INSTANCES" ] && [ "$ALL_INSTANCES" != "None" ]; then
+ for INSTANCE_ID in $ALL_INSTANCES; do
+ echo -n " Attaching to $INSTANCE_ID... "
+ aws ec2 associate-iam-instance-profile \
+ --region "$REGION" \
+ --instance-id "$INSTANCE_ID" \
+ --iam-instance-profile Name="$INSTANCE_PROFILE_NAME" 2>/dev/null \
+ && echo "done" \
+ || echo "(already attached or error)"
+ done
+else
+ echo "No running opensandbox instances found."
+fi
+
+echo ""
+
+# --- Done ---
+echo -e "${GREEN}============================================${NC}"
+echo -e "${GREEN} Setup complete!${NC}"
+echo ""
+echo "Worker Secret ARN: $WORKER_SECRET_ARN"
+echo "Server Secret ARN: $SERVER_SECRET_ARN"
+echo "IAM Role: $ROLE_NAME"
+echo "Instance Profile: $INSTANCE_PROFILE_NAME"
+echo ""
+echo "Next steps:"
+echo ""
+echo " Worker — update systemd unit to use Secrets Manager:"
+echo " sudo systemctl edit opensandbox-worker --force"
+echo " # Replace inline secrets with:"
+echo " # Environment=OPENSANDBOX_SECRETS_ARN=${WORKER_SECRET_ARN}"
+echo ""
+echo " Server — update env file to use Secrets Manager:"
+echo " Add to /etc/opensandbox/server.env:"
+echo " OPENSANDBOX_SECRETS_ARN=${SERVER_SECRET_ARN}"
+echo " Then remove: DATABASE_URL, OPENSANDBOX_REDIS_URL, OPENSANDBOX_JWT_SECRET,"
+echo " OPENSANDBOX_S3_*, OPENSANDBOX_ECR_*, WORKOS_*"
+echo ""
+echo -e "${GREEN}============================================${NC}"
diff --git a/deploy/ec2/worker.env.example b/deploy/ec2/worker.env.example
index 867725b6..51e5c954 100644
--- a/deploy/ec2/worker.env.example
+++ b/deploy/ec2/worker.env.example
@@ -9,20 +9,53 @@ OPENSANDBOX_WORKER_ID=w-use2-1
OPENSANDBOX_HTTP_ADDR=http://<WORKER_PUBLIC_IP>:8080
OPENSANDBOX_GRPC_ADVERTISE=<WORKER_PUBLIC_IP>:9090
-# Redis (local)
-OPENSANDBOX_REDIS_URL=redis://default:<REDIS_PASSWORD>@127.0.0.1:6379
-
-# Auth
-OPENSANDBOX_JWT_SECRET=<JWT_SECRET>
-
# Domain for sandbox routing (wildcard DNS must point to this instance)
OPENSANDBOX_SANDBOX_DOMAIN=workers.opensandbox.ai
-# S3 — used for checkpoint storage
-OPENSANDBOX_S3_ACCESS_KEY_ID=<AWS_ACCESS_KEY_ID>
-OPENSANDBOX_S3_SECRET_ACCESS_KEY=<AWS_SECRET_ACCESS_KEY>
-OPENSANDBOX_S3_BUCKET=opensandbox-checkpoints
-OPENSANDBOX_S3_REGION=us-east-2
+# --- Secrets Manager (recommended) ---
+# Store all secrets in a single Secrets Manager secret as a JSON object.
+# The worker fetches them at startup using the EC2 instance's IAM role.
+# Keys in the secret should match env var names (e.g. OPENSANDBOX_JWT_SECRET).
+# Any env vars set here take precedence over values from Secrets Manager.
+#
+# OPENSANDBOX_SECRETS_ARN=arn:aws:secretsmanager:us-east-2:123456789012:secret:opensandbox/worker-AbCdEf
+#
+# If using Secrets Manager, you do NOT need to set the secrets below.
+# The JSON secret should contain:
+# {
+# "OPENSANDBOX_JWT_SECRET": "...",
+# "OPENSANDBOX_REDIS_URL": "redis://...",
+# "OPENSANDBOX_S3_ACCESS_KEY_ID": "...",
+# "OPENSANDBOX_S3_SECRET_ACCESS_KEY": "...",
+# "OPENSANDBOX_S3_BUCKET": "opensandbox-checkpoints",
+# "OPENSANDBOX_S3_REGION": "us-east-2",
+# "DATABASE_URL": "postgres://..."
+# }
+
+# --- OR: inline secrets (for manual deployments without IAM roles) ---
+# OPENSANDBOX_JWT_SECRET=<JWT_SECRET>
+# OPENSANDBOX_REDIS_URL=redis://default:<REDIS_PASSWORD>@127.0.0.1:6379
+# OPENSANDBOX_S3_ACCESS_KEY_ID=<AWS_ACCESS_KEY_ID>
+# OPENSANDBOX_S3_SECRET_ACCESS_KEY=<AWS_SECRET_ACCESS_KEY>
+# OPENSANDBOX_S3_BUCKET=opensandbox-checkpoints
+# OPENSANDBOX_S3_REGION=us-east-2
+# DATABASE_URL=postgres://<DB_USER>:<DB_PASSWORD>@<DB_HOST>:5432/opensandbox?sslmode=disable
+
+# --- Sandbox resource defaults ---
+# Adjust per instance type for benchmarking:
+#
+# c7gd.metal (64 vCPU, 128GB RAM, 3.8TB NVMe):
+# OPENSANDBOX_MAX_CAPACITY=32
+# OPENSANDBOX_DEFAULT_SANDBOX_MEMORY_MB=4096
+# OPENSANDBOX_DEFAULT_SANDBOX_CPUS=2
+#
+# r6gd.metal / r7gd.metal (64 vCPU, 512GB RAM, 3.8TB NVMe):
+# OPENSANDBOX_MAX_CAPACITY=32
+# OPENSANDBOX_DEFAULT_SANDBOX_MEMORY_MB=16384
+# OPENSANDBOX_DEFAULT_SANDBOX_CPUS=2
+# (or: MAX_CAPACITY=64, MEMORY_MB=8192, CPUS=1 for higher density)
-# Postgres (control plane database)
-DATABASE_URL=postgres://<DB_USER>:<DB_PASSWORD>@<DB_HOST>:5432/opensandbox?sslmode=disable
+OPENSANDBOX_MAX_CAPACITY=32
+OPENSANDBOX_DEFAULT_SANDBOX_MEMORY_MB=4096
+OPENSANDBOX_DEFAULT_SANDBOX_CPUS=2
+OPENSANDBOX_DEFAULT_SANDBOX_DISK_MB=51200
diff --git a/deploy/fly-worker.toml b/deploy/fly-worker.toml
deleted file mode 100644
index 1fa33356..00000000
--- a/deploy/fly-worker.toml
+++ /dev/null
@@ -1,45 +0,0 @@
-app = "opensandbox-worker"
-primary_region = "iad"
-
-[build]
- dockerfile = "Dockerfile.worker"
-
-# HTTP service for direct SDK access
-[http_service]
- internal_port = 8080
- force_https = true
- auto_stop_machines = false
- auto_start_machines = true
- min_machines_running = 1
-
-# gRPC service for control plane communication
-[[services]]
- protocol = "tcp"
- internal_port = 9090
- [[services.ports]]
- port = 9090
- handlers = ["tls"]
-
-# Metrics endpoint
-[[services]]
- protocol = "tcp"
- internal_port = 9091
- [[services.ports]]
- port = 9091
-
-[env]
- OPENSANDBOX_MODE = "worker"
- OPENSANDBOX_PORT = "8080"
- OPENSANDBOX_REGION = "iad"
- OPENSANDBOX_DATA_DIR = "/data/sandboxes"
- OPENSANDBOX_HTTP_ADDR = "https://worker.opensandbox.ai"
- # Secrets via `fly secrets set`: OPENSANDBOX_JWT_SECRET, OPENSANDBOX_REDIS_URL
-
-[mounts]
- source = "sandbox_data"
- destination = "/data/sandboxes"
-
-[[vm]]
- cpu_kind = "shared"
- cpus = 2
- memory_mb = 2048
diff --git a/deploy/fly.toml b/deploy/fly.toml
deleted file mode 100644
index 53beac88..00000000
--- a/deploy/fly.toml
+++ /dev/null
@@ -1,32 +0,0 @@
-app = "opensandbox"
-primary_region = "iad"
-
-[build]
- dockerfile = "Dockerfile.server"
-
-[http_service]
- internal_port = 8080
- force_https = true
- auto_stop_machines = false
- auto_start_machines = true
- min_machines_running = 1
-
-[env]
- OPENSANDBOX_MODE = "server"
- OPENSANDBOX_PORT = "8080"
- OPENSANDBOX_REGION = "iad"
- OPENSANDBOX_WORKER_ID = "cp-iad-1"
- OPENSANDBOX_HTTP_ADDR = "https://app.opensandbox.ai"
- OPENSANDBOX_DATA_DIR = "/data/sandboxes"
- WORKOS_REDIRECT_URI = "https://app.opensandbox.ai/auth/callback"
- WORKOS_COOKIE_DOMAIN = "opensandbox.ai"
- # Secrets via `fly secrets set`: OPENSANDBOX_DATABASE_URL, OPENSANDBOX_JWT_SECRET,
- # WORKOS_API_KEY, WORKOS_CLIENT_ID, OPENSANDBOX_REDIS_URL
-
-[mounts]
- source = "osb_data"
- destination = "/data"
-
-[[vm]]
- size = "shared-cpu-1x"
- memory = "512mb"
diff --git a/deploy/worker-entrypoint.sh b/deploy/worker-entrypoint.sh
deleted file mode 100755
index 23f88ecb..00000000
--- a/deploy/worker-entrypoint.sh
+++ /dev/null
@@ -1,38 +0,0 @@
-#!/bin/sh
-set -e
-
-# Fix cgroup v1 split controller directories on Fly.io VMs.
-#
-# Fly VMs mount cgroup v1 controllers as separate directories like
-# "cpu,cpuacct" and "net_cls,net_prio". On standard Linux systems,
-# "cpu" is a symlink to "cpu,cpuacct", but Fly creates "cpu" as
-# a plain (empty) directory. This breaks podman/crun because they
-# try to create cgroup paths under /sys/fs/cgroup/cpu/ which is
-# not a real cgroup filesystem — just an empty tmpfs directory.
-#
-# Fix: replace the plain directories with symlinks to the real
-# combined controller directories.
-
-fix_cgroup_symlink() {
- local single="$1" # e.g. "cpu"
- local combined="$2" # e.g. "cpu,cpuacct"
-
- combined_path="/sys/fs/cgroup/${combined}"
- single_path="/sys/fs/cgroup/${single}"
-
- # Only fix if the combined path exists and the single path
- # is a directory (not already a symlink)
- if [ -d "$combined_path" ] && [ -d "$single_path" ] && [ ! -L "$single_path" ]; then
- echo "entrypoint: fixing cgroup symlink ${single} -> ${combined}"
- rm -rf "$single_path"
- ln -s "$combined_path" "$single_path"
- fi
-}
-
-# Fix known split cgroup v1 controllers
-fix_cgroup_symlink "cpu" "cpu,cpuacct"
-fix_cgroup_symlink "cpuacct" "cpu,cpuacct"
-fix_cgroup_symlink "net_cls" "net_cls,net_prio"
-fix_cgroup_symlink "net_prio" "net_cls,net_prio"
-
-exec "$@"
diff --git a/go.mod b/go.mod
index 2877b4e9..04952217 100644
--- a/go.mod
+++ b/go.mod
@@ -1,17 +1,21 @@
module github.com/opensandbox/opensandbox
-go 1.23.0
+go 1.24.0
require (
- github.com/aws/aws-sdk-go-v2 v1.41.1
- github.com/aws/aws-sdk-go-v2/credentials v1.19.8
+ github.com/aws/aws-sdk-go-v2 v1.41.2
+ github.com/aws/aws-sdk-go-v2/config v1.32.10
+ github.com/aws/aws-sdk-go-v2/credentials v1.19.10
+ github.com/aws/aws-sdk-go-v2/service/ec2 v1.290.1
github.com/aws/aws-sdk-go-v2/service/ecr v1.55.2
github.com/aws/aws-sdk-go-v2/service/s3 v1.96.0
+ github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.41.2
github.com/creack/pty v1.1.24
github.com/golang-jwt/jwt/v5 v5.2.1
github.com/google/uuid v1.6.0
github.com/gorilla/websocket v1.5.3
github.com/jackc/pgx/v5 v5.7.2
+ github.com/klauspost/compress v1.18.0
github.com/labstack/echo/v4 v4.12.0
github.com/mattn/go-sqlite3 v1.14.24
github.com/nats-io/nats.go v1.48.0
@@ -24,14 +28,20 @@ require (
require (
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.4 // indirect
- github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.17 // indirect
- github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.17 // indirect
+ github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.18 // indirect
+ github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.18 // indirect
+ github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.18 // indirect
+ github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4 // indirect
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.17 // indirect
- github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4 // indirect
+ github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.5 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.8 // indirect
- github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.17 // indirect
+ github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.18 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.17 // indirect
- github.com/aws/smithy-go v1.24.0 // indirect
+ github.com/aws/aws-sdk-go-v2/service/signin v1.0.6 // indirect
+ github.com/aws/aws-sdk-go-v2/service/sso v1.30.11 // indirect
+ github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.15 // indirect
+ github.com/aws/aws-sdk-go-v2/service/sts v1.41.7 // indirect
+ github.com/aws/smithy-go v1.24.1 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
@@ -40,7 +50,6 @@ require (
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
- github.com/klauspost/compress v1.18.0 // indirect
github.com/labstack/gommon v0.4.2 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
@@ -56,7 +65,7 @@ require (
golang.org/x/crypto v0.37.0 // indirect
golang.org/x/net v0.33.0 // indirect
golang.org/x/sync v0.13.0 // indirect
- golang.org/x/sys v0.32.0 // indirect
+ golang.org/x/sys v0.41.0 // indirect
golang.org/x/text v0.24.0 // indirect
golang.org/x/time v0.8.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20241015192408-796eee8c2d53 // indirect
diff --git a/go.sum b/go.sum
index 4fe6ef13..a60c2e8c 100644
--- a/go.sum
+++ b/go.sum
@@ -1,29 +1,47 @@
-github.com/aws/aws-sdk-go-v2 v1.41.1 h1:ABlyEARCDLN034NhxlRUSZr4l71mh+T5KAeGh6cerhU=
-github.com/aws/aws-sdk-go-v2 v1.41.1/go.mod h1:MayyLB8y+buD9hZqkCW3kX1AKq07Y5pXxtgB+rRFhz0=
+github.com/aws/aws-sdk-go-v2 v1.41.2 h1:LuT2rzqNQsauaGkPK/7813XxcZ3o3yePY0Iy891T2ls=
+github.com/aws/aws-sdk-go-v2 v1.41.2/go.mod h1:IvvlAZQXvTXznUPfRVfryiG1fbzE2NGK6m9u39YQ+S4=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.4 h1:489krEF9xIGkOaaX3CE/Be2uWjiXrkCH6gUX+bZA/BU=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.4/go.mod h1:IOAPF6oT9KCsceNTvvYMNHy0+kMF8akOjeDvPENWxp4=
-github.com/aws/aws-sdk-go-v2/credentials v1.19.8 h1:Jp2JYH1lRT3KhX4mshHPvVYsR5qqRec3hGvEarNYoR0=
-github.com/aws/aws-sdk-go-v2/credentials v1.19.8/go.mod h1:fZG9tuvyVfxknv1rKibIz3DobRaFw1Poe8IKtXB3XYY=
-github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.17 h1:xOLELNKGp2vsiteLsvLPwxC+mYmO6OZ8PYgiuPJzF8U=
-github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.17/go.mod h1:5M5CI3D12dNOtH3/mk6minaRwI2/37ifCURZISxA/IQ=
-github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.17 h1:WWLqlh79iO48yLkj1v3ISRNiv+3KdQoZ6JWyfcsyQik=
-github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.17/go.mod h1:EhG22vHRrvF8oXSTYStZhJc1aUgKtnJe+aOiFEV90cM=
+github.com/aws/aws-sdk-go-v2/config v1.32.10 h1:9DMthfO6XWZYLfzZglAgW5Fyou2nRI5CuV44sTedKBI=
+github.com/aws/aws-sdk-go-v2/config v1.32.10/go.mod h1:2rUIOnA2JaiqYmSKYmRJlcMWy6qTj1vuRFscppSBMcw=
+github.com/aws/aws-sdk-go-v2/credentials v1.19.10 h1:EEhmEUFCE1Yhl7vDhNOI5OCL/iKMdkkYFTRpZXNw7m8=
+github.com/aws/aws-sdk-go-v2/credentials v1.19.10/go.mod h1:RnnlFCAlxQCkN2Q379B67USkBMu1PipEEiibzYN5UTE=
+github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.18 h1:Ii4s+Sq3yDfaMLpjrJsqD6SmG/Wq/P5L/hw2qa78UAY=
+github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.18/go.mod h1:6x81qnY++ovptLE6nWQeWrpXxbnlIex+4H4eYYGcqfc=
+github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.18 h1:F43zk1vemYIqPAwhjTjYIz0irU2EY7sOb/F5eJ3HuyM=
+github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.18/go.mod h1:w1jdlZXrGKaJcNoL+Nnrj+k5wlpGXqnNrKoP22HvAug=
+github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.18 h1:xCeWVjj0ki0l3nruoyP2slHsGArMxeiiaoPN5QZH6YQ=
+github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.18/go.mod h1:r/eLGuGCBw6l36ZRWiw6PaZwPXb6YOj+i/7MizNl5/k=
+github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4 h1:WKuaxf++XKWlHWu9ECbMlha8WOEGm0OUEZqm4K/Gcfk=
+github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4/go.mod h1:ZWy7j6v1vWGmPReu0iSGvRiise4YI5SkR3OHKTZ6Wuc=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.17 h1:JqcdRG//czea7Ppjb+g/n4o8i/R50aTBHkA7vu0lK+k=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.17/go.mod h1:CO+WeGmIdj/MlPel2KwID9Gt7CNq4M65HUfBW97liM0=
+github.com/aws/aws-sdk-go-v2/service/ec2 v1.290.1 h1:iNxv8JSlaMFSo/DDDGsAPgvPuONsfNp6kyJnzjHgIQ4=
+github.com/aws/aws-sdk-go-v2/service/ec2 v1.290.1/go.mod h1:2dMnUs1QzlGzsm46i9oBHAxVHQp7b6qF7PljWcgVEVE=
github.com/aws/aws-sdk-go-v2/service/ecr v1.55.2 h1:eEiC82g/AJpNtBB73Par9iO/EbWXcl8vh6tbM8wb+EM=
github.com/aws/aws-sdk-go-v2/service/ecr v1.55.2/go.mod h1:cpYRXx5BkmS3mwWRKPbWSPKmyAUNL7aLWAPiiinwk/U=
-github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4 h1:0ryTNEdJbzUCEWkVXEXoqlXV72J5keC1GvILMOuD00E=
-github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4/go.mod h1:HQ4qwNZh32C3CBeO6iJLQlgtMzqeG17ziAA/3KDJFow=
+github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.5 h1:CeY9LUdur+Dxoeldqoun6y4WtJ3RQtzk0JMP2gfUay0=
+github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.5/go.mod h1:AZLZf2fMaahW5s/wMRciu1sYbdsikT/UHwbUjOdEVTc=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.8 h1:Z5EiPIzXKewUQK0QTMkutjiaPVeVYXX7KIqhXu/0fXs=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.8/go.mod h1:FsTpJtvC4U1fyDXk7c71XoDv3HlRm8V3NiYLeYLh5YE=
-github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.17 h1:RuNSMoozM8oXlgLG/n6WLaFGoea7/CddrCfIiSA+xdY=
-github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.17/go.mod h1:F2xxQ9TZz5gDWsclCtPQscGpP0VUOc8RqgFM3vDENmU=
+github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.18 h1:LTRCYFlnnKFlKsyIQxKhJuDuA3ZkrDQMRYm6rXiHlLY=
+github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.18/go.mod h1:XhwkgGG6bHSd00nO/mexWTcTjgd6PjuvWQMqSn2UaEk=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.17 h1:bGeHBsGZx0Dvu/eJC0Lh9adJa3M1xREcndxLNZlve2U=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.17/go.mod h1:dcW24lbU0CzHusTE8LLHhRLI42ejmINN8Lcr22bwh/g=
github.com/aws/aws-sdk-go-v2/service/s3 v1.96.0 h1:oeu8VPlOre74lBA/PMhxa5vewaMIMmILM+RraSyB8KA=
github.com/aws/aws-sdk-go-v2/service/s3 v1.96.0/go.mod h1:5jggDlZ2CLQhwJBiZJb4vfk4f0GxWdEDruWKEJ1xOdo=
-github.com/aws/smithy-go v1.24.0 h1:LpilSUItNPFr1eY85RYgTIg5eIEPtvFbskaFcmmIUnk=
-github.com/aws/smithy-go v1.24.0/go.mod h1:LEj2LM3rBRQJxPZTB4KuzZkaZYnZPnvgIhb4pu07mx0=
+github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.41.2 h1:hezAo5AQM0moD4qitsn8bZuc2WE/MmP+cySGfJWEi1A=
+github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.41.2/go.mod h1:7+wvNfdX7NZtxNyVLbbS89gYldQ3H+1nlVRr7J9KQDA=
+github.com/aws/aws-sdk-go-v2/service/signin v1.0.6 h1:MzORe+J94I+hYu2a6XmV5yC9huoTv8NRcCrUNedDypQ=
+github.com/aws/aws-sdk-go-v2/service/signin v1.0.6/go.mod h1:hXzcHLARD7GeWnifd8j9RWqtfIgxj4/cAtIVIK7hg8g=
+github.com/aws/aws-sdk-go-v2/service/sso v1.30.11 h1:7oGD8KPfBOJGXiCoRKrrrQkbvCp8N++u36hrLMPey6o=
+github.com/aws/aws-sdk-go-v2/service/sso v1.30.11/go.mod h1:0DO9B5EUJQlIDif+XJRWCljZRKsAFKh3gpFz7UnDtOo=
+github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.15 h1:edCcNp9eGIUDUCrzoCu1jWAXLGFIizeqkdkKgRlJwWc=
+github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.15/go.mod h1:lyRQKED9xWfgkYC/wmmYfv7iVIM68Z5OQ88ZdcV1QbU=
+github.com/aws/aws-sdk-go-v2/service/sts v1.41.7 h1:NITQpgo9A5NrDZ57uOWj+abvXSb83BbyggcUBVksN7c=
+github.com/aws/aws-sdk-go-v2/service/sts v1.41.7/go.mod h1:sks5UWBhEuWYDPdwlnRFn1w7xWdH29Jcpe+/PJQefEs=
+github.com/aws/smithy-go v1.24.1 h1:VbyeNfmYkWoxMVpGUAbQumkODcYmfMRfZ8yQiH30SK0=
+github.com/aws/smithy-go v1.24.1/go.mod h1:LEj2LM3rBRQJxPZTB4KuzZkaZYnZPnvgIhb4pu07mx0=
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
@@ -143,6 +161,8 @@ golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20=
golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
+golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
+golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0=
golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU=
golang.org/x/time v0.8.0 h1:9i3RxcPv3PZnitoVGMPDKZSq1xW1gK1Xy3ArNOGZfEg=
diff --git a/internal/auth/oauth_handlers.go b/internal/auth/oauth_handlers.go
index 9a790097..ee7e0863 100644
--- a/internal/auth/oauth_handlers.go
+++ b/internal/auth/oauth_handlers.go
@@ -181,7 +181,7 @@ func (h *OAuthHandlers) HandleMe(c echo.Context) error {
}
// isSecureRequest returns true if the request is over HTTPS,
-// either directly or via a TLS-terminating proxy (e.g. fly.io).
+// either directly or via a TLS-terminating proxy (e.g. Caddy, ALB).
func isSecureRequest(c echo.Context) bool {
if c.Request().TLS != nil {
return true
diff --git a/internal/compute/ec2.go b/internal/compute/ec2.go
new file mode 100644
index 00000000..36714a9b
--- /dev/null
+++ b/internal/compute/ec2.go
@@ -0,0 +1,293 @@
+package compute
+
+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/ec2"
+ ec2types "github.com/aws/aws-sdk-go-v2/service/ec2/types"
+)
+
+const (
+ tagRole = "opensandbox:role"
+ tagInstanceType = "opensandbox:instance-type"
+ tagDraining = "opensandbox:draining"
+)
+
+// EC2PoolConfig configures the EC2 compute pool.
+type EC2PoolConfig struct {
+ Region string
+ AccessKeyID string
+ SecretAccessKey string
+ AMI string
+ InstanceType string // "c7gd.metal", "r6gd.metal", "r7gd.metal"
+ SubnetID string
+ SecurityGroupID string
+ KeyName string
+ IAMInstanceProfile string // IAM instance profile name (for Secrets Manager + S3 access)
+ SecretsARN string // Secrets Manager ARN passed to worker env
+}
+
+// EC2Pool implements compute.Pool using AWS EC2 instances.
+type EC2Pool struct {
+ client *ec2.Client
+ cfg EC2PoolConfig
+}
+
+// NewEC2Pool creates an EC2 compute pool.
+// If AccessKeyID is empty, uses the default AWS credential chain (IAM instance profile, env vars, etc.).
+func NewEC2Pool(cfg EC2PoolConfig) (*EC2Pool, error) {
+ var client *ec2.Client
+
+ if cfg.AccessKeyID != "" {
+ // Static credentials
+ awsCfg := aws.Config{
+ Region: cfg.Region,
+ Credentials: credentials.NewStaticCredentialsProvider(
+ cfg.AccessKeyID,
+ cfg.SecretAccessKey,
+ "",
+ ),
+ }
+ client = ec2.NewFromConfig(awsCfg)
+ } else {
+ // IAM credential chain
+ awsCfg, err := awsconfig.LoadDefaultConfig(context.Background(),
+ awsconfig.WithRegion(cfg.Region),
+ )
+ if err != nil {
+ return nil, fmt.Errorf("ec2: failed to load AWS config: %w", err)
+ }
+ client = ec2.NewFromConfig(awsCfg)
+ }
+
+ return &EC2Pool{
+ client: client,
+ cfg: cfg,
+ }, nil
+}
+
+func (p *EC2Pool) CreateMachine(ctx context.Context, opts MachineOpts) (*Machine, error) {
+ instanceType := p.cfg.InstanceType
+ if opts.Size != "" {
+ instanceType = opts.Size
+ }
+
+ userData := p.buildUserData(opts)
+
+ input := &ec2.RunInstancesInput{
+ ImageId: aws.String(p.cfg.AMI),
+ InstanceType: ec2types.InstanceType(instanceType),
+ MinCount: aws.Int32(1),
+ MaxCount: aws.Int32(1),
+ UserData: aws.String(base64.StdEncoding.EncodeToString([]byte(userData))),
+ TagSpecifications: []ec2types.TagSpecification{
+ {
+ ResourceType: ec2types.ResourceTypeInstance,
+ Tags: []ec2types.Tag{
+ {Key: aws.String("Name"), Value: aws.String("opensandbox-worker")},
+ {Key: aws.String(tagRole), Value: aws.String("worker")},
+ {Key: aws.String(tagInstanceType), Value: aws.String(instanceType)},
+ },
+ },
+ },
+ }
+
+ if p.cfg.SubnetID != "" {
+ input.SubnetId = aws.String(p.cfg.SubnetID)
+ }
+ if p.cfg.SecurityGroupID != "" {
+ input.SecurityGroupIds = []string{p.cfg.SecurityGroupID}
+ }
+ if p.cfg.KeyName != "" {
+ input.KeyName = aws.String(p.cfg.KeyName)
+ }
+ if p.cfg.IAMInstanceProfile != "" {
+ input.IamInstanceProfile = &ec2types.IamInstanceProfileSpecification{
+ Name: aws.String(p.cfg.IAMInstanceProfile),
+ }
+ }
+
+ result, err := p.client.RunInstances(ctx, input)
+ if err != nil {
+ return nil, fmt.Errorf("ec2: RunInstances failed: %w", err)
+ }
+
+ if len(result.Instances) == 0 {
+ return nil, fmt.Errorf("ec2: no instances returned")
+ }
+
+ inst := result.Instances[0]
+ return p.instanceToMachine(&inst), nil
+}
+
+func (p *EC2Pool) DestroyMachine(ctx context.Context, machineID string) error {
+ _, err := p.client.TerminateInstances(ctx, &ec2.TerminateInstancesInput{
+ InstanceIds: []string{machineID},
+ })
+ if err != nil {
+ return fmt.Errorf("ec2: TerminateInstances failed for %s: %w", machineID, err)
+ }
+ return nil
+}
+
+func (p *EC2Pool) StartMachine(ctx context.Context, machineID string) error {
+ _, err := p.client.StartInstances(ctx, &ec2.StartInstancesInput{
+ InstanceIds: []string{machineID},
+ })
+ if err != nil {
+ return fmt.Errorf("ec2: StartInstances failed for %s: %w", machineID, err)
+ }
+ return nil
+}
+
+func (p *EC2Pool) StopMachine(ctx context.Context, machineID string) error {
+ _, err := p.client.StopInstances(ctx, &ec2.StopInstancesInput{
+ InstanceIds: []string{machineID},
+ })
+ if err != nil {
+ return fmt.Errorf("ec2: StopInstances failed for %s: %w", machineID, err)
+ }
+ return nil
+}
+
+func (p *EC2Pool) ListMachines(ctx context.Context) ([]*Machine, error) {
+ input := &ec2.DescribeInstancesInput{
+ Filters: []ec2types.Filter{
+ {
+ Name: aws.String("tag:" + tagRole),
+ Values: []string{"worker"},
+ },
+ {
+ Name: aws.String("instance-state-name"),
+ Values: []string{"pending", "running", "stopping", "stopped"},
+ },
+ },
+ }
+
+ result, err := p.client.DescribeInstances(ctx, input)
+ if err != nil {
+ return nil, fmt.Errorf("ec2: DescribeInstances failed: %w", err)
+ }
+
+ var machines []*Machine
+ for _, res := range result.Reservations {
+ for _, inst := range res.Instances {
+ machines = append(machines, p.instanceToMachine(&inst))
+ }
+ }
+ return machines, nil
+}
+
+func (p *EC2Pool) HealthCheck(ctx context.Context, machineID string) error {
+ result, err := p.client.DescribeInstanceStatus(ctx, &ec2.DescribeInstanceStatusInput{
+ InstanceIds: []string{machineID},
+ })
+ if err != nil {
+ return fmt.Errorf("ec2: DescribeInstanceStatus failed for %s: %w", machineID, err)
+ }
+
+ if len(result.InstanceStatuses) == 0 {
+ return fmt.Errorf("ec2: instance %s not found or not running", machineID)
+ }
+
+ status := result.InstanceStatuses[0]
+ if status.InstanceStatus.Status != ec2types.SummaryStatusOk {
+ return fmt.Errorf("ec2: instance %s status is %s", machineID, status.InstanceStatus.Status)
+ }
+ return nil
+}
+
+func (p *EC2Pool) SupportedRegions(_ context.Context) ([]string, error) {
+ return []string{p.cfg.Region}, nil
+}
+
+func (p *EC2Pool) DrainMachine(ctx context.Context, machineID string) error {
+ _, err := p.client.CreateTags(ctx, &ec2.CreateTagsInput{
+ Resources: []string{machineID},
+ Tags: []ec2types.Tag{
+ {Key: aws.String(tagDraining), Value: aws.String("true")},
+ },
+ })
+ if err != nil {
+ return fmt.Errorf("ec2: failed to tag %s as draining: %w", machineID, err)
+ }
+ return nil
+}
+
+func (p *EC2Pool) instanceToMachine(inst *ec2types.Instance) *Machine {
+ id := aws.ToString(inst.InstanceId)
+ status := "creating"
+ if inst.State != nil {
+ switch inst.State.Name {
+ case ec2types.InstanceStateNameRunning:
+ status = "running"
+ case ec2types.InstanceStateNameStopped:
+ status = "stopped"
+ case ec2types.InstanceStateNamePending:
+ status = "creating"
+ case ec2types.InstanceStateNameTerminated, ec2types.InstanceStateNameShuttingDown:
+ status = "stopped"
+ }
+ }
+
+ addr := ""
+ if inst.PrivateIpAddress != nil {
+ addr = fmt.Sprintf("%s:9090", aws.ToString(inst.PrivateIpAddress))
+ }
+
+ httpAddr := ""
+ if inst.PublicIpAddress != nil {
+ httpAddr = fmt.Sprintf("http://%s:8080", aws.ToString(inst.PublicIpAddress))
+ }
+
+ region := ""
+ if inst.Placement != nil {
+ region = aws.ToString(inst.Placement.AvailabilityZone)
+ }
+
+ return &Machine{
+ ID: id,
+ Addr: addr,
+ HTTPAddr: httpAddr,
+ Region: region,
+ Status: status,
+ }
+}
+
+func (p *EC2Pool) buildUserData(opts MachineOpts) string {
+ var sb strings.Builder
+ sb.WriteString("#!/bin/bash\nset -euo pipefail\n\n")
+
+ // Write minimal env file — secrets come from Secrets Manager via IAM role
+ sb.WriteString("mkdir -p /etc/opensandbox\n")
+ sb.WriteString("cat > /etc/opensandbox/worker.env << 'ENVEOF'\n")
+ sb.WriteString("HOME=/root\n")
+ sb.WriteString("OPENSANDBOX_MODE=worker\n")
+ sb.WriteString(fmt.Sprintf("OPENSANDBOX_DATA_DIR=/data/sandboxes\n"))
+ if opts.Region != "" {
+ sb.WriteString(fmt.Sprintf("OPENSANDBOX_REGION=%s\n", opts.Region))
+ }
+ if p.cfg.SecretsARN != "" {
+ sb.WriteString(fmt.Sprintf("OPENSANDBOX_SECRETS_ARN=%s\n", p.cfg.SecretsARN))
+ }
+ sb.WriteString("ENVEOF\n\n")
+
+ // Mount NVMe with XFS project quotas
+ sb.WriteString("# Mount NVMe instance storage with XFS project quotas\n")
+ sb.WriteString("if [ -b /dev/nvme1n1 ]; then\n")
+ sb.WriteString(" mkfs.xfs -f /dev/nvme1n1\n")
+ sb.WriteString(" mkdir -p /data/sandboxes\n")
+ sb.WriteString(" mount -o prjquota /dev/nvme1n1 /data/sandboxes\n")
+ sb.WriteString("fi\n\n")
+
+ // Start the worker service
+ sb.WriteString("systemctl restart opensandbox-worker\n")
+
+ return sb.String()
+}
diff --git a/internal/compute/fly.go b/internal/compute/fly.go
deleted file mode 100644
index 5c2cfcd0..00000000
--- a/internal/compute/fly.go
+++ /dev/null
@@ -1,191 +0,0 @@
-package compute
-
-import (
- "bytes"
- "context"
- "encoding/json"
- "fmt"
- "io"
- "net/http"
- "os"
-)
-
-const flyAPIBase = "https://api.machines.dev/v1"
-
-// FlyPool implements the compute pool interface for Fly.io Machines.
-type FlyPool struct {
- appName string
- token string
- client *http.Client
-}
-
-// NewFlyPool creates a Fly.io compute pool.
-func NewFlyPool(appName string) (*FlyPool, error) {
- token := os.Getenv("FLY_API_TOKEN")
- if token == "" {
- return nil, fmt.Errorf("FLY_API_TOKEN environment variable is required")
- }
- return &FlyPool{
- appName: appName,
- token: token,
- client: &http.Client{},
- }, nil
-}
-
-func (p *FlyPool) CreateMachine(ctx context.Context, opts MachineOpts) (*Machine, error) {
- body := map[string]interface{}{
- "config": map[string]interface{}{
- "image": opts.Image,
- "guest": map[string]interface{}{
- "cpu_kind": "shared",
- "cpus": 2,
- "memory_mb": 2048,
- },
- "services": []map[string]interface{}{
- {
- "ports": []map[string]interface{}{{"port": 9090, "handlers": []string{"tls", "http"}}},
- "protocol": "tcp",
- "internal_port": 9090,
- },
- },
- },
- "region": opts.Region,
- }
-
- data, _ := json.Marshal(body)
- url := fmt.Sprintf("%s/apps/%s/machines", flyAPIBase, p.appName)
-
- req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(data))
- if err != nil {
- return nil, err
- }
- req.Header.Set("Authorization", "Bearer "+p.token)
- req.Header.Set("Content-Type", "application/json")
-
- resp, err := p.client.Do(req)
- if err != nil {
- return nil, fmt.Errorf("fly API request failed: %w", err)
- }
- defer resp.Body.Close()
-
- if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
- respBody, _ := io.ReadAll(resp.Body)
- return nil, fmt.Errorf("fly API returned %d: %s", resp.StatusCode, string(respBody))
- }
-
- var result struct {
- ID string `json:"id"`
- PrivateIP string `json:"private_ip"`
- Region string `json:"region"`
- State string `json:"state"`
- }
- if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
- return nil, fmt.Errorf("failed to decode fly response: %w", err)
- }
-
- return &Machine{
- ID: result.ID,
- Addr: fmt.Sprintf("%s:9090", result.PrivateIP),
- Region: result.Region,
- Status: result.State,
- Capacity: 50,
- }, nil
-}
-
-func (p *FlyPool) DestroyMachine(ctx context.Context, machineID string) error {
- return p.machineAction(ctx, machineID, "DELETE", "")
-}
-
-func (p *FlyPool) StartMachine(ctx context.Context, machineID string) error {
- return p.machineAction(ctx, machineID, "POST", "/start")
-}
-
-func (p *FlyPool) StopMachine(ctx context.Context, machineID string) error {
- return p.machineAction(ctx, machineID, "POST", "/stop")
-}
-
-func (p *FlyPool) ListMachines(ctx context.Context) ([]*Machine, error) {
- url := fmt.Sprintf("%s/apps/%s/machines", flyAPIBase, p.appName)
- req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
- if err != nil {
- return nil, err
- }
- req.Header.Set("Authorization", "Bearer "+p.token)
-
- resp, err := p.client.Do(req)
- if err != nil {
- return nil, fmt.Errorf("fly API request failed: %w", err)
- }
- defer resp.Body.Close()
-
- var results []struct {
- ID string `json:"id"`
- PrivateIP string `json:"private_ip"`
- Region string `json:"region"`
- State string `json:"state"`
- }
- if err := json.NewDecoder(resp.Body).Decode(&results); err != nil {
- return nil, err
- }
-
- machines := make([]*Machine, len(results))
- for i, r := range results {
- machines[i] = &Machine{
- ID: r.ID,
- Addr: fmt.Sprintf("%s:9090", r.PrivateIP),
- Region: r.Region,
- Status: r.State,
- }
- }
- return machines, nil
-}
-
-func (p *FlyPool) HealthCheck(ctx context.Context, machineID string) error {
- url := fmt.Sprintf("%s/apps/%s/machines/%s", flyAPIBase, p.appName, machineID)
- req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
- if err != nil {
- return err
- }
- req.Header.Set("Authorization", "Bearer "+p.token)
-
- resp, err := p.client.Do(req)
- if err != nil {
- return fmt.Errorf("health check failed: %w", err)
- }
- defer resp.Body.Close()
-
- if resp.StatusCode != http.StatusOK {
- return fmt.Errorf("machine %s returned status %d", machineID, resp.StatusCode)
- }
- return nil
-}
-
-func (p *FlyPool) SupportedRegions(_ context.Context) ([]string, error) {
- return []string{"iad", "ams", "lhr", "sjc", "nrt", "syd", "cdg", "fra"}, nil
-}
-
-func (p *FlyPool) DrainMachine(ctx context.Context, machineID string) error {
- // Stop the machine gracefully (Fly will drain connections)
- return p.StopMachine(ctx, machineID)
-}
-
-func (p *FlyPool) machineAction(ctx context.Context, machineID, method, action string) error {
- url := fmt.Sprintf("%s/apps/%s/machines/%s%s", flyAPIBase, p.appName, machineID, action)
- req, err := http.NewRequestWithContext(ctx, method, url, nil)
- if err != nil {
- return err
- }
- req.Header.Set("Authorization", "Bearer "+p.token)
-
- resp, err := p.client.Do(req)
- if err != nil {
- return fmt.Errorf("fly API request failed: %w", err)
- }
- defer resp.Body.Close()
-
- if resp.StatusCode >= 400 {
- respBody, _ := io.ReadAll(resp.Body)
- return fmt.Errorf("fly API returned %d: %s", resp.StatusCode, string(respBody))
- }
- return nil
-}
diff --git a/internal/config/config.go b/internal/config/config.go
index 6a9d4923..fa6164bb 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -1,9 +1,17 @@
package config
import (
+ "context"
+ "encoding/json"
"fmt"
+ "log"
"os"
"strconv"
+ "strings"
+ "time"
+
+ awsconfig "github.com/aws/aws-sdk-go-v2/config"
+ "github.com/aws/aws-sdk-go-v2/service/secretsmanager"
)
// Config holds all configuration for the opensandbox server.
@@ -56,10 +64,42 @@ type Config struct {
// 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 512
+ DefaultSandboxCPUs int // default vCPUs per sandbox, default 1
+ DefaultSandboxDiskMB int // default disk quota per sandbox (MB), 0 = no quota
+
+ // AWS EC2 compute pool (server mode only — for auto-scaling worker machines)
+ EC2AMI string // Custom AMI with Podman+CRIU pre-installed
+ EC2InstanceType string // e.g. "c7gd.metal", "r6gd.metal", "r7gd.metal"
+ EC2SubnetID string // VPC subnet for worker instances
+ EC2SecurityGroupID string // Security group (allow 8080, 9090, 9091)
+ EC2KeyName string // SSH key pair name (for debugging)
+ EC2WorkerImage string // Docker image for containerized workers
+ EC2IAMInstanceProfile string // IAM instance profile for worker instances (Secrets Manager + S3)
+
+ // Autoscaler
+ ScaleCooldownSec int // Cooldown between scale-up actions (seconds), default 300
+
+ // AWS Secrets Manager — if set, secrets are fetched at startup using IAM credentials.
+ // The secret should be a JSON object with keys matching env var names (e.g. OPENSANDBOX_JWT_SECRET).
+ // Env vars take precedence over secret values (for local overrides).
+ SecretsARN string
}
// Load reads configuration from environment variables with sensible defaults.
+// If OPENSANDBOX_SECRETS_ARN is set, secrets are fetched from AWS Secrets Manager
+// first, then environment variables are applied on top (env vars take precedence).
func Load() (*Config, error) {
+ // Fetch secrets from AWS Secrets Manager if configured.
+ // This populates the process environment so subsequent os.Getenv calls pick them up.
+ if arn := os.Getenv("OPENSANDBOX_SECRETS_ARN"); arn != "" {
+ if err := loadSecretsManager(arn); err != nil {
+ return nil, fmt.Errorf("failed to load secrets from %s: %w", arn, err)
+ }
+ }
+
cfg := &Config{
Port: 8080,
APIKey: os.Getenv("OPENSANDBOX_API_KEY"),
@@ -96,6 +136,22 @@ func Load() (*Config, error) {
ECRRegistry: os.Getenv("OPENSANDBOX_ECR_REGISTRY"),
ECRRepository: envOrDefault("OPENSANDBOX_ECR_REPOSITORY", "opensandbox-templates"),
+
+ DefaultSandboxMemoryMB: envOrDefaultInt("OPENSANDBOX_DEFAULT_SANDBOX_MEMORY_MB", 512),
+ DefaultSandboxCPUs: envOrDefaultInt("OPENSANDBOX_DEFAULT_SANDBOX_CPUS", 1),
+ DefaultSandboxDiskMB: envOrDefaultInt("OPENSANDBOX_DEFAULT_SANDBOX_DISK_MB", 0),
+
+ EC2AMI: os.Getenv("OPENSANDBOX_EC2_AMI"),
+ EC2InstanceType: envOrDefault("OPENSANDBOX_EC2_INSTANCE_TYPE", "c7gd.metal"),
+ EC2SubnetID: os.Getenv("OPENSANDBOX_EC2_SUBNET_ID"),
+ EC2SecurityGroupID: os.Getenv("OPENSANDBOX_EC2_SECURITY_GROUP_ID"),
+ EC2KeyName: os.Getenv("OPENSANDBOX_EC2_KEY_NAME"),
+ EC2WorkerImage: envOrDefault("OPENSANDBOX_EC2_WORKER_IMAGE", "opensandbox-worker:latest"),
+ EC2IAMInstanceProfile: os.Getenv("OPENSANDBOX_EC2_IAM_INSTANCE_PROFILE"),
+
+ ScaleCooldownSec: envOrDefaultInt("OPENSANDBOX_SCALE_COOLDOWN_SEC", 300),
+
+ SecretsARN: os.Getenv("OPENSANDBOX_SECRETS_ARN"),
}
// Default S3 region to worker region for same-region storage
@@ -129,3 +185,51 @@ func envOrDefaultInt(key string, fallback int) int {
}
return fallback
}
+
+// loadSecretsManager fetches a JSON secret from AWS Secrets Manager and sets
+// any values as environment variables (only if not already set, so explicit
+// env vars always win). Uses the default AWS credential chain (IAM instance
+// profile on EC2, or ~/.aws/credentials locally).
+func loadSecretsManager(arn string) error {
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ // Extract region from ARN: arn:aws:secretsmanager:REGION:ACCOUNT:secret:NAME
+ var opts []func(*awsconfig.LoadOptions) error
+ if parts := strings.Split(arn, ":"); len(parts) >= 4 && parts[3] != "" {
+ opts = append(opts, awsconfig.WithRegion(parts[3]))
+ }
+
+ awsCfg, err := awsconfig.LoadDefaultConfig(ctx, opts...)
+ if err != nil {
+ return fmt.Errorf("load AWS config: %w", err)
+ }
+
+ client := secretsmanager.NewFromConfig(awsCfg)
+ result, err := client.GetSecretValue(ctx, &secretsmanager.GetSecretValueInput{
+ SecretId: &arn,
+ })
+ if err != nil {
+ return fmt.Errorf("GetSecretValue: %w", err)
+ }
+
+ if result.SecretString == nil {
+ return fmt.Errorf("secret %s has no string value", arn)
+ }
+
+ var secrets map[string]string
+ if err := json.Unmarshal([]byte(*result.SecretString), &secrets); err != nil {
+ return fmt.Errorf("parse secret JSON: %w", err)
+ }
+
+ applied := 0
+ for key, value := range secrets {
+ if os.Getenv(key) == "" {
+ os.Setenv(key, value)
+ applied++
+ }
+ }
+
+ log.Printf("config: loaded %d secrets from Secrets Manager (%d keys in secret, env overrides take precedence)", applied, len(secrets))
+ return nil
+}
diff --git a/internal/controlplane/redis_registry.go b/internal/controlplane/redis_registry.go
index 0241caa0..a91c99e3 100644
--- a/internal/controlplane/redis_registry.go
+++ b/internal/controlplane/redis_registry.go
@@ -19,14 +19,15 @@ import (
// WorkerEntry represents a worker in the Redis-backed registry.
type WorkerEntry struct {
- ID string `json:"worker_id"`
- Region string `json:"region"`
- GRPCAddr string `json:"grpc_addr"`
- HTTPAddr string `json:"http_addr"`
- Capacity int `json:"capacity"`
- Current int `json:"current"`
- CPUPct float64 `json:"cpu_pct"`
- MemPct float64 `json:"mem_pct"`
+ ID string `json:"worker_id"`
+ MachineID string `json:"machine_id,omitempty"` // EC2 instance ID
+ Region string `json:"region"`
+ GRPCAddr string `json:"grpc_addr"`
+ HTTPAddr string `json:"http_addr"`
+ Capacity int `json:"capacity"`
+ Current int `json:"current"`
+ CPUPct float64 `json:"cpu_pct"`
+ MemPct float64 `json:"mem_pct"`
}
// RedisWorkerRegistry maintains an in-memory cache of worker state
@@ -203,6 +204,9 @@ func (r *RedisWorkerRegistry) handleHeartbeat(entry WorkerEntry) {
if entry.HTTPAddr != "" {
existing.HTTPAddr = entry.HTTPAddr
}
+ if entry.MachineID != "" {
+ existing.MachineID = entry.MachineID
+ }
} else {
// New worker
r.workers[entry.ID] = &entry
@@ -356,3 +360,62 @@ func (r *RedisWorkerRegistry) Stop() {
r.rdb.Close()
log.Println("redis_registry: stopped")
}
+
+// Regions returns all known regions (satisfies ScalerRegistry).
+func (r *RedisWorkerRegistry) Regions() []string {
+ r.mu.RLock()
+ defer r.mu.RUnlock()
+
+ regionSet := make(map[string]struct{})
+ for _, w := range r.workers {
+ regionSet[w.Region] = struct{}{}
+ }
+
+ regions := make([]string, 0, len(regionSet))
+ for region := range regionSet {
+ regions = append(regions, region)
+ }
+ return regions
+}
+
+// GetWorkersByRegion returns workers in a region (satisfies ScalerRegistry).
+func (r *RedisWorkerRegistry) GetWorkersByRegion(region string) []*WorkerInfo {
+ r.mu.RLock()
+ defer r.mu.RUnlock()
+
+ var result []*WorkerInfo
+ for _, w := range r.workers {
+ if w.Region == region {
+ result = append(result, &WorkerInfo{
+ ID: w.ID,
+ MachineID: w.MachineID,
+ Region: w.Region,
+ GRPCAddr: w.GRPCAddr,
+ HTTPAddr: w.HTTPAddr,
+ Capacity: w.Capacity,
+ Current: w.Current,
+ CPUPct: w.CPUPct,
+ MemPct: w.MemPct,
+ })
+ }
+ }
+ return result
+}
+
+// RegionUtilization returns the average utilization for a region (satisfies ScalerRegistry).
+func (r *RedisWorkerRegistry) RegionUtilization(region string) float64 {
+ workers := r.GetWorkersByRegion(region)
+ if len(workers) == 0 {
+ return 0
+ }
+
+ var totalCap, totalCur int
+ for _, w := range workers {
+ totalCap += w.Capacity
+ totalCur += w.Current
+ }
+ if totalCap == 0 {
+ return 0
+ }
+ return float64(totalCur) / float64(totalCap)
+}
diff --git a/internal/controlplane/scaler.go b/internal/controlplane/scaler.go
index 1f80d17e..b4736d1c 100644
--- a/internal/controlplane/scaler.go
+++ b/internal/controlplane/scaler.go
@@ -10,28 +10,58 @@ import (
)
const (
- scaleUpThreshold = 0.70 // Scale up when utilization > 70%
- scaleDownThreshold = 0.30 // Scale down when utilization < 30%
+ scaleUpThreshold = 0.70 // Scale up when utilization > 70%
+ scaleDownThreshold = 0.30 // Scale down when utilization < 30%
minWorkersPerRegion = 1
- scaleCheckInterval = 10 * time.Second
)
+// ScalerRegistry is the interface the Scaler uses to query worker state.
+// Both WorkerRegistry (NATS) and RedisWorkerRegistry satisfy this.
+type ScalerRegistry interface {
+ Regions() []string
+ GetWorkersByRegion(region string) []*WorkerInfo
+ RegionUtilization(region string) float64
+}
+
+// ScalerConfig configures the autoscaler.
+type ScalerConfig struct {
+ Pool compute.Pool
+ Registry ScalerRegistry
+ WorkerImage string
+ Cooldown time.Duration // minimum time between scale-up actions per region
+ Interval time.Duration // how often to evaluate scaling (0 = default 30s)
+}
+
// Scaler manages autoscaling of workers via the compute Pool.
type Scaler struct {
- pool compute.Pool
- registry *WorkerRegistry
- image string // worker Docker image
- stop chan struct{}
- wg sync.WaitGroup
+ pool compute.Pool
+ registry ScalerRegistry
+ image string
+ cooldown time.Duration
+ interval time.Duration
+ lastScaleUp map[string]time.Time // region -> last scale-up time
+ stop chan struct{}
+ wg sync.WaitGroup
}
// NewScaler creates a new autoscaling controller.
-func NewScaler(pool compute.Pool, registry *WorkerRegistry, workerImage string) *Scaler {
+func NewScaler(cfg ScalerConfig) *Scaler {
+ interval := cfg.Interval
+ if interval <= 0 {
+ interval = 30 * time.Second
+ }
+ cooldown := cfg.Cooldown
+ if cooldown <= 0 {
+ cooldown = 5 * time.Minute
+ }
return &Scaler{
- pool: pool,
- registry: registry,
- image: workerImage,
- stop: make(chan struct{}),
+ pool: cfg.Pool,
+ registry: cfg.Registry,
+ image: cfg.WorkerImage,
+ cooldown: cooldown,
+ interval: interval,
+ lastScaleUp: make(map[string]time.Time),
+ stop: make(chan struct{}),
}
}
@@ -40,7 +70,7 @@ func (s *Scaler) Start() {
s.wg.Add(1)
go func() {
defer s.wg.Done()
- ticker := time.NewTicker(scaleCheckInterval)
+ ticker := time.NewTicker(s.interval)
defer ticker.Stop()
for {
@@ -52,7 +82,7 @@ func (s *Scaler) Start() {
}
}
}()
- log.Println("scaler: autoscaling controller started")
+ log.Printf("scaler: autoscaling controller started (interval=%s, cooldown=%s)", s.interval, s.cooldown)
}
// Stop stops the autoscaling loop.
@@ -76,6 +106,12 @@ func (s *Scaler) evaluateRegion(ctx context.Context, region string) {
utilization := s.registry.RegionUtilization(region)
if utilization > scaleUpThreshold {
+ // Check cooldown before scaling up
+ if last, ok := s.lastScaleUp[region]; ok && time.Since(last) < s.cooldown {
+ log.Printf("scaler: region %s needs scale-up but cooldown active (%s remaining)",
+ region, s.cooldown-time.Since(last))
+ return
+ }
log.Printf("scaler: region %s utilization %.1f%% > %.0f%%, scaling up", region, utilization*100, scaleUpThreshold*100)
s.scaleUp(ctx, region)
} else if utilization < scaleDownThreshold && len(workers) > minWorkersPerRegion {
@@ -96,6 +132,7 @@ func (s *Scaler) scaleUp(ctx context.Context, region string) {
return
}
+ s.lastScaleUp[region] = time.Now()
log.Printf("scaler: created machine %s in %s (addr=%s)", machine.ID, region, machine.Addr)
}
@@ -112,14 +149,22 @@ func (s *Scaler) scaleDown(ctx context.Context, region string, workers []*Worker
return
}
- log.Printf("scaler: draining worker %s in %s (current=%d)", target.ID, region, target.Current)
+ // Use EC2 instance ID (MachineID) for drain/destroy operations.
+ // If the worker hasn't reported its machine ID, skip the drain.
+ machineID := target.MachineID
+ if machineID == "" {
+ log.Printf("scaler: worker %s has no machine ID, skipping drain", target.ID)
+ return
+ }
+
+ log.Printf("scaler: draining worker %s (machine=%s) in %s (current=%d)", target.ID, machineID, region, target.Current)
- if err := s.pool.DrainMachine(ctx, target.ID); err != nil {
- log.Printf("scaler: failed to drain machine %s: %v", target.ID, err)
+ if err := s.pool.DrainMachine(ctx, machineID); err != nil {
+ log.Printf("scaler: failed to drain machine %s: %v", machineID, err)
return
}
- if err := s.pool.DestroyMachine(ctx, target.ID); err != nil {
- log.Printf("scaler: failed to destroy machine %s: %v", target.ID, err)
+ if err := s.pool.DestroyMachine(ctx, machineID); err != nil {
+ log.Printf("scaler: failed to destroy machine %s: %v", machineID, err)
}
}
diff --git a/internal/controlplane/worker_registry.go b/internal/controlplane/worker_registry.go
index 6330214b..308bf32d 100644
--- a/internal/controlplane/worker_registry.go
+++ b/internal/controlplane/worker_registry.go
@@ -12,6 +12,7 @@ import (
// WorkerInfo represents a registered worker.
type WorkerInfo struct {
ID string `json:"worker_id"`
+ MachineID string `json:"machine_id,omitempty"` // EC2 instance ID
Region string `json:"region"`
GRPCAddr string `json:"grpc_addr"`
HTTPAddr string `json:"http_addr"`
@@ -200,6 +201,9 @@ func (r *WorkerRegistry) handleHeartbeat(msg *nats.Msg) {
if hb.HTTPAddr != "" {
existing.HTTPAddr = hb.HTTPAddr
}
+ if hb.MachineID != "" {
+ existing.MachineID = hb.MachineID
+ }
} else {
hb.LastSeen = time.Now()
r.workers[hb.ID] = &hb
diff --git a/internal/ecr/auth.go b/internal/ecr/auth.go
index 85c0a819..acf25038 100644
--- a/internal/ecr/auth.go
+++ b/internal/ecr/auth.go
@@ -7,6 +7,7 @@ import (
"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"
)
@@ -21,19 +22,34 @@ type Config struct {
}
// 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 != "" && c.AccessKey != "" && c.SecretKey != ""
+ return c.Registry != "" && c.Repository != ""
}
// GetAuthToken retrieves a Docker-compatible auth token from ECR.
// Returns (username, password) suitable for `podman 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) {
- awsCfg := aws.Config{
- Region: cfg.Region,
- Credentials: credentials.NewStaticCredentialsProvider(cfg.AccessKey, cfg.SecretKey, ""),
- }
+ var client *ecr.Client
- client := ecr.NewFromConfig(awsCfg)
+ 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)
diff --git a/internal/podman/container.go b/internal/podman/container.go
index d0528816..337822f3 100644
--- a/internal/podman/container.go
+++ b/internal/podman/container.go
@@ -20,6 +20,7 @@ type ContainerConfig struct {
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
@@ -97,6 +98,9 @@ func (c *Client) CreateContainer(ctx context.Context, cfg ContainerConfig) (stri
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)
}
diff --git a/internal/sandbox/hibernate.go b/internal/sandbox/hibernate.go
index 8ba193af..d80c99d8 100644
--- a/internal/sandbox/hibernate.go
+++ b/internal/sandbox/hibernate.go
@@ -1,12 +1,17 @@
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"
@@ -20,22 +25,41 @@ type HibernateResult struct {
}
// Hibernate checkpoints a running sandbox, uploads to S3, and removes the container.
+// The CRIU checkpoint (process memory) is cached on local NVMe for fast same-machine wake.
+// The workspace directory stays on local NVMe and is archived to S3 async for cross-machine wake.
func (m *Manager) Hibernate(ctx context.Context, sandboxID string, checkpointStore *storage.CheckpointStore) (*HibernateResult, error) {
name := m.ContainerName(sandboxID)
// 1. Trim memory before checkpoint (best-effort)
m.trimBeforeCheckpoint(ctx, name)
- // 2. Checkpoint to temp file with zstd compression
- tmpDir, err := os.MkdirTemp("", "osb-checkpoint-")
- if err != nil {
- return nil, fmt.Errorf("failed to create temp dir: %w", err)
+ // 2. Generate S3 key upfront so we can use it for cache path
+ s3Key := storage.CheckpointKey(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 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 for S3 upload
+ // 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)
@@ -46,23 +70,38 @@ func (m *Manager) Hibernate(ctx context.Context, sandboxID string, checkpointSto
return nil, fmt.Errorf("failed to copy checkpoint from VM for sandbox %s: %w", sandboxID, err)
}
} else {
- // On Linux: checkpoint directly to local path
+ // 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)
}
}
- // 3. Upload to S3
- s3Key := storage.CheckpointKey(sandboxID)
+ // 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)
}
- // 4. Remove the container (checkpoint --export already stopped it)
- // Note: timer management now lives in SandboxRouter (caller handles MarkHibernated)
+ // 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,
CheckpointKey: s3Key,
@@ -70,24 +109,51 @@ func (m *Manager) Hibernate(ctx context.Context, sandboxID string, checkpointSto
}, nil
}
-// Wake restores a hibernated sandbox from its S3 checkpoint.
-// The checkpoint is streamed directly into podman restore.
+// Wake restores a hibernated sandbox.
+// Fast path: if CRIU checkpoint + workspace are both on local NVMe, no S3 calls at all.
+// Slow path: downloads missing data from S3 (and caches it locally for next time).
func (m *Manager) Wake(ctx context.Context, sandboxID string, checkpointKey string, checkpointStore *storage.CheckpointStore, timeout int) (*types.Sandbox, error) {
name := m.ContainerName(sandboxID)
- // 1. Download checkpoint as a stream from S3
- reader, err := checkpointStore.Download(ctx, checkpointKey)
- if err != nil {
- return nil, fmt.Errorf("failed to download checkpoint for sandbox %s: %w", sandboxID, err)
+ // 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)
+ }
}
- defer reader.Close()
- // 2. Stream restore via FIFO
- if err := m.podman.RestoreContainerFromStream(ctx, reader, name); err != nil {
- return nil, fmt.Errorf("failed to restore sandbox %s: %w", sandboxID, err)
+ // 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 (timer management now lives in SandboxRouter; caller handles Register)
+ // 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)
@@ -97,7 +163,6 @@ func (m *Manager) Wake(ctx context.Context, sandboxID string, checkpointKey stri
}
// trimBeforeCheckpoint reduces the container's memory footprint before checkpointing.
-// Best-effort: errors are ignored since the container may lack permissions.
func (m *Manager) trimBeforeCheckpoint(ctx context.Context, containerName string) {
trimCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
@@ -114,3 +179,175 @@ func (m *Manager) trimBeforeCheckpoint(ctx context.Context, containerName string
})
}
}
+
+// 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 *Manager) 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 *Manager) 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()
+}
diff --git a/internal/sandbox/manager.go b/internal/sandbox/manager.go
index 18e191b0..47f686e3 100644
--- a/internal/sandbox/manager.go
+++ b/internal/sandbox/manager.go
@@ -3,6 +3,8 @@ package sandbox
import (
"context"
"fmt"
+ "os"
+ "path/filepath"
"strconv"
"time"
@@ -22,8 +24,6 @@ const (
defaultTimeout = 300 // 5 minutes
defaultImage = "docker.io/library/ubuntu:22.04"
- defaultMemoryMB = 1024
- defaultCPU = 1
maxMemoryMB = 2048
maxCPU = 4
)
@@ -31,14 +31,52 @@ const (
// Manager handles sandbox lifecycle operations (pure container executor).
// Timer management and state machine logic live in SandboxRouter.
type Manager struct {
- podman *podman.Client
+ 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 Manager.
+type ManagerOption func(*Manager)
+
+// WithDataDir sets the base directory for per-sandbox persistent data.
+func WithDataDir(dir string) ManagerOption {
+ return func(m *Manager) { m.dataDir = dir }
+}
+
+// WithDefaultMemoryMB sets the default memory per sandbox (in MB).
+func WithDefaultMemoryMB(mb int) ManagerOption {
+ return func(m *Manager) { m.defaultMemoryMB = mb }
+}
+
+// WithDefaultCPUs sets the default vCPU count per sandbox.
+func WithDefaultCPUs(cpus int) ManagerOption {
+ return func(m *Manager) { m.defaultCPU = cpus }
+}
+
+// WithDefaultDiskMB sets the default disk quota per sandbox (in MB). 0 = no quota.
+func WithDefaultDiskMB(mb int) ManagerOption {
+ return func(m *Manager) { m.defaultDiskMB = mb }
}
// NewManager creates a new sandbox manager.
-func NewManager(client *podman.Client) *Manager {
- return &Manager{
- podman: client,
+func NewManager(client *podman.Client, opts ...ManagerOption) *Manager {
+ m := &Manager{
+ 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 *Manager) DataDir() string {
+ return m.dataDir
}
// Create creates a new sandbox container and starts it.
@@ -61,11 +99,11 @@ func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (*types.S
memoryMB := cfg.MemoryMB
if memoryMB <= 0 {
- memoryMB = defaultMemoryMB
+ memoryMB = m.defaultMemoryMB
}
cpuCount := cfg.CpuCount
if cpuCount <= 0 {
- cpuCount = defaultCPU
+ cpuCount = m.defaultCPU
}
now := time.Now()
@@ -98,10 +136,24 @@ func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (*types.S
ccfg.Publish = []string{fmt.Sprintf("%d:%d/tcp", hostPort, containerPort)}
ccfg.Labels[labelHostPort] = strconv.Itoa(hostPort)
- // Make /tmp writable for sandbox use
+ // Make /tmp writable for sandbox use (scratch space, not persisted)
ccfg.TmpFS["/tmp"] = "rw,size=100m"
- // Add a writable workspace directory (default working directory for users)
- ccfg.TmpFS["/workspace"] = "rw,size=200m"
+
+ // 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)
@@ -139,12 +191,16 @@ func (m *Manager) Get(ctx context.Context, id string) (*types.Sandbox, error) {
return containerInfoToSandbox(info), nil
}
-// Kill forcefully removes a sandbox.
+// Kill forcefully removes a sandbox and cleans up its on-disk workspace.
func (m *Manager) 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
}
diff --git a/internal/sandbox/quota.go b/internal/sandbox/quota.go
new file mode 100644
index 00000000..64ceffd7
--- /dev/null
+++ b/internal/sandbox/quota.go
@@ -0,0 +1,139 @@
+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 *Manager) 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 *Manager) 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/storage/s3.go b/internal/storage/s3.go
index e0a39d44..7756f60f 100644
--- a/internal/storage/s3.go
+++ b/internal/storage/s3.go
@@ -2,14 +2,21 @@ package storage
import (
"context"
+ "crypto/sha256"
"fmt"
"io"
+ "log"
"os"
+ "path/filepath"
+ "sort"
+ "sync"
"time"
"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/s3"
+ "golang.org/x/sys/unix"
)
// S3Config holds the configuration for the S3 storage backend.
@@ -22,30 +29,57 @@ type S3Config struct {
ForcePathStyle bool
}
-// CheckpointStore manages checkpoint archives in S3-compatible object storage.
+// CheckpointStore manages checkpoint archives in S3-compatible object storage,
+// with an optional local NVMe cache for fast same-machine wake.
+//
+// S3 is always the source of truth. Local NVMe is a hot cache.
+// On hibernate: CRIU checkpoint + workspace both uploaded to S3, kept locally.
+// On wake: check NVMe first, fall back to S3 download.
+// Eviction: LRU based on real filesystem pressure (keep 20% free for active sandboxes).
type CheckpointStore struct {
- client *s3.Client
- bucket string
+ client *s3.Client
+ bucket string
+ cacheDir string // local NVMe cache for CRIU checkpoints (empty = disabled)
+ cacheMu sync.Mutex
}
// NewCheckpointStore creates a new S3 checkpoint store.
+// If AccessKeyID is empty, uses the default AWS credential chain (IAM instance profile on EC2).
func NewCheckpointStore(cfg S3Config) (*CheckpointStore, error) {
- opts := []func(*s3.Options){
- func(o *s3.Options) {
- o.Region = cfg.Region
- o.Credentials = credentials.NewStaticCredentialsProvider(
- cfg.AccessKeyID, cfg.SecretAccessKey, "",
- )
- if cfg.ForcePathStyle {
- o.UsePathStyle = true
- }
- if cfg.Endpoint != "" {
- o.BaseEndpoint = aws.String(cfg.Endpoint)
- }
- },
- }
-
- client := s3.New(s3.Options{}, opts...)
+ var client *s3.Client
+
+ if cfg.AccessKeyID != "" {
+ opts := []func(*s3.Options){
+ func(o *s3.Options) {
+ o.Region = cfg.Region
+ o.Credentials = credentials.NewStaticCredentialsProvider(
+ cfg.AccessKeyID, cfg.SecretAccessKey, "",
+ )
+ if cfg.ForcePathStyle {
+ o.UsePathStyle = true
+ }
+ if cfg.Endpoint != "" {
+ o.BaseEndpoint = aws.String(cfg.Endpoint)
+ }
+ },
+ }
+ client = s3.New(s3.Options{}, opts...)
+ } else {
+ awsCfg, err := awsconfig.LoadDefaultConfig(context.Background(),
+ awsconfig.WithRegion(cfg.Region),
+ )
+ if err != nil {
+ return nil, fmt.Errorf("failed to load AWS config for S3: %w", err)
+ }
+ var s3Opts []func(*s3.Options)
+ if cfg.ForcePathStyle {
+ s3Opts = append(s3Opts, func(o *s3.Options) { o.UsePathStyle = true })
+ }
+ if cfg.Endpoint != "" {
+ s3Opts = append(s3Opts, func(o *s3.Options) { o.BaseEndpoint = aws.String(cfg.Endpoint) })
+ }
+ client = s3.NewFromConfig(awsCfg, s3Opts...)
+ }
return &CheckpointStore{
client: client,
@@ -53,13 +87,48 @@ func NewCheckpointStore(cfg S3Config) (*CheckpointStore, error) {
}, nil
}
+// SetCacheDir enables local NVMe checkpoint caching at the given directory.
+func (s *CheckpointStore) SetCacheDir(dir string) error {
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ return fmt.Errorf("failed to create checkpoint cache dir: %w", err)
+ }
+ s.cacheDir = dir
+ entries, totalMB, availMB := s.CacheStats()
+ log.Printf("checkpoint-cache: enabled at %s (%d cached entries, %d MB used, %d MB available)",
+ dir, entries, totalMB, availMB)
+ return nil
+}
+
// CheckpointKey returns the S3 key for a checkpoint archive.
func CheckpointKey(sandboxID string) string {
return fmt.Sprintf("checkpoints/%s/%d.tar.zst", sandboxID, time.Now().UnixNano())
}
+// cacheFilename returns a stable filename for a given S3 key.
+func cacheFilename(key string) string {
+ h := sha256.Sum256([]byte(key))
+ return fmt.Sprintf("%x.tar.zst", h[:16])
+}
+
+// CachePath returns the local NVMe cache path for a checkpoint key, or empty if caching is disabled.
+func (s *CheckpointStore) CachePath(key string) string {
+ if s.cacheDir == "" {
+ return ""
+ }
+ return filepath.Join(s.cacheDir, cacheFilename(key))
+}
+
+// CacheHit returns true if the checkpoint exists in the local cache.
+func (s *CheckpointStore) CacheHit(key string) bool {
+ if s.cacheDir == "" {
+ return false
+ }
+ _, err := os.Stat(s.CachePath(key))
+ return err == nil
+}
+
// Upload uploads a checkpoint archive from a local file to S3.
-// Returns the size in bytes.
+// If caching is enabled, the file is also copied into the local NVMe cache.
func (s *CheckpointStore) Upload(ctx context.Context, key, localPath string) (int64, error) {
f, err := os.Open(localPath)
if err != nil {
@@ -82,12 +151,134 @@ func (s *CheckpointStore) Upload(ctx context.Context, key, localPath string) (in
return 0, fmt.Errorf("failed to upload checkpoint to S3: %w", err)
}
+ // Cache locally for fast same-machine wake
+ if s.cacheDir != "" {
+ s.cacheFromFile(localPath, key, stat.Size())
+ }
+
return stat.Size(), nil
}
-// Download returns an io.ReadCloser streaming the checkpoint from S3.
-// The caller must close the reader when done.
+// cacheFromFile copies or hard-links a checkpoint into the local NVMe cache.
+func (s *CheckpointStore) cacheFromFile(localPath, key string, size int64) {
+ s.evictIfNeeded()
+
+ cachePath := s.CachePath(key)
+
+ // Try hard link first (instant, zero copy)
+ if err := os.Link(localPath, cachePath); err == nil {
+ log.Printf("checkpoint-cache: stored %s (%d MB, hard-link)", key, size>>20)
+ return
+ }
+
+ // Hard link failed (cross-device, e.g. /tmp → /data) — file copy
+ src, err := os.Open(localPath)
+ if err != nil {
+ log.Printf("checkpoint-cache: failed to cache %s: %v", key, err)
+ return
+ }
+ defer src.Close()
+
+ dst, err := os.CreateTemp(s.cacheDir, ".cache-tmp-*")
+ if err != nil {
+ log.Printf("checkpoint-cache: failed to create temp: %v", err)
+ return
+ }
+ tmpPath := dst.Name()
+
+ if _, err := io.Copy(dst, src); err != nil {
+ dst.Close()
+ os.Remove(tmpPath)
+ log.Printf("checkpoint-cache: copy failed for %s: %v", key, err)
+ return
+ }
+ dst.Close()
+
+ if err := os.Rename(tmpPath, cachePath); err != nil {
+ os.Remove(tmpPath)
+ log.Printf("checkpoint-cache: rename failed for %s: %v", key, err)
+ return
+ }
+
+ log.Printf("checkpoint-cache: stored %s (%d MB, file-copy)", key, size>>20)
+}
+
+// Download returns an io.ReadCloser for the checkpoint.
+// Checks local NVMe cache first, falls back to S3.
+// On S3 download, caches the result locally for next time.
func (s *CheckpointStore) Download(ctx context.Context, key string) (io.ReadCloser, error) {
+ if s.cacheDir != "" {
+ if reader, err := s.openCached(key); err == nil {
+ return reader, nil
+ }
+ // Cache miss — download from S3 and cache
+ return s.downloadAndCache(ctx, key)
+ }
+ return s.downloadFromS3(ctx, key)
+}
+
+// openCached opens a checkpoint from the local NVMe cache.
+func (s *CheckpointStore) openCached(key string) (io.ReadCloser, error) {
+ cachePath := s.CachePath(key)
+ f, err := os.Open(cachePath)
+ if err != nil {
+ return nil, err
+ }
+ // Touch mtime for LRU tracking
+ now := time.Now()
+ _ = os.Chtimes(cachePath, now, now)
+
+ stat, _ := f.Stat()
+ log.Printf("checkpoint-cache: HIT %s (%d MB from NVMe)", key, stat.Size()>>20)
+ return f, nil
+}
+
+// downloadAndCache downloads from S3, writes to NVMe cache, returns the cached file.
+func (s *CheckpointStore) downloadAndCache(ctx context.Context, key string) (io.ReadCloser, error) {
+ resp, err := s.client.GetObject(ctx, &s3.GetObjectInput{
+ Bucket: aws.String(s.bucket),
+ Key: aws.String(key),
+ })
+ if err != nil {
+ return nil, fmt.Errorf("failed to download checkpoint from S3: %w", err)
+ }
+
+ s.evictIfNeeded()
+
+ cachePath := s.CachePath(key)
+ tmpFile, err := os.CreateTemp(s.cacheDir, ".dl-tmp-*")
+ if err != nil {
+ // Can't write to cache — fall back to direct S3 stream
+ log.Printf("checkpoint-cache: can't create temp, streaming from S3: %v", err)
+ return resp.Body, nil
+ }
+ tmpPath := tmpFile.Name()
+
+ written, err := io.Copy(tmpFile, resp.Body)
+ resp.Body.Close()
+ if err != nil {
+ tmpFile.Close()
+ os.Remove(tmpPath)
+ return nil, fmt.Errorf("failed to download checkpoint from S3: %w", err)
+ }
+ tmpFile.Close()
+
+ if err := os.Rename(tmpPath, cachePath); err != nil {
+ os.Remove(tmpPath)
+ log.Printf("checkpoint-cache: rename failed: %v", err)
+ } else {
+ log.Printf("checkpoint-cache: MISS %s (%d MB downloaded from S3, now cached)", key, written>>20)
+ }
+
+ f, err := os.Open(cachePath)
+ if err != nil {
+ return nil, fmt.Errorf("failed to open cached checkpoint: %w", err)
+ }
+ return f, nil
+}
+
+// downloadFromS3 streams directly from S3 (no caching).
+func (s *CheckpointStore) downloadFromS3(ctx context.Context, key string) (io.ReadCloser, error) {
resp, err := s.client.GetObject(ctx, &s3.GetObjectInput{
Bucket: aws.String(s.bucket),
Key: aws.String(key),
@@ -98,7 +289,79 @@ func (s *CheckpointStore) Download(ctx context.Context, key string) (io.ReadClos
return resp.Body, nil
}
-// Delete removes a checkpoint archive from S3.
+// evictIfNeeded removes the oldest cached checkpoints when the filesystem
+// is low on space. Policy: keep 20% of total filesystem space free for
+// active sandboxes (workspaces, container layers, temp files).
+func (s *CheckpointStore) evictIfNeeded() {
+ s.cacheMu.Lock()
+ defer s.cacheMu.Unlock()
+
+ var stat unix.Statfs_t
+ if err := unix.Statfs(s.cacheDir, &stat); err != nil {
+ log.Printf("checkpoint-cache: statfs failed: %v", err)
+ return
+ }
+
+ totalBytes := stat.Blocks * uint64(stat.Bsize)
+ availBytes := stat.Bavail * uint64(stat.Bsize)
+ reserveBytes := totalBytes / 5 // 20% reserve
+
+ if availBytes > reserveBytes {
+ return
+ }
+
+ entries, err := os.ReadDir(s.cacheDir)
+ if err != nil {
+ log.Printf("checkpoint-cache: readdir failed: %v", err)
+ return
+ }
+
+ type cacheEntry struct {
+ path string
+ size int64
+ mtime time.Time
+ }
+ var files []cacheEntry
+ for _, e := range entries {
+ if e.IsDir() || (len(e.Name()) > 0 && e.Name()[0] == '.') {
+ continue
+ }
+ info, err := e.Info()
+ if err != nil {
+ continue
+ }
+ files = append(files, cacheEntry{
+ path: filepath.Join(s.cacheDir, e.Name()),
+ size: info.Size(),
+ mtime: info.ModTime(),
+ })
+ }
+
+ sort.Slice(files, func(i, j int) bool {
+ return files[i].mtime.Before(files[j].mtime)
+ })
+
+ needToFree := int64(reserveBytes - availBytes)
+ var freed int64
+ var evicted int
+ for _, f := range files {
+ if freed >= needToFree {
+ break
+ }
+ if err := os.Remove(f.path); err != nil {
+ continue
+ }
+ freed += f.size
+ evicted++
+ }
+
+ if evicted > 0 {
+ log.Printf("checkpoint-cache: evicted %d entries, freed %d MB (avail was %d MB, reserve %d MB)",
+ evicted, freed>>20, availBytes>>20, reserveBytes>>20)
+ }
+}
+
+// Delete removes a checkpoint from S3 and from the local cache.
func (s *CheckpointStore) Delete(ctx context.Context, key string) error {
_, err := s.client.DeleteObject(ctx, &s3.DeleteObjectInput{
Bucket: aws.String(s.bucket),
@@ -107,5 +370,42 @@ func (s *CheckpointStore) Delete(ctx context.Context, key string) error {
if err != nil {
return fmt.Errorf("failed to delete checkpoint from S3: %w", err)
}
+
+ if s.cacheDir != "" {
+ os.Remove(s.CachePath(key))
+ }
+
return nil
}
+
+// CacheStats returns current cache statistics.
+func (s *CheckpointStore) CacheStats() (entries int, totalSizeMB int64, availMB int64) {
+ if s.cacheDir == "" {
+ return 0, 0, 0
+ }
+
+ dirEntries, err := os.ReadDir(s.cacheDir)
+ if err != nil {
+ return 0, 0, 0
+ }
+
+ var totalSize int64
+ for _, e := range dirEntries {
+ if e.IsDir() || (len(e.Name()) > 0 && e.Name()[0] == '.') {
+ continue
+ }
+ info, err := e.Info()
+ if err != nil {
+ continue
+ }
+ entries++
+ totalSize += info.Size()
+ }
+
+ var stat unix.Statfs_t
+ if err := unix.Statfs(s.cacheDir, &stat); err == nil {
+ availMB = int64(stat.Bavail*uint64(stat.Bsize)) >> 20
+ }
+
+ return entries, totalSize >> 20, availMB
+}
diff --git a/internal/worker/ec2_metadata.go b/internal/worker/ec2_metadata.go
new file mode 100644
index 00000000..d344babd
--- /dev/null
+++ b/internal/worker/ec2_metadata.go
@@ -0,0 +1,41 @@
+package worker
+
+import (
+ "context"
+ "io"
+ "net/http"
+ "strings"
+ "time"
+)
+
+// GetEC2InstanceID retrieves the EC2 instance ID from IMDSv2.
+// Returns empty string if not running on EC2 or IMDS is unavailable.
+func GetEC2InstanceID() string {
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+
+ // Get IMDSv2 token
+ tokenReq, _ := http.NewRequestWithContext(ctx, "PUT", "http://169.254.169.254/latest/api/token", nil)
+ tokenReq.Header.Set("X-aws-ec2-metadata-token-ttl-seconds", "60")
+ tokenResp, err := http.DefaultClient.Do(tokenReq)
+ if err != nil {
+ return ""
+ }
+ defer tokenResp.Body.Close()
+ tokenBytes, _ := io.ReadAll(tokenResp.Body)
+ token := strings.TrimSpace(string(tokenBytes))
+ if token == "" {
+ return ""
+ }
+
+ // Get instance ID
+ idReq, _ := http.NewRequestWithContext(ctx, "GET", "http://169.254.169.254/latest/meta-data/instance-id", nil)
+ idReq.Header.Set("X-aws-ec2-metadata-token", token)
+ idResp, err := http.DefaultClient.Do(idReq)
+ if err != nil {
+ return ""
+ }
+ defer idResp.Body.Close()
+ idBytes, _ := io.ReadAll(idResp.Body)
+ return strings.TrimSpace(string(idBytes))
+}
diff --git a/internal/worker/redis_heartbeat.go b/internal/worker/redis_heartbeat.go
index bc2badbe..65be7e66 100644
--- a/internal/worker/redis_heartbeat.go
+++ b/internal/worker/redis_heartbeat.go
@@ -12,14 +12,15 @@ import (
// redisHeartbeatPayload is the JSON structure published to Redis.
type redisHeartbeatPayload struct {
- WorkerID string `json:"worker_id"`
- Region string `json:"region"`
- GRPCAddr string `json:"grpc_addr"`
- HTTPAddr string `json:"http_addr"`
- Capacity int `json:"capacity"`
- Current int `json:"current"`
- CPUPct float64 `json:"cpu_pct"`
- MemPct float64 `json:"mem_pct"`
+ WorkerID string `json:"worker_id"`
+ MachineID string `json:"machine_id,omitempty"` // EC2 instance ID (e.g. i-099088f8ac4a34ef3)
+ Region string `json:"region"`
+ GRPCAddr string `json:"grpc_addr"`
+ HTTPAddr string `json:"http_addr"`
+ Capacity int `json:"capacity"`
+ Current int `json:"current"`
+ CPUPct float64 `json:"cpu_pct"`
+ MemPct float64 `json:"mem_pct"`
}
// RedisHeartbeat publishes periodic heartbeats to Redis for worker discovery.
@@ -27,13 +28,14 @@ type redisHeartbeatPayload struct {
// 1. SETs worker:{id} with a 30s TTL (auto-expires if worker dies)
// 2. PUBLISHes to workers:heartbeat for real-time server notification
type RedisHeartbeat struct {
- rdb *redis.Client
- workerID string
- region string
- grpcAddr string
- httpAddr string
- getStats func() (capacity, current int, cpuPct, memPct float64)
- stop chan struct{}
+ rdb *redis.Client
+ workerID string
+ machineID string
+ region string
+ grpcAddr string
+ httpAddr string
+ getStats func() (capacity, current int, cpuPct, memPct float64)
+ stop chan struct{}
}
// NewRedisHeartbeat creates a new heartbeat publisher.
@@ -62,6 +64,11 @@ func NewRedisHeartbeat(redisURL, workerID, region, grpcAddr, httpAddr string) (*
}, nil
}
+// SetMachineID sets the EC2 instance ID for the heartbeat (used by scaler for drain/terminate).
+func (h *RedisHeartbeat) SetMachineID(id string) {
+ h.machineID = id
+}
+
// Start begins publishing heartbeats every 10 seconds.
func (h *RedisHeartbeat) Start(getStats func() (int, int, float64, float64)) {
h.getStats = getStats
@@ -88,14 +95,15 @@ func (h *RedisHeartbeat) publish() {
capacity, current, cpuPct, memPct := h.getStats()
payload := redisHeartbeatPayload{
- WorkerID: h.workerID,
- Region: h.region,
- GRPCAddr: h.grpcAddr,
- HTTPAddr: h.httpAddr,
- Capacity: capacity,
- Current: current,
- CPUPct: cpuPct,
- MemPct: memPct,
+ WorkerID: h.workerID,
+ MachineID: h.machineID,
+ Region: h.region,
+ GRPCAddr: h.grpcAddr,
+ HTTPAddr: h.httpAddr,
+ Capacity: capacity,
+ Current: current,
+ CPUPct: cpuPct,
+ MemPct: memPct,
}
data, err := json.Marshal(payload)
diff --git a/scripts/bench-heavy.sh b/scripts/bench-heavy.sh
new file mode 100755
index 00000000..6273b498
--- /dev/null
+++ b/scripts/bench-heavy.sh
@@ -0,0 +1,306 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+# Heavy benchmark: sandbox with running processes + 2GB user data.
+#
+# Compares:
+# 1. Fresh launch + full setup (install packages, start processes, write 2GB)
+# 2. Wake from local checkpoint (everything already in place)
+# 3. Wake from S3 checkpoint (simulates cross-worker migration)
+#
+# Usage: ./scripts/bench-heavy.sh <server-url> <api-key>
+
+SERVER="${1:?Usage: $0 <server-url> <api-key>}"
+API_KEY="${2:?Usage: $0 <server-url> <api-key>}"
+
+RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'
+CYAN='\033[0;36m'; BOLD='\033[1m'; NC='\033[0m'
+
+header() { echo -e "\n${BOLD}${CYAN}═══════════════════════════════════════════════════════════${NC}"; echo -e "${BOLD}${CYAN} $1${NC}"; echo -e "${BOLD}${CYAN}═══════════════════════════════════════════════════════════${NC}"; }
+info() { echo -e "${YELLOW}→${NC} $1"; }
+ok() { echo -e "${GREEN}✓${NC} $1"; }
+fail() { echo -e "${RED}✗${NC} $1"; }
+timing() { echo -e "${BOLD}${GREEN} ⏱ $1${NC}"; }
+
+api() {
+ local method="$1" path="$2"; shift 2
+ curl -s -w "\n%{http_code}" -X "$method" "${SERVER}${path}" \
+ -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "$@"
+}
+
+parse_response() {
+ local body http_code
+ body=$(echo "$1" | sed '$d')
+ http_code=$(echo "$1" | tail -1)
+ echo "$body"
+ [[ "$http_code" -lt 400 ]] || { fail "HTTP $http_code: $body"; return 1; }
+}
+
+run_cmd() {
+ # run_cmd <sandbox_id> <bash_command> [timeout_secs]
+ local sid="$1" cmd="$2" tout="${3:-30}"
+ local resp
+ resp=$(curl -s --max-time "$tout" -X POST "${EXEC_URL}/sandboxes/${sid}/commands" \
+ -H "${AUTH_HEADER}" -H "Content-Type: application/json" \
+ -d "$(python3 -c "import json; print(json.dumps({'cmd':'bash','args':['-c',$(python3 -c "import json; print(json.dumps('$cmd'))")]}))") ")
+ echo "$resp"
+}
+
+run_cmd_raw() {
+ # Passes a raw JSON body — use for complex commands with quotes
+ local sid="$1" json_body="$2" tout="${3:-30}"
+ curl -s --max-time "$tout" -X POST "${EXEC_URL}/sandboxes/${sid}/commands" \
+ -H "${AUTH_HEADER}" -H "Content-Type: application/json" \
+ -d "$json_body"
+}
+
+# ─────────────────────────────────────────────────────────
+header "HEAVY BENCHMARK: Processes + 2GB Data"
+echo -e "Server: ${SERVER}"
+echo -e "API Key: ${API_KEY:0:12}..."
+echo ""
+
+# ─────────────────────────────────────────────────────────
+header "PHASE 1: Create sandbox + full setup"
+info "Creating sandbox (python template, 4GB RAM, 4 CPUs)..."
+
+T_TOTAL_START=$(python3 -c 'import time; print(time.time())')
+T_START=$T_TOTAL_START
+
+RESP=$(api POST /api/sandboxes -d '{
+ "templateID": "python",
+ "timeout": 1800,
+ "memoryMB": 4096,
+ "cpuCount": 4
+}')
+BODY=$(parse_response "$RESP") || exit 1
+
+T_END=$(python3 -c 'import time; print(time.time())')
+CREATE_MS=$(python3 -c "print(f'{($T_END - $T_START) * 1000:.0f}')")
+
+SANDBOX_ID=$(echo "$BODY" | python3 -c "import sys,json; print(json.load(sys.stdin)['sandboxID'])")
+CONNECT_URL=$(echo "$BODY" | python3 -c "import sys,json; print(json.load(sys.stdin).get('connectURL',''))" 2>/dev/null || echo "")
+TOKEN=$(echo "$BODY" | python3 -c "import sys,json; print(json.load(sys.stdin).get('token',''))" 2>/dev/null || echo "")
+WORKER_ID=$(echo "$BODY" | python3 -c "import sys,json; print(json.load(sys.stdin).get('workerID',''))" 2>/dev/null || echo "")
+
+if [[ -n "$CONNECT_URL" && -n "$TOKEN" ]]; then
+ EXEC_URL="${CONNECT_URL}"
+ AUTH_HEADER="Authorization: Bearer ${TOKEN}"
+else
+ EXEC_URL="${SERVER}"
+ AUTH_HEADER="X-API-Key: ${API_KEY}"
+fi
+
+ok "Sandbox created: ${SANDBOX_ID} on ${WORKER_ID} (${CREATE_MS}ms)"
+
+# --- Install packages ---
+info "Installing packages (python packages, curl, etc.)..."
+T_START=$(python3 -c 'import time; print(time.time())')
+
+run_cmd_raw "$SANDBOX_ID" '{"cmd":"bash","args":["-c","apt-get update -qq && apt-get install -y -qq curl wget redis-tools net-tools > /dev/null 2>&1 && echo done"]}' 120 > /dev/null
+
+T_END=$(python3 -c 'import time; print(time.time())')
+APT_MS=$(python3 -c "print(f'{($T_END - $T_START) * 1000:.0f}')")
+ok "APT packages installed (${APT_MS}ms)"
+
+info "Installing Python packages..."
+T_START=$(python3 -c 'import time; print(time.time())')
+
+run_cmd_raw "$SANDBOX_ID" '{"cmd":"bash","args":["-c","pip install --quiet flask requests numpy pandas > /dev/null 2>&1 && echo done"]}' 120 > /dev/null
+
+T_END=$(python3 -c 'import time; print(time.time())')
+PIP_MS=$(python3 -c "print(f'{($T_END - $T_START) * 1000:.0f}')")
+ok "Python packages installed (${PIP_MS}ms)"
+
+# --- Start background processes ---
+info "Starting background processes..."
+T_START=$(python3 -c 'import time; print(time.time())')
+
+# Start a Flask web server
+run_cmd_raw "$SANDBOX_ID" '{"cmd":"bash","args":["-c","cat > /tmp/app.py << PYEOF\nfrom flask import Flask\nimport os, time\napp = Flask(__name__)\nstart_time = time.time()\[email protected](\"/\")\ndef index():\n return {\"uptime\": time.time() - start_time, \"pid\": os.getpid()}\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=5000)\nPYEOF\nnohup python3 /tmp/app.py > /tmp/flask.log 2>&1 &\necho started"]}' 10 > /dev/null
+
+# Start a CPU worker process
+run_cmd_raw "$SANDBOX_ID" '{"cmd":"bash","args":["-c","nohup python3 -c \"import time, hashlib; [hashlib.sha256(str(i).encode()).hexdigest() for i in iter(int, 1)]\" > /dev/null 2>&1 &\necho started"]}' 10 > /dev/null
+
+# Start a periodic logger
+run_cmd_raw "$SANDBOX_ID" '{"cmd":"bash","args":["-c","nohup bash -c \"while true; do echo $(date) heartbeat >> /tmp/heartbeat.log; sleep 1; done\" > /dev/null 2>&1 &\necho started"]}' 10 > /dev/null
+
+T_END=$(python3 -c 'import time; print(time.time())')
+PROC_MS=$(python3 -c "print(f'{($T_END - $T_START) * 1000:.0f}')")
+ok "3 background processes started (${PROC_MS}ms)"
+
+# --- Write 2GB of data ---
+info "Writing 2GB of user data (this will take a minute)..."
+T_START=$(python3 -c 'import time; print(time.time())')
+
+# Write 2GB in 256MB chunks to avoid command timeouts
+for i in $(seq 1 8); do
+ run_cmd_raw "$SANDBOX_ID" "{\"cmd\":\"bash\",\"args\":[\"-c\",\"dd if=/dev/urandom of=/tmp/data_${i}.bin bs=1M count=256 2>/dev/null && echo chunk_${i}_done\"]}" 120 > /dev/null
+ echo -ne " Writing chunk ${i}/8 ($(( i * 256 )) MB)...\r"
+done
+echo ""
+
+T_END=$(python3 -c 'import time; print(time.time())')
+DATA_MS=$(python3 -c "print(f'{($T_END - $T_START) * 1000:.0f}')")
+DATA_SECS=$(python3 -c "print(f'{($T_END - $T_START):.1f}')")
+ok "2GB data written (${DATA_SECS}s)"
+
+# Verify data + processes
+info "Verifying sandbox state..."
+VERIFY=$(run_cmd_raw "$SANDBOX_ID" '{"cmd":"bash","args":["-c","echo marker=benchmark-heavy-12345 && echo data_size=$(du -sh /tmp/data_*.bin 2>/dev/null | tail -1 | cut -f1) && echo total_files=$(ls /tmp/data_*.bin 2>/dev/null | wc -l) && echo procs=$(ps aux | grep -v grep | grep -c python) && echo flask_up=$(curl -s http://localhost:5000/ | head -c 50)"]}' 10)
+echo "$VERIFY" | python3 -c "
+import sys, json
+d = json.load(sys.stdin)
+for line in d.get('stdout','').strip().split('\n'):
+ print(f' {line}')
+" 2>/dev/null || echo " (could not parse verify output)"
+
+T_TOTAL_END=$(python3 -c 'import time; print(time.time())')
+SETUP_TOTAL_MS=$(python3 -c "print(f'{($T_TOTAL_END - $T_TOTAL_START) * 1000:.0f}')")
+SETUP_TOTAL_SECS=$(python3 -c "print(f'{($T_TOTAL_END - $T_TOTAL_START):.1f}')")
+
+ok "Sandbox fully set up"
+timing "Total fresh setup: ${SETUP_TOTAL_SECS}s (${SETUP_TOTAL_MS}ms)"
+echo ""
+echo -e " Breakdown:"
+echo -e " Create container: ${CREATE_MS}ms"
+echo -e " APT install: ${APT_MS}ms"
+echo -e " pip install: ${PIP_MS}ms"
+echo -e " Start processes: ${PROC_MS}ms"
+echo -e " Write 2GB data: ${DATA_SECS}s"
+
+sleep 2
+
+# ─────────────────────────────────────────────────────────
+header "PHASE 2: Hibernate → Wake (local checkpoint)"
+info "Hibernating sandbox with 2GB data + 3 running processes..."
+
+T_START=$(python3 -c 'import time; print(time.time())')
+RESP=$(api POST "/api/sandboxes/${SANDBOX_ID}/hibernate")
+BODY=$(parse_response "$RESP") || { fail "Hibernate failed"; exit 1; }
+T_END=$(python3 -c 'import time; print(time.time())')
+HIB_MS=$(python3 -c "print(f'{($T_END - $T_START) * 1000:.0f}')")
+HIB_SECS=$(python3 -c "print(f'{($T_END - $T_START):.1f}')")
+
+CP_SIZE=$(echo "$BODY" | python3 -c "import sys,json; print(json.load(sys.stdin).get('sizeBytes', 0))" 2>/dev/null || echo "0")
+CP_SIZE_MB=$(python3 -c "print(f'{int($CP_SIZE) / 1024 / 1024:.1f}')")
+ok "Hibernated"
+timing "Hibernate: ${HIB_SECS}s (checkpoint: ${CP_SIZE_MB} MB)"
+
+sleep 2
+
+info "Waking from local checkpoint..."
+T_START=$(python3 -c 'import time; print(time.time())')
+RESP=$(api POST "/api/sandboxes/${SANDBOX_ID}/wake" -d '{"timeout": 1800}')
+BODY=$(parse_response "$RESP") || { fail "Wake failed"; exit 1; }
+T_END=$(python3 -c 'import time; print(time.time())')
+LOCAL_WAKE_MS=$(python3 -c "print(f'{($T_END - $T_START) * 1000:.0f}')")
+LOCAL_WAKE_SECS=$(python3 -c "print(f'{($T_END - $T_START):.1f}')")
+
+CONNECT_URL2=$(echo "$BODY" | python3 -c "import sys,json; print(json.load(sys.stdin).get('connectURL',''))" 2>/dev/null || echo "$CONNECT_URL")
+TOKEN2=$(echo "$BODY" | python3 -c "import sys,json; print(json.load(sys.stdin).get('token',''))" 2>/dev/null || echo "$TOKEN")
+if [[ -n "$CONNECT_URL2" && -n "$TOKEN2" ]]; then
+ EXEC_URL="${CONNECT_URL2}"
+ AUTH_HEADER="Authorization: Bearer ${TOKEN2}"
+fi
+
+ok "Woke from local checkpoint"
+timing "Local wake: ${LOCAL_WAKE_SECS}s (${LOCAL_WAKE_MS}ms)"
+
+# Verify everything survived
+info "Verifying state after local wake..."
+VERIFY=$(run_cmd_raw "$SANDBOX_ID" '{"cmd":"bash","args":["-c","echo data_size=$(du -sh /tmp/data_*.bin 2>/dev/null | tail -1 | cut -f1) && echo total_files=$(ls /tmp/data_*.bin 2>/dev/null | wc -l) && echo procs=$(ps aux | grep -v grep | grep -c python) && echo flask=$(curl -s http://localhost:5000/ | head -c 80) && echo heartbeat_lines=$(wc -l < /tmp/heartbeat.log 2>/dev/null || echo 0)"]}' 10)
+echo "$VERIFY" | python3 -c "
+import sys, json
+d = json.load(sys.stdin)
+for line in d.get('stdout','').strip().split('\n'):
+ print(f' {line}')
+" 2>/dev/null || echo " (could not parse)"
+
+sleep 2
+
+# ─────────────────────────────────────────────────────────
+header "PHASE 3: Hibernate → Purge Local → Wake (S3 migration)"
+info "Hibernating again..."
+
+T_START=$(python3 -c 'import time; print(time.time())')
+RESP=$(api POST "/api/sandboxes/${SANDBOX_ID}/hibernate")
+BODY=$(parse_response "$RESP") || { fail "Hibernate failed"; exit 1; }
+T_END=$(python3 -c 'import time; print(time.time())')
+HIB2_MS=$(python3 -c "print(f'{($T_END - $T_START) * 1000:.0f}')")
+HIB2_SECS=$(python3 -c "print(f'{($T_END - $T_START):.1f}')")
+
+CP2_SIZE=$(echo "$BODY" | python3 -c "import sys,json; print(json.load(sys.stdin).get('sizeBytes', 0))" 2>/dev/null || echo "0")
+CP2_SIZE_MB=$(python3 -c "print(f'{int($CP2_SIZE) / 1024 / 1024:.1f}')")
+ok "Hibernated (checkpoint: ${CP2_SIZE_MB} MB)"
+timing "Hibernate: ${HIB2_SECS}s"
+
+info "Purging local checkpoint to force S3 pull..."
+# Purge on both workers
+ssh -i ~/.ssh/opensandbox-digger.pem -o StrictHostKeyChecking=no -o ConnectTimeout=5 [email protected] \
+ "sudo find /data/sandboxes/checkpoints -name '*${SANDBOX_ID}*' -exec rm -rf {} + 2>/dev/null; echo purged" 2>/dev/null || true
+ssh -i ~/.ssh/opensandbox-digger.pem -o StrictHostKeyChecking=no -o ConnectTimeout=5 [email protected] \
+ "sudo find /data/sandboxes/checkpoints -name '*${SANDBOX_ID}*' -exec rm -rf {} + 2>/dev/null; echo purged" 2>/dev/null || true
+ok "Local checkpoint purged"
+
+sleep 1
+
+info "Waking from S3 (must download checkpoint)..."
+T_START=$(python3 -c 'import time; print(time.time())')
+RESP=$(api POST "/api/sandboxes/${SANDBOX_ID}/wake" -d '{"timeout": 1800}')
+BODY=$(parse_response "$RESP") || { fail "S3 wake failed"; exit 1; }
+T_END=$(python3 -c 'import time; print(time.time())')
+S3_WAKE_MS=$(python3 -c "print(f'{($T_END - $T_START) * 1000:.0f}')")
+S3_WAKE_SECS=$(python3 -c "print(f'{($T_END - $T_START):.1f}')")
+
+CONNECT_URL3=$(echo "$BODY" | python3 -c "import sys,json; print(json.load(sys.stdin).get('connectURL',''))" 2>/dev/null || echo "$CONNECT_URL")
+TOKEN3=$(echo "$BODY" | python3 -c "import sys,json; print(json.load(sys.stdin).get('token',''))" 2>/dev/null || echo "$TOKEN")
+if [[ -n "$CONNECT_URL3" && -n "$TOKEN3" ]]; then
+ EXEC_URL="${CONNECT_URL3}"
+ AUTH_HEADER="Authorization: Bearer ${TOKEN3}"
+fi
+
+ok "Woke from S3"
+timing "S3 wake: ${S3_WAKE_SECS}s (${S3_WAKE_MS}ms)"
+
+info "Verifying state after S3 restore..."
+VERIFY=$(run_cmd_raw "$SANDBOX_ID" '{"cmd":"bash","args":["-c","echo data_size=$(du -sh /tmp/data_*.bin 2>/dev/null | tail -1 | cut -f1) && echo total_files=$(ls /tmp/data_*.bin 2>/dev/null | wc -l) && echo procs=$(ps aux | grep -v grep | grep -c python) && echo flask=$(curl -s http://localhost:5000/ | head -c 80)"]}' 10)
+echo "$VERIFY" | python3 -c "
+import sys, json
+d = json.load(sys.stdin)
+for line in d.get('stdout','').strip().split('\n'):
+ print(f' {line}')
+" 2>/dev/null || echo " (could not parse)"
+
+# ─────────────────────────────────────────────────────────
+# Cleanup
+info "Cleaning up — destroying sandbox..."
+api DELETE "/api/sandboxes/${SANDBOX_ID}" > /dev/null 2>&1 || true
+
+# ─────────────────────────────────────────────────────────
+header "RESULTS SUMMARY"
+echo ""
+echo -e " ${BOLD}Sandbox config:${NC} python template, 4 CPUs, 4GB RAM"
+echo -e " ${BOLD}Payload:${NC} 2GB random data, Flask server, CPU worker, heartbeat logger"
+echo -e " ${BOLD}Checkpoint:${NC} ${CP_SIZE_MB} MB (1st), ${CP2_SIZE_MB} MB (2nd)"
+echo ""
+echo -e " ┌───────────────────────────────────┬────────────┐"
+echo -e " │ Operation │ Time │"
+echo -e " ├───────────────────────────────────┼────────────┤"
+echo -e " │ ${BOLD}Fresh create + full setup${NC} │ ${BOLD}${RED}${SETUP_TOTAL_SECS}s${NC} │"
+echo -e " │ └ Container create │ ${CREATE_MS}ms │"
+echo -e " │ └ APT packages │ ${APT_MS}ms │"
+echo -e " │ └ pip packages │ ${PIP_MS}ms │"
+echo -e " │ └ Start processes │ ${PROC_MS}ms │"
+echo -e " │ └ Write 2GB data │ ${DATA_SECS}s │"
+echo -e " ├───────────────────────────────────┼────────────┤"
+echo -e " │ Hibernate (1st) │ ${HIB_SECS}s │"
+echo -e " │ ${BOLD}${GREEN}Wake (local checkpoint)${NC} │ ${BOLD}${GREEN}${LOCAL_WAKE_SECS}s${NC} │"
+echo -e " ├───────────────────────────────────┼────────────┤"
+echo -e " │ Hibernate (2nd) │ ${HIB2_SECS}s │"
+echo -e " │ ${BOLD}${GREEN}Wake (S3 → restore)${NC} │ ${BOLD}${GREEN}${S3_WAKE_SECS}s${NC} │"
+echo -e " └───────────────────────────────────┴────────────┘"
+echo ""
+echo -e " ${BOLD}${CYAN}Speedup (local wake vs fresh):${NC} $(python3 -c "print(f'{int($SETUP_TOTAL_MS) / max(int($LOCAL_WAKE_MS), 1):.0f}')") x faster"
+echo -e " ${BOLD}${CYAN}Speedup (S3 wake vs fresh):${NC} $(python3 -c "print(f'{int($SETUP_TOTAL_MS) / max(int($S3_WAKE_MS), 1):.0f}')") x faster"
+echo ""
diff --git a/scripts/bench-launch.sh b/scripts/bench-launch.sh
new file mode 100755
index 00000000..f74db1fa
--- /dev/null
+++ b/scripts/bench-launch.sh
@@ -0,0 +1,252 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+# Benchmark sandbox launch times:
+# 1. Fresh launch (cold start — no checkpoint)
+# 2. Wake from local checkpoint (hibernated, data still on disk)
+# 3. Wake from S3 checkpoint (simulate migration — purge local, pull from S3)
+#
+# Usage: ./scripts/bench-launch.sh <server-url> <api-key>
+# Example: ./scripts/bench-launch.sh http://3.135.246.117:8080 osb_600b1a...
+
+SERVER="${1:?Usage: $0 <server-url> <api-key>}"
+API_KEY="${2:?Usage: $0 <server-url> <api-key>}"
+
+# Colors
+RED='\033[0;31m'
+GREEN='\033[0;32m'
+YELLOW='\033[1;33m'
+CYAN='\033[0;36m'
+BOLD='\033[1m'
+NC='\033[0m'
+
+header() { echo -e "\n${BOLD}${CYAN}═══════════════════════════════════════════════════${NC}"; echo -e "${BOLD}${CYAN} $1${NC}"; echo -e "${BOLD}${CYAN}═══════════════════════════════════════════════════${NC}"; }
+info() { echo -e "${YELLOW}→${NC} $1"; }
+ok() { echo -e "${GREEN}✓${NC} $1"; }
+fail() { echo -e "${RED}✗${NC} $1"; }
+timing() { echo -e "${BOLD}${GREEN} ⏱ $1${NC}"; }
+
+api() {
+ local method="$1" path="$2"
+ shift 2
+ curl -s -w "\n%{http_code}" -X "$method" "${SERVER}${path}" \
+ -H "X-API-Key: ${API_KEY}" \
+ -H "Content-Type: application/json" "$@"
+}
+
+parse_response() {
+ local body http_code
+ body=$(echo "$1" | sed '$d')
+ http_code=$(echo "$1" | tail -1)
+ echo "$body"
+ if [[ "$http_code" -ge 400 ]]; then
+ fail "HTTP $http_code: $body"
+ return 1
+ fi
+}
+
+# ─────────────────────────────────────────────────────
+header "BENCHMARK: Sandbox Launch Times"
+echo -e "Server: ${SERVER}"
+echo -e "API Key: ${API_KEY:0:12}..."
+echo ""
+
+# ─────────────────────────────────────────────────────
+header "TEST 1: Fresh Launch (cold start)"
+info "Creating sandbox from base template..."
+
+T_START=$(python3 -c 'import time; print(time.time())')
+
+RESP=$(api POST /api/sandboxes -d '{
+ "templateID": "base",
+ "timeout": 600,
+ "memoryMB": 512,
+ "cpuCount": 2
+}')
+BODY=$(parse_response "$RESP") || exit 1
+
+T_END=$(python3 -c 'import time; print(time.time())')
+FRESH_MS=$(python3 -c "print(f'{($T_END - $T_START) * 1000:.0f}')")
+
+SANDBOX_ID=$(echo "$BODY" | python3 -c "import sys,json; print(json.load(sys.stdin)['sandboxID'])")
+CONNECT_URL=$(echo "$BODY" | python3 -c "import sys,json; print(json.load(sys.stdin).get('connectURL',''))" 2>/dev/null || echo "")
+TOKEN=$(echo "$BODY" | python3 -c "import sys,json; print(json.load(sys.stdin).get('token',''))" 2>/dev/null || echo "")
+WORKER_ID=$(echo "$BODY" | python3 -c "import sys,json; print(json.load(sys.stdin).get('workerID',''))" 2>/dev/null || echo "")
+
+ok "Sandbox created: ${SANDBOX_ID}"
+ok "Worker: ${WORKER_ID}"
+timing "Fresh launch: ${FRESH_MS}ms"
+
+# Write some state so we can verify persistence after wake
+info "Writing state into sandbox..."
+if [[ -n "$CONNECT_URL" && -n "$TOKEN" ]]; then
+ EXEC_URL="${CONNECT_URL}"
+ AUTH_HEADER="Authorization: Bearer ${TOKEN}"
+else
+ EXEC_URL="${SERVER}"
+ AUTH_HEADER="X-API-Key: ${API_KEY}"
+fi
+
+curl -s -X POST "${EXEC_URL}/sandboxes/${SANDBOX_ID}/commands" \
+ -H "${AUTH_HEADER}" \
+ -H "Content-Type: application/json" \
+ -d '{"cmd":"bash","args":["-c","echo benchmark-marker-12345 > /tmp/bench.txt && date +%s > /tmp/bench-time.txt"]}' > /dev/null 2>&1
+
+# Verify state
+CMD_RESP=$(curl -s -X POST "${EXEC_URL}/sandboxes/${SANDBOX_ID}/commands" \
+ -H "${AUTH_HEADER}" \
+ -H "Content-Type: application/json" \
+ -d '{"cmd":"bash","args":["-c","cat /tmp/bench.txt"]}')
+MARKER=$(echo "$CMD_RESP" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d.get('stdout','').strip())" 2>/dev/null || echo "")
+if [[ "$MARKER" == "benchmark-marker-12345" ]]; then
+ ok "State written and verified"
+else
+ fail "Could not verify state (got: $MARKER)"
+fi
+
+sleep 1
+
+# ─────────────────────────────────────────────────────
+header "TEST 2: Hibernate → Wake (local checkpoint)"
+info "Hibernating sandbox ${SANDBOX_ID}..."
+
+T_START=$(python3 -c 'import time; print(time.time())')
+RESP=$(api POST "/api/sandboxes/${SANDBOX_ID}/hibernate")
+BODY=$(parse_response "$RESP") || { fail "Hibernate failed"; exit 1; }
+T_END=$(python3 -c 'import time; print(time.time())')
+HIB_MS=$(python3 -c "print(f'{($T_END - $T_START) * 1000:.0f}')")
+
+CP_SIZE=$(echo "$BODY" | python3 -c "import sys,json; print(json.load(sys.stdin).get('sizeBytes', 0))" 2>/dev/null || echo "0")
+CP_SIZE_MB=$(python3 -c "print(f'{$CP_SIZE / 1024 / 1024:.1f}')")
+ok "Hibernated (checkpoint: ${CP_SIZE_MB} MB)"
+timing "Hibernate: ${HIB_MS}ms"
+
+sleep 1
+
+info "Waking sandbox (local checkpoint on same worker)..."
+T_START=$(python3 -c 'import time; print(time.time())')
+RESP=$(api POST "/api/sandboxes/${SANDBOX_ID}/wake" -d '{"timeout": 600}')
+BODY=$(parse_response "$RESP") || { fail "Wake failed"; exit 1; }
+T_END=$(python3 -c 'import time; print(time.time())')
+LOCAL_WAKE_MS=$(python3 -c "print(f'{($T_END - $T_START) * 1000:.0f}')")
+
+# Update connect info in case worker changed
+CONNECT_URL2=$(echo "$BODY" | python3 -c "import sys,json; print(json.load(sys.stdin).get('connectURL',''))" 2>/dev/null || echo "$CONNECT_URL")
+TOKEN2=$(echo "$BODY" | python3 -c "import sys,json; print(json.load(sys.stdin).get('token',''))" 2>/dev/null || echo "$TOKEN")
+if [[ -n "$CONNECT_URL2" && -n "$TOKEN2" ]]; then
+ EXEC_URL="${CONNECT_URL2}"
+ AUTH_HEADER="Authorization: Bearer ${TOKEN2}"
+fi
+
+ok "Woke from local checkpoint"
+timing "Local wake: ${LOCAL_WAKE_MS}ms"
+
+# Verify state persisted
+info "Verifying state persistence..."
+CMD_RESP=$(curl -s -X POST "${EXEC_URL}/sandboxes/${SANDBOX_ID}/commands" \
+ -H "${AUTH_HEADER}" \
+ -H "Content-Type: application/json" \
+ -d '{"cmd":"bash","args":["-c","cat /tmp/bench.txt"]}')
+MARKER=$(echo "$CMD_RESP" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d.get('stdout','').strip())" 2>/dev/null || echo "")
+if [[ "$MARKER" == "benchmark-marker-12345" ]]; then
+ ok "State verified after local wake ✓"
+else
+ fail "State lost after wake (got: $MARKER)"
+fi
+
+sleep 1
+
+# ─────────────────────────────────────────────────────
+header "TEST 3: Hibernate → Purge Local → Wake (S3 migration)"
+info "Hibernating sandbox again..."
+
+T_START=$(python3 -c 'import time; print(time.time())')
+RESP=$(api POST "/api/sandboxes/${SANDBOX_ID}/hibernate")
+BODY=$(parse_response "$RESP") || { fail "Hibernate failed"; exit 1; }
+T_END=$(python3 -c 'import time; print(time.time())')
+HIB2_MS=$(python3 -c "print(f'{($T_END - $T_START) * 1000:.0f}')")
+ok "Hibernated again"
+timing "Hibernate: ${HIB2_MS}ms"
+
+# Find which worker had this sandbox and purge the local checkpoint
+info "Purging local checkpoint to simulate S3 migration..."
+WAKE_WORKER=$(echo "$BODY" | python3 -c "import sys,json; print(json.load(sys.stdin).get('workerID',''))" 2>/dev/null || echo "$WORKER_ID")
+
+# We need to remove the local checkpoint files from the worker
+# The checkpoint lives under DATA_DIR/checkpoints/<sandboxID>/
+# We'll SSH to the worker and remove it
+
+# Figure out which worker IP to SSH to
+if [[ "$WAKE_WORKER" == *"099088f8"* ]]; then
+ WORKER_IP="18.117.11.151"
+elif [[ "$WAKE_WORKER" == *"0e250197"* ]]; then
+ WORKER_IP="18.219.23.64"
+else
+ # Try both
+ WORKER_IP="18.117.11.151"
+fi
+
+# Remove local checkpoint data
+ssh -i ~/.ssh/opensandbox-digger.pem -o StrictHostKeyChecking=no -o ConnectTimeout=5 "ubuntu@${WORKER_IP}" \
+ "sudo find /data/sandboxes/checkpoints -name '*${SANDBOX_ID}*' -exec rm -rf {} + 2>/dev/null; echo 'purged'" 2>/dev/null || info "Could not purge on ${WORKER_IP}, trying other worker..."
+
+# Also try the other worker just in case
+if [[ "$WORKER_IP" == "18.117.11.151" ]]; then
+ ssh -i ~/.ssh/opensandbox-digger.pem -o StrictHostKeyChecking=no -o ConnectTimeout=5 [email protected] \
+ "sudo find /data/sandboxes/checkpoints -name '*${SANDBOX_ID}*' -exec rm -rf {} + 2>/dev/null; echo 'purged'" 2>/dev/null || true
+else
+ ssh -i ~/.ssh/opensandbox-digger.pem -o StrictHostKeyChecking=no -o ConnectTimeout=5 [email protected] \
+ "sudo find /data/sandboxes/checkpoints -name '*${SANDBOX_ID}*' -exec rm -rf {} + 2>/dev/null; echo 'purged'" 2>/dev/null || true
+fi
+
+ok "Local checkpoint purged — will restore from S3"
+
+sleep 1
+
+info "Waking sandbox (must pull from S3)..."
+T_START=$(python3 -c 'import time; print(time.time())')
+RESP=$(api POST "/api/sandboxes/${SANDBOX_ID}/wake" -d '{"timeout": 600}')
+BODY=$(parse_response "$RESP") || { fail "S3 wake failed"; exit 1; }
+T_END=$(python3 -c 'import time; print(time.time())')
+S3_WAKE_MS=$(python3 -c "print(f'{($T_END - $T_START) * 1000:.0f}')")
+
+CONNECT_URL3=$(echo "$BODY" | python3 -c "import sys,json; print(json.load(sys.stdin).get('connectURL',''))" 2>/dev/null || echo "$CONNECT_URL")
+TOKEN3=$(echo "$BODY" | python3 -c "import sys,json; print(json.load(sys.stdin).get('token',''))" 2>/dev/null || echo "$TOKEN")
+if [[ -n "$CONNECT_URL3" && -n "$TOKEN3" ]]; then
+ EXEC_URL="${CONNECT_URL3}"
+ AUTH_HEADER="Authorization: Bearer ${TOKEN3}"
+fi
+
+ok "Woke from S3 checkpoint"
+timing "S3 wake: ${S3_WAKE_MS}ms"
+
+# Verify state persisted through S3 round-trip
+info "Verifying state persistence after S3 restore..."
+CMD_RESP=$(curl -s -X POST "${EXEC_URL}/sandboxes/${SANDBOX_ID}/commands" \
+ -H "${AUTH_HEADER}" \
+ -H "Content-Type: application/json" \
+ -d '{"cmd":"bash","args":["-c","cat /tmp/bench.txt"]}')
+MARKER=$(echo "$CMD_RESP" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d.get('stdout','').strip())" 2>/dev/null || echo "")
+if [[ "$MARKER" == "benchmark-marker-12345" ]]; then
+ ok "State verified after S3 wake ✓"
+else
+ fail "State lost after S3 wake (got: $MARKER)"
+fi
+
+# ─────────────────────────────────────────────────────
+# Cleanup
+info "Cleaning up — destroying sandbox..."
+api DELETE "/api/sandboxes/${SANDBOX_ID}" > /dev/null 2>&1 || true
+
+# ─────────────────────────────────────────────────────
+header "RESULTS"
+echo ""
+echo -e " ${BOLD}Fresh launch (cold start):${NC} ${BOLD}${GREEN}${FRESH_MS}ms${NC}"
+echo -e " ${BOLD}Hibernate:${NC} ${HIB_MS}ms (checkpoint: ${CP_SIZE_MB} MB)"
+echo -e " ${BOLD}Wake (local checkpoint):${NC} ${BOLD}${GREEN}${LOCAL_WAKE_MS}ms${NC}"
+echo -e " ${BOLD}Hibernate (2nd):${NC} ${HIB2_MS}ms"
+echo -e " ${BOLD}Wake (S3 → restore):${NC} ${BOLD}${GREEN}${S3_WAKE_MS}ms${NC}"
+echo ""
+echo -e " ${CYAN}Speedup local vs fresh:${NC} $(python3 -c "print(f'{$FRESH_MS / max($LOCAL_WAKE_MS, 1):.1f}')") x"
+echo -e " ${CYAN}Speedup S3 vs fresh:${NC} $(python3 -c "print(f'{$FRESH_MS / max($S3_WAKE_MS, 1):.1f}')") x"
+echo ""