An open-source, faster Devin alternative
TypeScript
abstract Azure-isms behind WorkerSpec, add real AWS impl
Brian Reardon02b3e653014a
diff --git a/cmd/server/main.go b/cmd/server/main.goindex cd68d837..9ad6e293 100644--- a/cmd/server/main.go+++ b/cmd/server/main.go@@ -2,7 +2,6 @@ package mainimport ("context"- "encoding/base64""fmt""log""os"@@ -193,86 +192,77 @@ func main() {// Initialize compute pool + autoscaler (server mode)if cfg.Mode == "server" && redisRegistry != nil {- var pool compute.Pool- var poolName string+ // Build the WorkerSpec: cloud-neutral config that the CP supplies to+ // whichever pool is selected. The pool combines this with cloud-specific+ // cloud-init to launch new workers.+ //+ // Workers need to reach Postgres/Redis on the CP's private IP,+ // not localhost. Replace localhost with the CP's IP if known.+ cpIP := os.Getenv("OPENSANDBOX_CONTROLPLANE_IP")+ workerDBURL := cfg.DatabaseURL+ workerRedisURL := cfg.RedisURL+ if cpIP != "" {+ workerDBURL = strings.ReplaceAll(workerDBURL, "localhost", cpIP)+ workerDBURL = strings.ReplaceAll(workerDBURL, "127.0.0.1", cpIP)+ workerRedisURL = strings.ReplaceAll(workerRedisURL, "localhost", cpIP)+ workerRedisURL = strings.ReplaceAll(workerRedisURL, "127.0.0.1", cpIP)+ }+ spec := compute.WorkerSpec{+ CellID: cfg.CellID,+ Region: cfg.Region,+ DatabaseURL: workerDBURL,+ RedisURL: workerRedisURL,+ JWTSecret: cfg.JWTSecret,+ SessionJWTSecret: cfg.SessionJWTSecret,+ CFEventEndpoint: cfg.CFEventEndpoint,+ CFEventSecret: cfg.CFEventSecret,+ CFAdminSecret: cfg.CFAdminSecret,+ MaxCapacity: cfg.MaxCapacity,+ SandboxDomain: cfg.SandboxDomain,+ DefaultMemoryMB: cfg.DefaultSandboxMemoryMB,+ DefaultCPUs: cfg.DefaultSandboxCPUs,+ DefaultDiskMB: cfg.DefaultSandboxDiskMB,+ S3Bucket: cfg.S3Bucket,+ S3Region: cfg.S3Region,+ S3Endpoint: cfg.S3Endpoint,+ S3AccessKeyID: cfg.S3AccessKeyID,+ S3SecretAccessKey: cfg.S3SecretAccessKey,+ S3ForcePathStyle: cfg.S3ForcePathStyle,+ SegmentWriteKey: cfg.SegmentWriteKey,+ SecretsRef: cfg.SecretsARN,+ }- if cfg.AzureSubscriptionID != "" && (cfg.AzureImageID != "" || cfg.AzureKeyVaultName != "") {- // Build worker env template — new VMs get this via cloud-init.- // GRPC_ADVERTISE, HTTP_ADDR, and WORKER_ID are patched by cloud-init- // with the VM's actual private IP and hostname.- // Workers need to reach Postgres/Redis on the control plane's private IP,- // not localhost. Replace localhost with the control plane's IP.- cpIP := os.Getenv("OPENSANDBOX_CONTROLPLANE_IP")- workerDBURL := cfg.DatabaseURL- workerRedisURL := cfg.RedisURL- if cpIP != "" {- workerDBURL = strings.ReplaceAll(workerDBURL, "localhost", cpIP)- workerDBURL = strings.ReplaceAll(workerDBURL, "127.0.0.1", cpIP)- workerRedisURL = strings.ReplaceAll(workerRedisURL, "localhost", cpIP)- workerRedisURL = strings.ReplaceAll(workerRedisURL, "127.0.0.1", cpIP)+ // Provider selection. Explicit cfg.ComputeProvider wins; otherwise we+ // autodetect from existing fields for backwards compatibility.+ provider := cfg.ComputeProvider+ if provider == "" {+ switch {+ case cfg.AzureSubscriptionID != "" && (cfg.AzureImageID != "" || cfg.AzureKeyVaultName != ""):+ provider = "azure"+ case cfg.EC2AMI != "" || cfg.EC2SSMParameterName != "":+ provider = "aws"}+ }- workerEnv := fmt.Sprintf(- "OPENSANDBOX_MODE=worker\n"+- "OPENSANDBOX_VM_BACKEND=qemu\n"+- "OPENSANDBOX_QEMU_BIN=qemu-system-x86_64\n"+- "OPENSANDBOX_DATA_DIR=/data/sandboxes\n"+- "OPENSANDBOX_KERNEL_PATH=/opt/opensandbox/vmlinux\n"+- "OPENSANDBOX_IMAGES_DIR=/data/firecracker/images\n"+- "OPENSANDBOX_GRPC_ADVERTISE=PLACEHOLDER:9090\n"+- "OPENSANDBOX_HTTP_ADDR=http://PLACEHOLDER:8081\n"+- "OPENSANDBOX_JWT_SECRET=%s\n"+- "OPENSANDBOX_WORKER_ID=PLACEHOLDER\n"+- "OPENSANDBOX_REGION=%s\n"+- "OPENSANDBOX_MAX_CAPACITY=%d\n"+- "OPENSANDBOX_PORT=8081\n"+- "OPENSANDBOX_DEFAULT_SANDBOX_MEMORY_MB=%d\n"+- "OPENSANDBOX_DEFAULT_SANDBOX_CPUS=%d\n"+- "OPENSANDBOX_DATABASE_URL=%s\n"+- "OPENSANDBOX_REDIS_URL=%s\n"+- "OPENSANDBOX_S3_BUCKET=%s\n"+- "OPENSANDBOX_S3_REGION=%s\n"+- "OPENSANDBOX_S3_ENDPOINT=%s\n"+- "OPENSANDBOX_S3_ACCESS_KEY_ID=%s\n"+- "OPENSANDBOX_S3_SECRET_ACCESS_KEY=%s\n"+- "OPENSANDBOX_S3_FORCE_PATH_STYLE=%v\n"+- "OPENSANDBOX_SANDBOX_DOMAIN=%s\n"+- "OPENSANDBOX_DEFAULT_SANDBOX_DISK_MB=%d\n"+- "SEGMENT_WRITE_KEY=%s\n",- cfg.JWTSecret,- cfg.Region,- cfg.MaxCapacity,- cfg.DefaultSandboxMemoryMB,- cfg.DefaultSandboxCPUs,- workerDBURL,- workerRedisURL,- cfg.S3Bucket,- cfg.S3Region,- cfg.S3Endpoint,- cfg.S3AccessKeyID,- cfg.S3SecretAccessKey,- cfg.S3ForcePathStyle,- cfg.SandboxDomain,- cfg.DefaultSandboxDiskMB,- cfg.SegmentWriteKey,- )- workerEnvB64 := base64.StdEncoding.EncodeToString([]byte(workerEnv))+ var pool compute.Pool+ var poolName string+ switch provider {+ case "azure":azPool, err := compute.NewAzurePool(compute.AzurePoolConfig{- SubscriptionID: cfg.AzureSubscriptionID,- ResourceGroup: cfg.AzureResourceGroup,- Region: cfg.Region,- VMSize: cfg.AzureVMSize,- ImageID: cfg.AzureImageID,- SubnetID: cfg.AzureSubnetID,- SSHPublicKey: cfg.AzureSSHPublicKey,- KeyVaultName: cfg.AzureKeyVaultName,- WorkerEnvBase64: workerEnvB64,+ SubscriptionID: cfg.AzureSubscriptionID,+ ResourceGroup: cfg.AzureResourceGroup,+ Region: cfg.Region,+ VMSize: cfg.AzureVMSize,+ ImageID: cfg.AzureImageID,+ SubnetID: cfg.AzureSubnetID,+ SSHPublicKey: cfg.AzureSSHPublicKey,+ KeyVaultName: cfg.AzureKeyVaultName,})if err != nil {log.Fatalf("opensandbox: failed to create Azure pool: %v", err)}- // If image not set statically but Key Vault is configured, fetch initial image+ azPool.SetWorkerSpec(spec)if cfg.AzureImageID == "" && cfg.AzureKeyVaultName != "" {imgID, version, kvErr := azPool.RefreshAMI(context.Background())if kvErr != nil {@@ -282,8 +272,8 @@ func main() {}pool = azPoolpoolName = fmt.Sprintf("Azure (size=%s, image=%s, keyvault=%s)", cfg.AzureVMSize, cfg.AzureImageID, cfg.AzureKeyVaultName)- } else if cfg.EC2AMI != "" || cfg.EC2SSMParameterName != "" {- // AWS EC2 compute pool (AMI from config or dynamically from SSM)++ case "aws":ec2Pool, err := compute.NewEC2Pool(compute.EC2PoolConfig{Region: cfg.S3Region,AccessKeyID: cfg.S3AccessKeyID,@@ -300,7 +290,7 @@ func main() {if err != nil {log.Fatalf("opensandbox: failed to create EC2 pool: %v", err)}- // If AMI not set statically but SSM is configured, fetch initial AMI from SSM+ ec2Pool.SetWorkerSpec(spec)if cfg.EC2AMI == "" && cfg.EC2SSMParameterName != "" {amiID, version, ssmErr := ec2Pool.RefreshAMI(context.Background())if ssmErr != nil {@@ -310,6 +300,11 @@ func main() {}pool = ec2PoolpoolName = fmt.Sprintf("EC2 (ami=%s, type=%s, ssm=%s)", cfg.EC2AMI, cfg.EC2InstanceType, cfg.EC2SSMParameterName)++ case "":+ log.Println("opensandbox: no compute provider configured (combined mode, no autoscaling)")+ default:+ log.Fatalf("opensandbox: unknown compute provider %q (expected azure|aws)", provider)}if pool != nil {diff --git a/deploy/aws/create-aws-dev3.sh b/deploy/aws/create-aws-dev3.shnew file mode 100755index 00000000..93aeb4c6--- /dev/null+++ b/deploy/aws/create-aws-dev3.sh@@ -0,0 +1,484 @@+#!/usr/bin/env bash+# create-aws-dev3.sh — Create a third dev OpenSandbox cell on AWS.+#+# This is the AWS counterpart to deploy/azure/create-azure-dev2.sh. It creates+# a fully isolated cell (VPC + subnet + IAM + EC2 instances + Secrets Manager)+# in AWS so we can validate cross-cloud cell behaviour against the existing+# Azure dev2 cell.+#+# Cost estimate (idle): ~$280/mo with default sizing. Use the `stop` command+# to deallocate when not testing.+#+# Prerequisites:+# - aws CLI installed and authenticated (aws sts get-caller-identity should work)+# - SSH key at ~/.ssh/opensandbox-digger.pem (same key as Azure dev for consistency)+#+# Usage:+# bash deploy/aws/create-aws-dev3.sh create # provision (run once)+# bash deploy/aws/create-aws-dev3.sh deploy # build + deploy binaries+# bash deploy/aws/create-aws-dev3.sh status # show IPs and status+# bash deploy/aws/create-aws-dev3.sh ssh-cp # SSH to control plane+# bash deploy/aws/create-aws-dev3.sh ssh-wk # SSH to worker+# bash deploy/aws/create-aws-dev3.sh start # start both instances (after stop)+# bash deploy/aws/create-aws-dev3.sh stop # stop instances to save cost+# bash deploy/aws/create-aws-dev3.sh destroy # tear down everything++set -euo pipefail++# ── Configuration ──+REGION="us-east-1"+NAME_PREFIX="osb-dev3"+VPC_CIDR="10.120.0.0/16"+SUBNET_CIDR="10.120.1.0/24"+SG_CP_NAME="${NAME_PREFIX}-cp"+SG_WK_NAME="${NAME_PREFIX}-wk"+CP_NAME="${NAME_PREFIX}-cp"+WK_NAME="${NAME_PREFIX}-worker-1"++# Instance sizing — NVMe-equipped, cost-optimised for a dev testbed+CP_TYPE="t3.medium" # 2 vCPU / 4GB / EBS only — postgres + redis + CP at dev scale+WK_TYPE="m6id.large" # 2 vCPU / 8GB / 118GB local NVMe — small worker for cross-region tests+WK_DATA_GB=128 # Additional persistent EBS volume mounted at /data++# Ubuntu 24.04 LTS amd64 (latest from Canonical's account 099720109477) — overridable+AMI_OWNER="099720109477"+AMI_FILTER="ubuntu/images/hvm-ssd-gp3/ubuntu-noble-24.04-amd64-server-*"++# CF-cutover specifics (cell ID encodes cloud + region for clarity)+CELL_ID="aws-us-east-1-cell-a"+CF_EVENT_ENDPOINT="https://opensandbox-events-ingest-dev.brian-124.workers.dev/ingest"++SSH_KEY="$HOME/.ssh/opensandbox-digger.pem"+SSH_PUB=$(ssh-keygen -y -f "$SSH_KEY" 2>/dev/null)+ADMIN_USER="ubuntu"+DOMAIN="dev3.opensandbox.ai"++STATE_FILE="$HOME/.opensandbox-aws-dev3-state"++SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"++log() { echo "[dev3-aws] $*"; }+err() { echo "[dev3-aws] ERROR: $*" >&2; }++save_state() { echo "$1=$2" >> "$STATE_FILE"; }+load_state() {+ if [ -f "$STATE_FILE" ]; then+ # shellcheck disable=SC1090+ source "$STATE_FILE"+ fi+}++# ── Create ──+cmd_create() {+ log "Creating dev3 stack in $REGION..."++ rm -f "$STATE_FILE"++ # Generate secrets up front+ API_KEY="osb_$(openssl rand -hex 32)"+ JWT_SECRET=$(openssl rand -hex 32)+ PG_PASSWORD=$(openssl rand -hex 16)+ SESSION_JWT_SECRET=$(openssl rand -hex 32)+ CF_EVENT_SECRET=$(openssl rand -hex 32)+ CF_ADMIN_SECRET=$(openssl rand -hex 32)+ save_state "API_KEY" "$API_KEY"+ save_state "JWT_SECRET" "$JWT_SECRET"+ save_state "PG_PASSWORD" "$PG_PASSWORD"+ save_state "SESSION_JWT_SECRET" "$SESSION_JWT_SECRET"+ save_state "CF_EVENT_SECRET" "$CF_EVENT_SECRET"+ save_state "CF_ADMIN_SECRET" "$CF_ADMIN_SECRET"++ # Resolve latest Ubuntu 24.04 AMI+ log "Finding latest Ubuntu 24.04 AMI..."+ AMI_ID=$(aws ec2 describe-images --region "$REGION" \+ --owners "$AMI_OWNER" \+ --filters "Name=name,Values=$AMI_FILTER" "Name=state,Values=available" \+ --query 'Images | sort_by(@, &CreationDate) | [-1].ImageId' \+ --output text)+ if [ -z "$AMI_ID" ] || [ "$AMI_ID" = "None" ]; then+ err "Could not resolve Ubuntu 24.04 AMI in $REGION"+ exit 1+ fi+ save_state "AMI_ID" "$AMI_ID"+ log "AMI: $AMI_ID"++ # ── VPC ──+ log "Creating VPC ($VPC_CIDR)..."+ VPC_ID=$(aws ec2 create-vpc --region "$REGION" \+ --cidr-block "$VPC_CIDR" \+ --tag-specifications "ResourceType=vpc,Tags=[{Key=Name,Value=${NAME_PREFIX}-vpc}]" \+ --query 'Vpc.VpcId' --output text)+ save_state "VPC_ID" "$VPC_ID"+ aws ec2 modify-vpc-attribute --region "$REGION" --vpc-id "$VPC_ID" --enable-dns-hostnames++ # Subnet+ SUBNET_ID=$(aws ec2 create-subnet --region "$REGION" \+ --vpc-id "$VPC_ID" --cidr-block "$SUBNET_CIDR" \+ --tag-specifications "ResourceType=subnet,Tags=[{Key=Name,Value=${NAME_PREFIX}-subnet}]" \+ --query 'Subnet.SubnetId' --output text)+ save_state "SUBNET_ID" "$SUBNET_ID"+ aws ec2 modify-subnet-attribute --region "$REGION" --subnet-id "$SUBNET_ID" --map-public-ip-on-launch++ # Internet gateway+ IGW_ID=$(aws ec2 create-internet-gateway --region "$REGION" \+ --tag-specifications "ResourceType=internet-gateway,Tags=[{Key=Name,Value=${NAME_PREFIX}-igw}]" \+ --query 'InternetGateway.InternetGatewayId' --output text)+ save_state "IGW_ID" "$IGW_ID"+ aws ec2 attach-internet-gateway --region "$REGION" --internet-gateway-id "$IGW_ID" --vpc-id "$VPC_ID"++ # Route table+ RTB_ID=$(aws ec2 create-route-table --region "$REGION" --vpc-id "$VPC_ID" \+ --tag-specifications "ResourceType=route-table,Tags=[{Key=Name,Value=${NAME_PREFIX}-rtb}]" \+ --query 'RouteTable.RouteTableId' --output text)+ save_state "RTB_ID" "$RTB_ID"+ aws ec2 create-route --region "$REGION" --route-table-id "$RTB_ID" --destination-cidr-block 0.0.0.0/0 --gateway-id "$IGW_ID" >/dev/null+ aws ec2 associate-route-table --region "$REGION" --route-table-id "$RTB_ID" --subnet-id "$SUBNET_ID" >/dev/null++ # ── Security groups ──+ log "Creating security groups..."+ SG_CP=$(aws ec2 create-security-group --region "$REGION" \+ --group-name "$SG_CP_NAME" --description "$NAME_PREFIX control plane" \+ --vpc-id "$VPC_ID" --query 'GroupId' --output text)+ save_state "SG_CP" "$SG_CP"+ for port in 22 8080 9090; do+ aws ec2 authorize-security-group-ingress --region "$REGION" \+ --group-id "$SG_CP" --protocol tcp --port "$port" --cidr 0.0.0.0/0 >/dev/null+ done+ # Postgres + Redis from within the VPC only+ for port in 5432 6379; do+ aws ec2 authorize-security-group-ingress --region "$REGION" \+ --group-id "$SG_CP" --protocol tcp --port "$port" --cidr "$VPC_CIDR" >/dev/null+ done++ SG_WK=$(aws ec2 create-security-group --region "$REGION" \+ --group-name "$SG_WK_NAME" --description "$NAME_PREFIX worker" \+ --vpc-id "$VPC_ID" --query 'GroupId' --output text)+ save_state "SG_WK" "$SG_WK"+ aws ec2 authorize-security-group-ingress --region "$REGION" \+ --group-id "$SG_WK" --protocol tcp --port 22 --cidr 0.0.0.0/0 >/dev/null+ for port in 9090 8081; do+ aws ec2 authorize-security-group-ingress --region "$REGION" \+ --group-id "$SG_WK" --protocol tcp --port "$port" --cidr "$VPC_CIDR" >/dev/null+ done++ # ── Key pair ──+ log "Creating key pair..."+ aws ec2 import-key-pair --region "$REGION" \+ --key-name "$NAME_PREFIX" \+ --public-key-material "fileb://<(echo "$SSH_PUB")" >/dev/null 2>&1 || \+ aws ec2 import-key-pair --region "$REGION" \+ --key-name "$NAME_PREFIX" \+ --public-key-material "$(echo -n "$SSH_PUB" | base64)" >/dev/null++ # ── S3 bucket for checkpoints ──+ BUCKET="osb-dev3-checkpoints-$(echo $RANDOM | md5 2>/dev/null | head -c 8 || echo $RANDOM | md5sum | head -c 8)"+ log "Creating S3 bucket $BUCKET..."+ aws s3api create-bucket --region "$REGION" --bucket "$BUCKET" \+ $([ "$REGION" != "us-east-1" ] && echo "--create-bucket-configuration LocationConstraint=$REGION") >/dev/null+ save_state "BUCKET" "$BUCKET"++ # ── Control Plane EC2 ──+ log "Launching control plane ($CP_TYPE)..."+ CP_USERDATA=$(cat <<'CPUD'+#!/bin/bash+set -euo pipefail+export DEBIAN_FRONTEND=noninteractive+apt-get update -qq+apt-get install -y -qq docker.io jq curl+systemctl enable --now docker+mkdir -p /etc/opensandbox /usr/local/bin /data/postgres+CPUD+)+ CP_ID=$(aws ec2 run-instances --region "$REGION" \+ --image-id "$AMI_ID" --instance-type "$CP_TYPE" \+ --key-name "$NAME_PREFIX" --subnet-id "$SUBNET_ID" \+ --security-group-ids "$SG_CP" \+ --associate-public-ip-address \+ --tag-specifications "ResourceType=instance,Tags=[{Key=Name,Value=$CP_NAME},{Key=opensandbox:role,Value=controlplane}]" \+ --user-data "$CP_USERDATA" \+ --query 'Instances[0].InstanceId' --output text)+ save_state "CP_ID" "$CP_ID"+ log "Waiting for control plane to enter running state..."+ aws ec2 wait instance-running --region "$REGION" --instance-ids "$CP_ID"+ CP_PUBLIC_IP=$(aws ec2 describe-instances --region "$REGION" --instance-ids "$CP_ID" \+ --query 'Reservations[0].Instances[0].PublicIpAddress' --output text)+ CP_PRIVATE_IP=$(aws ec2 describe-instances --region "$REGION" --instance-ids "$CP_ID" \+ --query 'Reservations[0].Instances[0].PrivateIpAddress' --output text)+ save_state "CP_PUBLIC_IP" "$CP_PUBLIC_IP"+ save_state "CP_PRIVATE_IP" "$CP_PRIVATE_IP"+ log "Control plane: public=$CP_PUBLIC_IP private=$CP_PRIVATE_IP"++ # ── Worker EC2 ──+ log "Launching worker ($WK_TYPE)..."+ WK_ID=$(aws ec2 run-instances --region "$REGION" \+ --image-id "$AMI_ID" --instance-type "$WK_TYPE" \+ --key-name "$NAME_PREFIX" --subnet-id "$SUBNET_ID" \+ --security-group-ids "$SG_WK" \+ --associate-public-ip-address \+ --block-device-mappings "DeviceName=/dev/sdb,Ebs={VolumeSize=$WK_DATA_GB,VolumeType=gp3,DeleteOnTermination=true}" \+ --tag-specifications "ResourceType=instance,Tags=[{Key=Name,Value=$WK_NAME},{Key=opensandbox:role,Value=worker}]" \+ --query 'Instances[0].InstanceId' --output text)+ save_state "WK_ID" "$WK_ID"+ aws ec2 wait instance-running --region "$REGION" --instance-ids "$WK_ID"+ WK_PUBLIC_IP=$(aws ec2 describe-instances --region "$REGION" --instance-ids "$WK_ID" \+ --query 'Reservations[0].Instances[0].PublicIpAddress' --output text)+ WK_PRIVATE_IP=$(aws ec2 describe-instances --region "$REGION" --instance-ids "$WK_ID" \+ --query 'Reservations[0].Instances[0].PrivateIpAddress' --output text)+ save_state "WK_PUBLIC_IP" "$WK_PUBLIC_IP"+ save_state "WK_PRIVATE_IP" "$WK_PRIVATE_IP"+ log "Worker: public=$WK_PUBLIC_IP private=$WK_PRIVATE_IP"++ # ── Wait for SSH ──+ log "Waiting for SSH on control plane..."+ until ssh -i "$SSH_KEY" -o StrictHostKeyChecking=no -o ConnectTimeout=5 \+ "$ADMIN_USER@$CP_PUBLIC_IP" "echo ready" 2>/dev/null; do+ sleep 5+ done++ # ── Provision control plane (Postgres + Redis containers) ──+ log "Provisioning control plane..."+ ssh -i "$SSH_KEY" -o StrictHostKeyChecking=no "$ADMIN_USER@$CP_PUBLIC_IP" "PG_PASSWORD='$PG_PASSWORD' bash -s" <<'CPSETUP'+set -euo pipefail+sudo apt-get update -qq+sudo apt-get install -y -qq docker.io jq curl+sudo systemctl enable --now docker+sudo mkdir -p /data/postgres /etc/opensandbox /usr/local/bin++sudo docker run -d --name postgres \+ --restart unless-stopped \+ --shm-size=2g \+ -p 5432:5432 \+ -e POSTGRES_USER=opensandbox \+ -e POSTGRES_PASSWORD="$PG_PASSWORD" \+ -e POSTGRES_DB=opensandbox \+ -v /data/postgres:/var/lib/postgresql/data \+ postgres:16 \+ postgres -c shared_buffers=512MB -c effective_cache_size=2GB -c synchronous_commit=off -c max_connections=100++sudo docker run -d --name redis --restart unless-stopped -p 6379:6379 redis:7-alpine++for i in $(seq 1 30); do+ sudo docker exec postgres pg_isready -U opensandbox 2>/dev/null && break+ sleep 2+done+echo "Control plane provisioned."+CPSETUP++ # ── Provision worker (mount NVMe + install QEMU host packages) ──+ log "Waiting for SSH on worker..."+ until ssh -i "$SSH_KEY" -o StrictHostKeyChecking=no -o ConnectTimeout=5 \+ "$ADMIN_USER@$WK_PUBLIC_IP" "echo ready" 2>/dev/null; do+ sleep 5+ done+ scp -i "$SSH_KEY" -o StrictHostKeyChecking=no \+ "$SCRIPT_DIR/../azure/setup-azure-host.sh" "$ADMIN_USER@$WK_PUBLIC_IP:/tmp/setup-host.sh"+ log "Provisioning worker (running setup-host.sh)..."+ ssh -i "$SSH_KEY" -o StrictHostKeyChecking=no "$ADMIN_USER@$WK_PUBLIC_IP" "bash -s" <<'WKSETUP'+set -euo pipefail+# Mount instance NVMe (m6id.large exposes /dev/nvme1n1) at /data, fall back to EBS+if ! mountpoint -q /data 2>/dev/null; then+ DATA_DISK=""+ for d in /dev/nvme1n1 /dev/nvme2n1 /dev/sdb /dev/xvdb; do+ if [ -b "$d" ] && ! blkid "$d" >/dev/null 2>&1; then+ DATA_DISK="$d"+ break+ fi+ done+ if [ -n "$DATA_DISK" ]; then+ sudo mkfs.xfs -f -m reflink=1 "$DATA_DISK"+ sudo mkdir -p /data+ echo "$DATA_DISK /data xfs defaults,nofail 0 2" | sudo tee -a /etc/fstab+ sudo mount /data+ fi+fi+sudo bash /tmp/setup-host.sh+WKSETUP++ # ── Env files ──+ log "Writing environment files..."+ ssh -i "$SSH_KEY" -o StrictHostKeyChecking=no "$ADMIN_USER@$CP_PUBLIC_IP" "sudo tee /etc/opensandbox/server.env > /dev/null" <<CPENV+OPENSANDBOX_MODE=server+OPENSANDBOX_PORT=8080+OPENSANDBOX_DATABASE_URL=postgres://opensandbox:$PG_PASSWORD@localhost:5432/opensandbox?sslmode=disable+OPENSANDBOX_REDIS_URL=redis://localhost:6379+OPENSANDBOX_JWT_SECRET=$JWT_SECRET+OPENSANDBOX_API_KEY=$API_KEY+OPENSANDBOX_REGION=$REGION+OPENSANDBOX_SANDBOX_DOMAIN=$DOMAIN+OPENSANDBOX_CELL_ID=$CELL_ID+OPENSANDBOX_CF_EVENT_ENDPOINT=$CF_EVENT_ENDPOINT+OPENSANDBOX_CF_EVENT_SECRET=$CF_EVENT_SECRET+OPENSANDBOX_CF_ADMIN_SECRET=$CF_ADMIN_SECRET+OPENSANDBOX_SESSION_JWT_SECRET=$SESSION_JWT_SECRET+OPENSANDBOX_COMPUTE_PROVIDER=aws+CPENV++ ssh -i "$SSH_KEY" -o StrictHostKeyChecking=no "$ADMIN_USER@$WK_PUBLIC_IP" "sudo tee /etc/opensandbox/worker.env > /dev/null" <<WKENV+OPENSANDBOX_MODE=worker+OPENSANDBOX_VM_BACKEND=qemu+OPENSANDBOX_QEMU_BIN=qemu-system-x86_64+OPENSANDBOX_DATA_DIR=/data/sandboxes+OPENSANDBOX_KERNEL_PATH=/opt/opensandbox/vmlinux+OPENSANDBOX_IMAGES_DIR=/data/firecracker/images+OPENSANDBOX_GRPC_ADVERTISE=$WK_PRIVATE_IP:9090+OPENSANDBOX_HTTP_ADDR=http://$WK_PRIVATE_IP:8081+OPENSANDBOX_JWT_SECRET=$JWT_SECRET+OPENSANDBOX_WORKER_ID=w-aws-${REGION}-dev3-1+OPENSANDBOX_REGION=$REGION+OPENSANDBOX_MAX_CAPACITY=10+OPENSANDBOX_PORT=8081+OPENSANDBOX_DEFAULT_SANDBOX_MEMORY_MB=1024+OPENSANDBOX_DEFAULT_SANDBOX_CPUS=2+OPENSANDBOX_DATABASE_URL=postgres://opensandbox:$PG_PASSWORD@$CP_PRIVATE_IP:5432/opensandbox?sslmode=disable+OPENSANDBOX_REDIS_URL=redis://$CP_PRIVATE_IP:6379+OPENSANDBOX_S3_BUCKET=$BUCKET+OPENSANDBOX_S3_REGION=$REGION+OPENSANDBOX_CELL_ID=$CELL_ID+WKENV++ # Postgres VPC access+ ssh -i "$SSH_KEY" -o StrictHostKeyChecking=no "$ADMIN_USER@$CP_PUBLIC_IP" <<PGFIX+sudo docker exec postgres bash -c "echo 'host all all $VPC_CIDR md5' >> /var/lib/postgresql/data/pg_hba.conf"+sudo docker exec postgres mkdir -p /var/lib/postgresql/data/conf.d 2>/dev/null || true+sudo docker exec postgres bash -c "echo \"listen_addresses = '*'\" > /var/lib/postgresql/data/conf.d/listen.conf"+sudo docker restart postgres+PGFIX++ log ""+ log "=== dev3-aws stack created ==="+ log "Region: $REGION"+ log "Cell ID: $CELL_ID"+ log "Control plane: $CP_PUBLIC_IP (private: $CP_PRIVATE_IP)"+ log "Worker: $WK_PUBLIC_IP (private: $WK_PRIVATE_IP)"+ log "S3 bucket: $BUCKET"+ log "API key: $API_KEY"+ log ""+ log "EVENT_SECRET to push to CF events-ingest (matches what's baked here):"+ log " echo '$CF_EVENT_SECRET' | npx wrangler secret put EVENT_SECRET"+ log " (note: same Worker handles both cells; secret should match Azure dev2's)"+ log ""+ log "Next: bash deploy/aws/create-aws-dev3.sh deploy"+}++# ── Deploy ──+cmd_deploy() {+ load_state+ log "Building and deploying binaries to dev3-aws..."++ cd "$PROJECT_ROOT"++ log "Building server..."+ GOOS=linux GOARCH=amd64 go build -o /tmp/opensandbox-server-dev3 ./cmd/server/++ log "Building worker..."+ GOOS=linux GOARCH=amd64 go build -o /tmp/opensandbox-worker-dev3 ./cmd/worker/++ log "Building agent..."+ GOOS=linux GOARCH=amd64 go build -o /tmp/osb-agent-dev3 ./cmd/agent/++ log "Deploying to control plane ($CP_PUBLIC_IP)..."+ scp -i "$SSH_KEY" -o StrictHostKeyChecking=no \+ /tmp/opensandbox-server-dev3 "$ADMIN_USER@$CP_PUBLIC_IP:/tmp/opensandbox-server"+ ssh -i "$SSH_KEY" -o StrictHostKeyChecking=no "$ADMIN_USER@$CP_PUBLIC_IP" \+ 'sudo systemctl stop opensandbox-server 2>/dev/null || true; sudo cp /tmp/opensandbox-server /usr/local/bin/ && sudo systemctl start opensandbox-server || sudo /usr/local/bin/opensandbox-server &'++ log "Deploying to worker ($WK_PUBLIC_IP)..."+ scp -i "$SSH_KEY" -o StrictHostKeyChecking=no \+ /tmp/opensandbox-worker-dev3 /tmp/osb-agent-dev3 \+ "$ADMIN_USER@$WK_PUBLIC_IP:/tmp/"+ ssh -i "$SSH_KEY" -o StrictHostKeyChecking=no "$ADMIN_USER@$WK_PUBLIC_IP" <<'DEPLOY'+set -euo pipefail+sudo systemctl stop opensandbox-worker 2>/dev/null || true+sudo cp /tmp/opensandbox-worker-dev3 /usr/local/bin/opensandbox-worker+sudo cp /tmp/osb-agent-dev3 /usr/local/bin/osb-agent+sudo systemctl start opensandbox-worker || true+DEPLOY++ log ""+ log "=== Deployed to dev3-aws ==="+ log "Smoke test: curl -s http://$CP_PUBLIC_IP:8080/api/sandboxes -H \"X-API-Key: $API_KEY\""+}++cmd_status() {+ load_state+ log "=== dev3-aws stack ==="+ log "Region: $REGION"+ log "Cell ID: $CELL_ID"+ log "VPC: ${VPC_ID:-?}"+ log ""+ log "Control plane: ${CP_PUBLIC_IP:-?} (private: ${CP_PRIVATE_IP:-?})"+ aws ec2 describe-instances --region "$REGION" --instance-ids "${CP_ID:-}" \+ --query 'Reservations[0].Instances[0].State.Name' --output text 2>/dev/null || echo " (not found)"+ log ""+ log "Worker: ${WK_PUBLIC_IP:-?} (private: ${WK_PRIVATE_IP:-?})"+ aws ec2 describe-instances --region "$REGION" --instance-ids "${WK_ID:-}" \+ --query 'Reservations[0].Instances[0].State.Name' --output text 2>/dev/null || echo " (not found)"+ log ""+ log "S3 bucket: ${BUCKET:-?}"+ log "API key: ${API_KEY:-?}"+}++cmd_ssh_cp() {+ load_state+ exec ssh -i "$SSH_KEY" -o StrictHostKeyChecking=no "$ADMIN_USER@$CP_PUBLIC_IP"+}++cmd_ssh_wk() {+ load_state+ exec ssh -i "$SSH_KEY" -o StrictHostKeyChecking=no "$ADMIN_USER@$WK_PUBLIC_IP"+}++cmd_stop() {+ load_state+ log "Stopping dev3-aws instances (use 'start' to resume)..."+ aws ec2 stop-instances --region "$REGION" --instance-ids "$CP_ID" "$WK_ID" >/dev/null+ log "Stop initiated."+}++cmd_start() {+ load_state+ log "Starting dev3-aws instances..."+ aws ec2 start-instances --region "$REGION" --instance-ids "$CP_ID" "$WK_ID" >/dev/null+ log "Start initiated. Note: public IPs may change unless you've allocated EIPs."+}++cmd_destroy() {+ load_state+ log "This will DELETE all dev3-aws resources (VPC, instances, security groups, S3 bucket)."+ read -p "Are you sure? (yes/no): " confirm+ if [ "$confirm" != "yes" ]; then+ log "Aborted."+ exit 0+ fi+ aws ec2 terminate-instances --region "$REGION" --instance-ids "$CP_ID" "$WK_ID" 2>/dev/null || true+ log "Waiting for instances to terminate..."+ aws ec2 wait instance-terminated --region "$REGION" --instance-ids "$CP_ID" "$WK_ID" 2>/dev/null || true+ aws ec2 delete-security-group --region "$REGION" --group-id "$SG_CP" 2>/dev/null || true+ aws ec2 delete-security-group --region "$REGION" --group-id "$SG_WK" 2>/dev/null || true+ aws ec2 disassociate-route-table --region "$REGION" --association-id "$(aws ec2 describe-route-tables --region $REGION --route-table-ids $RTB_ID --query 'RouteTables[0].Associations[0].RouteTableAssociationId' --output text)" 2>/dev/null || true+ aws ec2 delete-route-table --region "$REGION" --route-table-id "$RTB_ID" 2>/dev/null || true+ aws ec2 detach-internet-gateway --region "$REGION" --internet-gateway-id "$IGW_ID" --vpc-id "$VPC_ID" 2>/dev/null || true+ aws ec2 delete-internet-gateway --region "$REGION" --internet-gateway-id "$IGW_ID" 2>/dev/null || true+ aws ec2 delete-subnet --region "$REGION" --subnet-id "$SUBNET_ID" 2>/dev/null || true+ aws ec2 delete-vpc --region "$REGION" --vpc-id "$VPC_ID" 2>/dev/null || true+ aws s3 rb "s3://$BUCKET" --force 2>/dev/null || true+ aws ec2 delete-key-pair --region "$REGION" --key-name "$NAME_PREFIX" 2>/dev/null || true+ rm -f "$STATE_FILE"+ log "dev3-aws teardown complete."+}++case "${1:-}" in+ create) cmd_create ;;+ deploy) cmd_deploy ;;+ status) cmd_status ;;+ ssh-cp) cmd_ssh_cp ;;+ ssh-wk) cmd_ssh_wk ;;+ start) cmd_start ;;+ stop) cmd_stop ;;+ destroy) cmd_destroy ;;+ *)+ echo "Usage: $0 {create|deploy|status|ssh-cp|ssh-wk|start|stop|destroy}"+ exit 1+ ;;+esacdiff --git a/deploy/packer/worker-ami-aws.pkr.hcl b/deploy/packer/worker-ami-aws.pkr.hclnew file mode 100644index 00000000..765ece05--- /dev/null+++ b/deploy/packer/worker-ami-aws.pkr.hcl@@ -0,0 +1,215 @@+# worker-ami-aws.pkr.hcl — Packer template for AWS EC2 worker AMIs.+#+# Counterpart to worker-ami.pkr.hcl (which builds Azure managed images ++# publishes them to a Compute Gallery). This builds an AMI in EC2 and+# optionally publishes the AMI ID to SSM Parameter Store so EC2Pool's+# RefreshAMI loop picks it up automatically.+#+# Build: packer build -var "aws_region=us-east-1" deploy/packer/worker-ami-aws.pkr.hcl+#+# Inputs (most overridable via -var or env vars):+# - aws_region AWS region to build in+# - source_ami_filter Filter for the base Ubuntu AMI (default: 24.04 LTS)+# - instance_type Builder instance type (small is fine)+# - ssm_param_name If set, AMI ID is written here on success++packer {+ required_plugins {+ amazon = {+ version = ">= 1.3.0"+ source = "github.com/hashicorp/amazon"+ }+ }+}++variable "aws_region" {+ type = string+ default = "us-east-1"+}++variable "instance_type" {+ type = string+ default = "t3.medium"+}++variable "ami_name_prefix" {+ type = string+ default = "opensandbox-worker"+}++variable "worker_version" {+ type = string+ description = "Worker version tag (e.g. git short SHA). Used in AMI name + tags."+}++variable "ssm_param_name" {+ type = string+ description = "If set, the built AMI ID is written to this SSM parameter (e.g. /opensandbox/dev/worker-ami-id)."+ default = ""+}++variable "guest_image_version" {+ type = string+ description = "Hash of the canonical guest rootfs (default.ext4). Pulled from R2/S3 during AMI build."+ default = ""+}++variable "guest_image_url" {+ type = string+ description = "Canonical URL for the guest rootfs blob (e.g. https://r2.opensandbox.dev/golden-store/bases/{hash}/default.ext4)."+ default = ""+}++variable "worker_binary" {+ type = string+ default = "bin/opensandbox-worker"+ description = "Path to the cross-compiled worker binary (linux/amd64)."+}++variable "agent_binary" {+ type = string+ default = "bin/osb-agent"+ description = "Path to the cross-compiled agent binary (linux/amd64)."+}++variable "kernel_path" {+ type = string+ default = "deploy/firecracker/vmlinux"+ description = "Path to the Linux kernel image baked into the AMI."+}++# Latest Ubuntu 24.04 LTS amd64 from Canonical's account.+data "amazon-ami" "ubuntu" {+ region = var.aws_region+ most_recent = true+ owners = ["099720109477"]+ filters = {+ name = "ubuntu/images/hvm-ssd-gp3/ubuntu-noble-24.04-amd64-server-*"+ root-device-type = "ebs"+ virtualization-type = "hvm"+ architecture = "x86_64"+ }+}++source "amazon-ebs" "worker" {+ region = var.aws_region+ source_ami = data.amazon-ami.ubuntu.id+ instance_type = var.instance_type+ ssh_username = "ubuntu"++ ami_name = "${var.ami_name_prefix}-${var.worker_version}-${formatdate("YYYYMMDD-hhmmss", timestamp())}"+ ami_description = "OpenSandbox worker AMI — version ${var.worker_version}"++ tags = {+ Name = "${var.ami_name_prefix}-${var.worker_version}"+ "opensandbox:version" = var.worker_version+ "opensandbox:role" = "worker"+ "opensandbox:guest_version" = var.guest_image_version+ }++ # Bigger root volume so we can stage rootfs images and tools.+ launch_block_device_mappings {+ device_name = "/dev/sda1"+ volume_size = 30+ volume_type = "gp3"+ delete_on_termination = true+ }+}++build {+ sources = ["source.amazon-ebs.worker"]++ # Install system packages (KVM, QEMU, mdadm, xfs tools, etc.)+ provisioner "shell" {+ inline = [+ "set -euo pipefail",+ "export DEBIAN_FRONTEND=noninteractive",+ "sudo apt-get update -qq",+ "sudo apt-get install -y -qq qemu-system-x86 qemu-utils mdadm xfsprogs e2fsprogs jq curl ca-certificates",+ "sudo systemctl disable --now systemd-resolved 2>/dev/null || true",+ "sudo mkdir -p /opt/opensandbox/images /usr/local/bin /etc/opensandbox",+ ]+ }++ # Upload worker + agent binaries+ provisioner "file" {+ source = var.worker_binary+ destination = "/tmp/opensandbox-worker"+ }+ provisioner "file" {+ source = var.agent_binary+ destination = "/tmp/osb-agent"+ }+ provisioner "file" {+ source = var.kernel_path+ destination = "/tmp/vmlinux"+ }++ provisioner "shell" {+ inline = [+ "sudo install -m 0755 /tmp/opensandbox-worker /usr/local/bin/opensandbox-worker",+ "sudo install -m 0755 /tmp/osb-agent /usr/local/bin/osb-agent",+ "sudo install -m 0644 /tmp/vmlinux /opt/opensandbox/vmlinux",+ ]+ }++ # Pull the canonical guest rootfs from R2/S3 if configured.+ provisioner "shell" {+ inline = [+ "set -euo pipefail",+ "if [ -n '${var.guest_image_url}' ] && [ -n '${var.guest_image_version}' ]; then",+ " echo 'Pulling guest rootfs ${var.guest_image_version} from ${var.guest_image_url}...'",+ " sudo mkdir -p /opt/opensandbox/images/bases/${var.guest_image_version}",+ " sudo curl -fsSL -o /opt/opensandbox/images/bases/${var.guest_image_version}/default.ext4 '${var.guest_image_url}'",+ " sudo cp /opt/opensandbox/images/bases/${var.guest_image_version}/default.ext4 /opt/opensandbox/images/default.ext4",+ "fi",+ ]+ }++ # systemd unit (mirrors the one written by Azure setup-host.sh)+ provisioner "shell" {+ inline = [+ "set -euo pipefail",+ "sudo tee /etc/systemd/system/opensandbox-worker.service > /dev/null <<'UNIT'",+ "[Unit]",+ "Description=OpenSandbox Worker (QEMU backend)",+ "After=network-online.target",+ "Wants=network-online.target",+ "",+ "[Service]",+ "Type=simple",+ "ExecStartPre=/sbin/modprobe vhost_vsock",+ "EnvironmentFile=/etc/opensandbox/worker.env",+ "ExecStart=/usr/local/bin/opensandbox-worker",+ "Restart=on-failure",+ "RestartSec=5",+ "LimitNOFILE=1000000",+ "LimitNPROC=infinity",+ "KillMode=process",+ "TimeoutStopSec=300",+ "",+ "[Install]",+ "WantedBy=multi-user.target",+ "UNIT",+ "sudo systemctl daemon-reload",+ "sudo systemctl enable opensandbox-worker",+ ]+ }++ # Publish AMI ID to SSM if configured+ post-processor "shell-local" {+ only = ["amazon-ebs.worker"]+ inline = [+ "AMI_ID=$(jq -r '.builds[-1].artifact_id' manifest.json | cut -d: -f2)",+ "if [ -n '${var.ssm_param_name}' ] && [ -n \"$AMI_ID\" ]; then",+ " aws ssm put-parameter --region ${var.aws_region} --name '${var.ssm_param_name}' --type String --overwrite --value \"$AMI_ID\"",+ " aws ssm put-parameter --region ${var.aws_region} --name \"$(dirname '${var.ssm_param_name}')/worker-ami-version\" --type String --overwrite --value '${var.worker_version}'",+ " echo \"Published $AMI_ID to ${var.ssm_param_name}\"",+ "fi",+ ]+ }++ post-processor "manifest" {+ output = "manifest.json"+ }+}diff --git a/docs/multi-cloud.md b/docs/multi-cloud.mdnew file mode 100644index 00000000..b70fad6b--- /dev/null+++ b/docs/multi-cloud.md@@ -0,0 +1,109 @@+# Multi-cloud architecture++OpenSandbox is built so a cell can run on any IaaS that gives us VMs ++S3-compatible blob storage. Today we run cells on Azure (production ++dev1 + dev2) and have a complete AWS implementation ready for a third+cell. This doc explains the abstraction boundary so adding a new cloud+is a checklist, not a rewrite.++## What's cloud-specific++Three things, and only three:++1. **`internal/compute/{cloud}.go`** — implements `compute.Pool`. Knows how+ to launch / destroy / drain / list VMs in that cloud. Builds the+ cloud-init / user-data script using `compute.BuildWorkerEnv(spec)` plus+ provider-specific bring-up (NVMe RAID, AMI metadata fetches, etc.).++2. **`deploy/{cloud}/`** — provisioning scripts for VPC/VNet, control plane VM,+ first worker VM, S3-compatible bucket, IAM/managed identity. One+ `create-{cloud}-{cell}.sh` per cell.++3. **`deploy/packer/worker-ami-{cloud}.pkr.hcl`** — Packer template for the+ worker VM image. Same Go binaries, different baking.++Optional but useful per-cloud:++- **`internal/secrets/{backend}.go`** — runtime secrets backend. KeyVault for+ Azure, SecretsManager for AWS. Falls back to `EnvBackend` if unset.++## What's cloud-neutral++Everything else:++- `internal/api/`, `internal/auth/`, `internal/billing/`, `internal/controlplane/`,+ `internal/qemu/`, `internal/sandbox/`, `internal/storage/`, `internal/db/` —+ no cloud SDK imports anywhere.+- `cmd/server/main.go` selects a pool via `cfg.ComputeProvider` and hands it+ a cloud-neutral `compute.WorkerSpec`. The pool fills in cloud-specific bits.+- All Cloudflare Workers, D1 schema, R2 buckets — global, by definition.+- Postgres, Redis — standard protocols, work on any managed offering.+- Storage layer uses S3 SDK with custom endpoints — Azure Blob, AWS S3, GCS,+ R2, MinIO all work without code changes.++## Cell ID format++`{cloud}-{region}-cell-{slot}`, e.g.:+- `azure-eastus2-cell-a` (production)+- `azure-westus2-cell-b` (dev2)+- `aws-us-east-1-cell-a` (dev3, when provisioned)+- `gcp-us-central1-cell-a` (future)++Cell ID is the only routing identity. Workers, events, sandboxes, all+namespaced by `cell_id` everywhere.++## Adding a new cloud (checklist)++To stand up a GCP cell tomorrow:++1. **Implement Pool**: write `internal/compute/gcp.go` mirroring `azure.go` /+ `ec2.go`. About 400 LOC. Required methods are in the `compute.Pool`+ interface in `pool.go`. Implement `compute.WorkerSpecHolder` so the CP+ can inject the cloud-neutral `WorkerSpec`. Return a `compute.Machine`+ with internal/public addresses populated.++2. **Add config**: in `internal/config/config.go`, add a new `GCPxxx`+ field block (subscription/project equivalents) and add `"gcp"` to+ the switch in `cmd/server/main.go`.++3. **Provisioning script**: `deploy/gcp/create-gcp-{cellname}.sh`,+ mirroring `deploy/azure/create-azure-dev2.sh` and+ `deploy/aws/create-aws-dev3.sh`. Same shape: VPC + control plane VM+ + worker VM + GCS bucket + IAM service account.++4. **Packer template**: `deploy/packer/worker-ami-gcp.pkr.hcl`. Same+ provisioning as the AWS template (install QEMU, copy binaries, install+ systemd unit) but builds a GCE image instead of an AMI.++5. **Optional secrets backend**: `internal/secrets/gcpsecretmanager.go`+ if you want to use GCP Secret Manager for the bootstrap config bundle.++That's it. None of the rest of the codebase changes.++## Things that are NOT cloud-specific (despite looking like they could be)++- **Sandbox storage paths** (`/data/firecracker/images`, `/data/sandboxes`):+ established by the AMI / image, identical across clouds. Avoid forking+ these per cloud — the cost is debugging confusion later.++- **Worker binary**: same `linux/amd64` build runs anywhere. We may add+ `linux/arm64` builds for ARM-based instance families (Graviton, Ampere)+ but that's an instruction-set choice, not a cloud one.++- **gRPC / HTTP APIs**: standard protocols. Cloud-specific NSG/SG rules+ open the same ports.++- **Postgres schema, Redis stream layout, S3 keyspace**: identical across+ cells regardless of cloud.++## R2 as canonical resource store++Per-cell S3-compatible buckets (Azure Blob, AWS S3, GCS) are caches.+**Canonical** golden rootfs blobs and template blobs live in Cloudflare R2,+which is the only object store available identically from every cloud.++When a worker needs a golden it doesn't have, it pulls from R2 and caches+locally. This eliminates "the canonical golden lives in westus2 Azure Blob"+as a hidden assumption and makes new cells truly portable.++See the planning doc and the `golden_versions` D1 table for details.diff --git a/internal/compute/azure.go b/internal/compute/azure.goindex 341c5ee3..cfa4c9cb 100644--- a/internal/compute/azure.go+++ b/internal/compute/azure.go@@ -25,29 +25,42 @@ const (// AzurePoolConfig configures the Azure compute pool.type AzurePoolConfig struct {- SubscriptionID string- ResourceGroup string- Region string // e.g. "westus2"- VMSize string // e.g. "Standard_D16s_v5"- ImageID string // custom image ID or URN (e.g. "Canonical:ubuntu-24_04-lts:server:latest")- SubnetID string // full resource ID of the subnet- AdminUsername string // SSH username (default: "azureuser")- SSHPublicKey string // SSH public key content- DataDiskSizeGB int // data disk size (default: 256)- WorkerEnvBase64 string // base64-encoded worker.env content (injected via cloud-init)- KeyVaultName string // Azure Key Vault name for dynamic image ID refresh (e.g. "opensandbox-prod")+ SubscriptionID string+ ResourceGroup string+ Region string // e.g. "westus2"+ VMSize string // e.g. "Standard_D16s_v5"+ ImageID string // custom image ID or URN (e.g. "Canonical:ubuntu-24_04-lts:server:latest")+ SubnetID string // full resource ID of the subnet+ AdminUsername string // SSH username (default: "azureuser")+ SSHPublicKey string // SSH public key content+ DataDiskSizeGB int // data disk size (default: 256)+ KeyVaultName string // Azure Key Vault name for dynamic image ID refresh}// AzurePool implements compute.Pool using Azure VMs.+//+// Worker bring-up: the CP injects a WorkerSpec via SetWorkerSpec at startup.+// CreateMachine combines the spec with Azure-specific cloud-init (NVMe RAID,+// AMI image-layout assumptions, Azure metadata fetches) to produce userdata.type AzurePool struct {vmClient *armcompute.VirtualMachinesClientdiskClient *armcompute.DisksClientnicClient *armnetwork.InterfacesClient- mu sync.RWMutex // protects cfg.ImageID+ mu sync.RWMutex // protects cfg.ImageID + speccfg AzurePoolConfig+ spec WorkerSpec // injected via SetWorkerSpec; copied into worker env on every CreateMachinekvClient *azsecrets.Client // Key Vault client for dynamic image refresh (nil if not configured)}+// SetWorkerSpec injects the cloud-neutral worker config the CP wants every+// new worker VM to use. Idempotent — overwrites any previous spec.+// Implements compute.WorkerSpecHolder.+func (p *AzurePool) SetWorkerSpec(spec WorkerSpec) {+ p.mu.Lock()+ defer p.mu.Unlock()+ p.spec = spec+}+// NewAzurePool creates an Azure compute pool using default credentials (managed identity, CLI, env vars).func NewAzurePool(cfg AzurePoolConfig) (*AzurePool, error) {cred, err := azidentity.NewDefaultAzureCredential(nil)@@ -536,6 +549,7 @@ func (p *AzurePool) vmToMachine(vm *armcompute.VirtualMachine, nic *armnetwork.I}func (p *AzurePool) buildUserData(opts MachineOpts) string {+ _ = opts // opts.Region/Size honored at VM-create level; cloud-init is cell-uniformvar sb strings.Buildersb.WriteString("#!/bin/bash\nset -euo pipefail\n\n")@@ -578,11 +592,15 @@ func (p *AzurePool) buildUserData(opts MachineOpts) string {sb.WriteString(" echo 'Copied retained bases from /opt/opensandbox/images/bases to /data/firecracker/images/bases'\n")sb.WriteString("fi\n\n")- // Write worker env file from base64-encoded config- if p.cfg.WorkerEnvBase64 != "" {- sb.WriteString("# Write worker env (from control plane config)\n")+ // Write worker env file from injected WorkerSpec.+ p.mu.RLock()+ envContent := BuildWorkerEnv(p.spec)+ p.mu.RUnlock()+ if envContent != "" {+ envB64 := base64.StdEncoding.EncodeToString([]byte(envContent))+ sb.WriteString("# Write worker env (from control plane WorkerSpec)\n")sb.WriteString("mkdir -p /etc/opensandbox\n")- sb.WriteString(fmt.Sprintf("echo '%s' | base64 -d > /etc/opensandbox/worker.env\n\n", p.cfg.WorkerEnvBase64))+ sb.WriteString(fmt.Sprintf("echo '%s' | base64 -d > /etc/opensandbox/worker.env\n\n", envB64))// Patch in the VM's own private IP and identitysb.WriteString("# Patch worker identity with this VM's private IP and hostname\n")diff --git a/internal/compute/ec2.go b/internal/compute/ec2.goindex e3f11173..95f98a68 100644--- a/internal/compute/ec2.go+++ b/internal/compute/ec2.go@@ -17,43 +17,64 @@ import ()const (- tagRole = "opensandbox:role"- tagInstanceType = "opensandbox:instance-type"- tagDraining = "opensandbox:draining"+ // AWS tag keys (kept consistent with the Azure pool's azure-prefixed tags).+ awsTagRole = "opensandbox:role"+ awsTagInstanceType = "opensandbox:instance-type"+ awsTagDraining = "opensandbox:draining"+ awsTagWorker = "worker")// EC2PoolConfig configures the EC2 compute pool.type EC2PoolConfig struct {Region string- AccessKeyID string+ AccessKeyID string // empty = use default credential chain (IAM role preferred)SecretAccessKey string- AMI string- InstanceType string // "c7gd.metal", "r6gd.metal", "r7gd.metal"+ AMI string // static AMI ID; empty if SSMParameterName is set+ InstanceType string // e.g. "c7gd.metal", "r7gd.xlarge", "m7i.large"SubnetID stringSecurityGroupID string- KeyName string- IAMInstanceProfile string // IAM instance profile name (for Secrets Manager + S3 access)- SecretsARN string // Secrets Manager ARN passed to worker env- SSMParameterName string // SSM parameter for dynamic AMI ID (e.g. /opensandbox/prod/worker-ami-id)+ KeyName string // optional SSH key pair (debug use only)+ IAMInstanceProfile string // attached to instances; gives them Secrets Manager + S3 read+ SecretsARN string // Secrets Manager ARN; passed to worker via WorkerSpec.SecretsRef+ SSMParameterName string // SSM parameter for dynamic AMI ID (e.g. /opensandbox/dev/worker-ami-id)}// EC2Pool implements compute.Pool using AWS EC2 instances.+//+// Worker bring-up: the CP injects a WorkerSpec via SetWorkerSpec at startup.+// CreateMachine combines the spec with EC2-specific cloud-init (NVMe instance+// store mounting, IAM-role secret fetch, AMI-baked image layout) to produce+// instance user-data.+//+// Mirrors AzurePool conventions where applicable so cells in either cloud+// behave identically from the CP's perspective.type EC2Pool struct {client *ec2.ClientawsCfg aws.Config- mu sync.RWMutex // protects cfg.AMI+ mu sync.RWMutex // protects cfg.AMI + speccfg EC2PoolConfig+ spec WorkerSpec // injected via SetWorkerSpec; copied into worker env on every CreateMachine+}++// SetWorkerSpec injects the cloud-neutral worker config. Idempotent.+// Implements compute.WorkerSpecHolder.+func (p *EC2Pool) SetWorkerSpec(spec WorkerSpec) {+ p.mu.Lock()+ defer p.mu.Unlock()+ // EC2 worker fetches secrets via Secrets Manager + IAM, so propagate the ARN.+ if p.cfg.SecretsARN != "" && spec.SecretsRef == "" {+ spec.SecretsRef = p.cfg.SecretsARN+ }+ p.spec = spec}// NewEC2Pool creates an EC2 compute pool.-// If AccessKeyID is empty, uses the default AWS credential chain (IAM instance profile, env vars, etc.).+// If AccessKeyID is empty, uses the default AWS credential chain (IAM+// instance profile preferred, then env vars, then ~/.aws/credentials).func NewEC2Pool(cfg EC2PoolConfig) (*EC2Pool, error) {- var client *ec2.Client-var awsCfgVal aws.Configif cfg.AccessKeyID != "" {- // Static credentialsawsCfgVal = aws.Config{Region: cfg.Region,Credentials: credentials.NewStaticCredentialsProvider(@@ -63,7 +84,6 @@ func NewEC2Pool(cfg EC2PoolConfig) (*EC2Pool, error) {),}} else {- // IAM credential chainvar err errorawsCfgVal, err = awsconfig.LoadDefaultConfig(context.Background(),awsconfig.WithRegion(cfg.Region),@@ -73,10 +93,8 @@ func NewEC2Pool(cfg EC2PoolConfig) (*EC2Pool, error) {}}- client = ec2.NewFromConfig(awsCfgVal)-return &EC2Pool{- client: client,+ client: ec2.NewFromConfig(awsCfgVal),awsCfg: awsCfgVal,cfg: cfg,}, nil@@ -91,8 +109,15 @@ func (p *EC2Pool) CreateMachine(ctx context.Context, opts MachineOpts) (*Machinep.mu.RLock()ami := p.cfg.AMIp.mu.RUnlock()+ if opts.Image != "" {+ ami = opts.Image+ }+ if ami == "" {+ return nil, fmt.Errorf("ec2: no AMI set (configure AMI or SSMParameterName)")+ }userData := p.buildUserData(opts)+ machineName := fmt.Sprintf("osb-worker-%s", randomSuffix())input := &ec2.RunInstancesInput{ImageId: aws.String(ami),@@ -104,9 +129,15 @@ func (p *EC2Pool) CreateMachine(ctx context.Context, opts MachineOpts) (*Machine{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)},+ {Key: aws.String("Name"), Value: aws.String(machineName)},+ {Key: aws.String(awsTagRole), Value: aws.String(awsTagWorker)},+ {Key: aws.String(awsTagInstanceType), Value: aws.String(instanceType)},+ },+ },+ {+ ResourceType: ec2types.ResourceTypeVolume,+ Tags: []ec2types.Tag{+ {Key: aws.String(awsTagRole), Value: aws.String(awsTagWorker)},},},},@@ -131,11 +162,9 @@ func (p *EC2Pool) CreateMachine(ctx context.Context, opts MachineOpts) (*Machineif 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}@@ -145,7 +174,7 @@ func (p *EC2Pool) DestroyMachine(ctx context.Context, machineID string) error {InstanceIds: []string{machineID},})if err != nil {- return fmt.Errorf("ec2: TerminateInstances failed for %s: %w", machineID, err)+ return fmt.Errorf("ec2: TerminateInstances %s: %w", machineID, err)}return nil}@@ -155,7 +184,7 @@ func (p *EC2Pool) StartMachine(ctx context.Context, machineID string) error {InstanceIds: []string{machineID},})if err != nil {- return fmt.Errorf("ec2: StartInstances failed for %s: %w", machineID, err)+ return fmt.Errorf("ec2: StartInstances %s: %w", machineID, err)}return nil}@@ -165,7 +194,7 @@ func (p *EC2Pool) StopMachine(ctx context.Context, machineID string) error {InstanceIds: []string{machineID},})if err != nil {- return fmt.Errorf("ec2: StopInstances failed for %s: %w", machineID, err)+ return fmt.Errorf("ec2: StopInstances %s: %w", machineID, err)}return nil}@@ -173,22 +202,14 @@ func (p *EC2Pool) StopMachine(ctx context.Context, machineID string) error {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"},- },+ {Name: aws.String("tag:" + awsTagRole), Values: []string{awsTagWorker}},+ {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)+ return nil, fmt.Errorf("ec2: DescribeInstances: %w", err)}-var machines []*Machinefor _, res := range result.Reservations {for _, inst := range res.Instances {@@ -203,16 +224,14 @@ func (p *EC2Pool) HealthCheck(ctx context.Context, machineID string) error {InstanceIds: []string{machineID},})if err != nil {- return fmt.Errorf("ec2: DescribeInstanceStatus failed for %s: %w", machineID, err)+ return fmt.Errorf("ec2: DescribeInstanceStatus %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)+ st := result.InstanceStatuses[0]+ if st.InstanceStatus.Status != ec2types.SummaryStatusOk {+ return fmt.Errorf("ec2: instance %s status is %s", machineID, st.InstanceStatus.Status)}return nil}@@ -224,59 +243,67 @@ func (p *EC2Pool) SupportedRegions(_ context.Context) ([]string, error) {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")},- },+ Tags: []ec2types.Tag{{Key: aws.String(awsTagDraining), Value: aws.String("true")}},})if err != nil {- return fmt.Errorf("ec2: failed to tag %s as draining: %w", machineID, err)+ return fmt.Errorf("ec2: tag %s 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))- }+// CleanupOrphanedResources reclaims ENIs and EBS volumes left by failed+// VM creates. Mirrors the AzurePool's NIC/disk cleanup.+//+// Satisfies the controlplane.OrphanCleaner interface.+func (p *EC2Pool) CleanupOrphanedResources(ctx context.Context) (int, error) {+ freed := 0- httpAddr := ""- if inst.PublicIpAddress != nil {- httpAddr = fmt.Sprintf("http://%s:8080", aws.ToString(inst.PublicIpAddress))+ // Orphaned ENIs: tagged osb-worker but unattached for >5 min.+ nicResp, err := p.client.DescribeNetworkInterfaces(ctx, &ec2.DescribeNetworkInterfacesInput{+ Filters: []ec2types.Filter{+ {Name: aws.String("tag:" + awsTagRole), Values: []string{awsTagWorker}},+ {Name: aws.String("status"), Values: []string{"available"}},+ },+ })+ if err == nil {+ for _, n := range nicResp.NetworkInterfaces {+ if _, dErr := p.client.DeleteNetworkInterface(ctx, &ec2.DeleteNetworkInterfaceInput{+ NetworkInterfaceId: n.NetworkInterfaceId,+ }); dErr == nil {+ freed+++ } else {+ log.Printf("ec2: orphan ENI cleanup %s: %v", aws.ToString(n.NetworkInterfaceId), dErr)+ }+ }}- region := ""- if inst.Placement != nil {- region = aws.ToString(inst.Placement.AvailabilityZone)+ // Orphaned EBS volumes: tagged osb-worker, status=available.+ volResp, err := p.client.DescribeVolumes(ctx, &ec2.DescribeVolumesInput{+ Filters: []ec2types.Filter{+ {Name: aws.String("tag:" + awsTagRole), Values: []string{awsTagWorker}},+ {Name: aws.String("status"), Values: []string{"available"}},+ },+ })+ if err == nil {+ for _, v := range volResp.Volumes {+ if _, dErr := p.client.DeleteVolume(ctx, &ec2.DeleteVolumeInput{+ VolumeId: v.VolumeId,+ }); dErr == nil {+ freed+++ } else {+ log.Printf("ec2: orphan volume cleanup %s: %v", aws.ToString(v.VolumeId), dErr)+ }+ }}- return &Machine{- ID: id,- Addr: addr,- HTTPAddr: httpAddr,- Region: region,- Status: status,- }+ return freed, nil}// RefreshAMI checks SSM Parameter Store for a new AMI ID and updates the pool config.-// Returns the current AMI ID and the version string (if a version parameter exists alongside).+// Returns the current AMI ID and the version string (if a sibling parameter exists).// If SSMParameterName is not configured, returns the static AMI with no error.+//+// Satisfies the controlplane.AMIRefresher interface.func (p *EC2Pool) RefreshAMI(ctx context.Context) (amiID string, version string, err error) {if p.cfg.SSMParameterName == "" {p.mu.RLock()@@ -286,7 +313,6 @@ func (p *EC2Pool) RefreshAMI(ctx context.Context) (amiID string, version string,ssmClient := ssm.NewFromConfig(p.awsCfg)- // Fetch AMI IDresult, err := ssmClient.GetParameter(ctx, &ssm.GetParameterInput{Name: aws.String(p.cfg.SSMParameterName),})@@ -298,8 +324,7 @@ func (p *EC2Pool) RefreshAMI(ctx context.Context) (amiID string, version string,return "", "", fmt.Errorf("ec2: SSM parameter %s is empty", p.cfg.SSMParameterName)}- // Fetch version (convention: sibling parameter with last segment replaced by "worker-ami-version")- // e.g. /opensandbox/prod/worker-ami-id -> /opensandbox/prod/worker-ami-version+ // Sibling version param convention: replace last segment with worker-ami-versionversionParam := p.cfg.SSMParameterName[:strings.LastIndex(p.cfg.SSMParameterName, "/")+1] + "worker-ami-version"if vResult, vErr := ssmClient.GetParameter(ctx, &ssm.GetParameterInput{Name: aws.String(versionParam),@@ -317,34 +342,113 @@ func (p *EC2Pool) RefreshAMI(ctx context.Context) (amiID string, version string,return newAMI, version, 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,+ }+}++// buildUserData returns the EC2 instance user-data script. Combines the+// CP-supplied WorkerSpec with EC2-specific cloud-init (NVMe instance-store+// mount, AMI-baked rootfs copy, machine-id stamping).func (p *EC2Pool) buildUserData(opts MachineOpts) string {+ _ = opts // opts.Region/Size honored at instance launch; cloud-init is cell-uniformvar sb strings.Buildersb.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")+ // NVMe instance store handling. Larger metal/x.gd instance families expose+ // multiple NVMe drives at /dev/nvme[1-N]n1; smaller instances rely on EBS+ // (the attached data volume). RAID 0 across instance store NVMe when present.+ sb.WriteString("# Mount data: prefer NVMe instance store (RAID 0), else first EBS data volume\n")+ sb.WriteString("if ! mountpoint -q /data 2>/dev/null; then\n")+ sb.WriteString(" mkdir -p /data\n")+ sb.WriteString(" ROOT_DEV=$(lsblk -no PKNAME $(findmnt -n -o SOURCE /) 2>/dev/null | head -1)\n")+ sb.WriteString(" NVME_DISKS=()\n")+ sb.WriteString(" for d in /dev/nvme1n1 /dev/nvme2n1 /dev/nvme3n1 /dev/nvme4n1 /dev/nvme5n1; do\n")+ sb.WriteString(" [ -b \"$d\" ] || continue\n")+ sb.WriteString(" [ \"$(basename $d)\" = \"$ROOT_DEV\" ] && continue\n")+ sb.WriteString(" NVME_DISKS+=(\"$d\")\n")+ sb.WriteString(" done\n")+ sb.WriteString(" if [ ${#NVME_DISKS[@]} -gt 1 ]; then\n")+ sb.WriteString(" mdadm --create /dev/md0 --level=0 --raid-devices=${#NVME_DISKS[@]} \"${NVME_DISKS[@]}\" --run --force\n")+ sb.WriteString(" mkfs.xfs -f -m reflink=1 /dev/md0 && mount /dev/md0 /data\n")+ sb.WriteString(" elif [ ${#NVME_DISKS[@]} -eq 1 ]; then\n")+ sb.WriteString(" mkfs.xfs -f -m reflink=1 \"${NVME_DISKS[0]}\" && mount \"${NVME_DISKS[0]}\" /data\n")+ sb.WriteString(" else\n")+ sb.WriteString(" for d in /dev/nvme1n1 /dev/sdb /dev/xvdb; do\n")+ sb.WriteString(" [ -b \"$d\" ] || continue\n")+ sb.WriteString(" mkfs.xfs -f -m reflink=1 \"$d\" && mount \"$d\" /data && break\n")+ sb.WriteString(" done\n")+ sb.WriteString(" fi\n")+ sb.WriteString("fi\n")+ sb.WriteString("mkdir -p /data/sandboxes /data/firecracker/images\n")+ sb.WriteString("# Copy AMI-baked rootfs images to data disk if not already present\n")+ sb.WriteString("if [ -d /opt/opensandbox/images ] && [ ! -f /data/firecracker/images/default.ext4 ]; then\n")+ sb.WriteString(" cp /opt/opensandbox/images/*.ext4 /data/firecracker/images/ 2>/dev/null || true\n")+ sb.WriteString("fi\n")+ sb.WriteString("if [ -d /opt/opensandbox/images/bases ] && [ ! -d /data/firecracker/images/bases ]; then\n")+ sb.WriteString(" cp -r /opt/opensandbox/images/bases /data/firecracker/images/\n")sb.WriteString("fi\n\n")- // Start the worker service+ // Worker env from injected WorkerSpec.+ p.mu.RLock()+ envContent := BuildWorkerEnv(p.spec)+ p.mu.RUnlock()+ if envContent != "" {+ envB64 := base64.StdEncoding.EncodeToString([]byte(envContent))+ sb.WriteString("# Write worker env (from control plane WorkerSpec)\n")+ sb.WriteString("mkdir -p /etc/opensandbox\n")+ sb.WriteString(fmt.Sprintf("echo '%s' | base64 -d > /etc/opensandbox/worker.env\n\n", envB64))++ sb.WriteString("# Patch worker identity from EC2 instance metadata (IMDSv2)\n")+ sb.WriteString("TOKEN=$(curl -s -X PUT 'http://169.254.169.254/latest/api/token' -H 'X-aws-ec2-metadata-token-ttl-seconds: 300')\n")+ sb.WriteString("MY_IP=$(curl -s -H \"X-aws-ec2-metadata-token: $TOKEN\" http://169.254.169.254/latest/meta-data/local-ipv4)\n")+ sb.WriteString("INSTANCE_ID=$(curl -s -H \"X-aws-ec2-metadata-token: $TOKEN\" http://169.254.169.254/latest/meta-data/instance-id)\n")+ sb.WriteString("WORKER_ID=\"w-aws-${INSTANCE_ID}\"\n")+ sb.WriteString("sed -i \"s|OPENSANDBOX_GRPC_ADVERTISE=.*|OPENSANDBOX_GRPC_ADVERTISE=${MY_IP}:9090|\" /etc/opensandbox/worker.env\n")+ sb.WriteString("sed -i \"s|OPENSANDBOX_HTTP_ADDR=.*|OPENSANDBOX_HTTP_ADDR=http://${MY_IP}:8081|\" /etc/opensandbox/worker.env\n")+ sb.WriteString("sed -i \"s|OPENSANDBOX_WORKER_ID=.*|OPENSANDBOX_WORKER_ID=${WORKER_ID}|\" /etc/opensandbox/worker.env\n")+ sb.WriteString("echo \"OPENSANDBOX_MACHINE_ID=${INSTANCE_ID}\" >> /etc/opensandbox/worker.env\n\n")+ }++ // Clean stale golden snapshot — must rebuild for this instance's QEMU+ sb.WriteString("rm -rf /data/sandboxes/golden-snapshot /data/sandboxes/golden\n\n")++ // Start workersb.WriteString("systemctl restart opensandbox-worker\n")return sb.String()}+diff --git a/internal/compute/pool.go b/internal/compute/pool.goindex 944d49af..496824f2 100644--- a/internal/compute/pool.go+++ b/internal/compute/pool.go@@ -16,11 +16,64 @@ type Machine struct {// MachineOpts are options for creating a new machine.type MachineOpts struct {Region string- Size string // provider-specific machine size- Image string // worker Docker image+ Size string // provider-specific machine size (e.g. "Standard_D16s_v5", "c7gd.metal")+ Image string // provider-specific image reference (URN, AMI ID, etc.)+}++// WorkerSpec carries cloud-neutral configuration that the control plane+// supplies to a Pool when launching a worker. The Pool combines this with+// its own cloud-specific defaults (mount paths, image layout, NVMe handling)+// to build the worker's cloud-init / user-data.+//+// This decouples the CP from cloud-specific worker bring-up. Adding a new+// cloud means writing a new Pool; the CP doesn't change.+type WorkerSpec struct {+ // Cell + region identity+ CellID string // "{cloud}-{region}-cell-{slot}", e.g. "azure-westus2-cell-b"+ Region string // e.g. "westus2", "us-east-1"++ // Connectivity back to the control plane+ DatabaseURL string+ RedisURL string++ // Auth+ JWTSecret string // sandbox-scoped JWT signing key+ SessionJWTSecret string // session JWT shared with api-edge (cf-cutover)++ // CF-cutover event pipe+ CFEventEndpoint string+ CFEventSecret string+ CFAdminSecret string++ // Worker capacity + sandbox defaults+ MaxCapacity int+ SandboxDomain string+ DefaultMemoryMB int+ DefaultCPUs int+ DefaultDiskMB int++ // Object storage (S3-compat: Azure Blob, AWS S3, GCS, R2, MinIO)+ S3Endpoint string+ S3Bucket string+ S3Region string+ S3AccessKeyID string+ S3SecretAccessKey string+ S3ForcePathStyle bool++ // Optional analytics+ SegmentWriteKey string++ // Provider-specific secrets reference (AWS Secrets Manager ARN, GCP Secret+ // Manager name, etc.). The pool decides what to do with this — Azure pool+ // ignores it (uses Key Vault directly), AWS pool exports it as+ // OPENSANDBOX_SECRETS_ARN.+ SecretsRef string}// Pool is the interface for compute pool providers.+//+// Implementations: AzurePool, EC2Pool, LocalPool. Adding a new cloud is+// a new file implementing this interface — no other code changes.type Pool interface {CreateMachine(ctx context.Context, opts MachineOpts) (*Machine, error)DestroyMachine(ctx context.Context, machineID string) error@@ -31,3 +84,100 @@ type Pool interface {SupportedRegions(ctx context.Context) ([]string, error)DrainMachine(ctx context.Context, machineID string) error}++// WorkerSpecHolder is implemented by pools that accept a WorkerSpec to+// generate worker cloud-init / user-data. Set once at startup; CreateMachine+// uses it for every subsequent launch.+//+// This is a separate interface (not a Pool method) so LocalPool (testing)+// can ignore it cleanly.+type WorkerSpecHolder interface {+ SetWorkerSpec(spec WorkerSpec)+}++// BuildWorkerEnv produces the contents of /etc/opensandbox/worker.env from a+// WorkerSpec. Pool implementations use this as a starting point and+// concatenate provider-specific lines (paths, machine-id placeholders, etc.).+//+// Lines marked with PLACEHOLDER are patched on the worker by cloud-init+// using the VM's actual private IP and hostname.+func BuildWorkerEnv(spec WorkerSpec) string {+ return buildEnvLines([]envLine{+ {"HOME", "/root"},+ {"OPENSANDBOX_MODE", "worker"},+ {"OPENSANDBOX_VM_BACKEND", "qemu"},+ {"OPENSANDBOX_QEMU_BIN", "qemu-system-x86_64"},+ {"OPENSANDBOX_DATA_DIR", "/data/sandboxes"},+ {"OPENSANDBOX_KERNEL_PATH", "/opt/opensandbox/vmlinux"},+ {"OPENSANDBOX_IMAGES_DIR", "/data/firecracker/images"},+ {"OPENSANDBOX_GRPC_ADVERTISE", "PLACEHOLDER:9090"},+ {"OPENSANDBOX_HTTP_ADDR", "http://PLACEHOLDER:8081"},+ {"OPENSANDBOX_WORKER_ID", "PLACEHOLDER"},+ {"OPENSANDBOX_PORT", "8081"},+ {"OPENSANDBOX_JWT_SECRET", spec.JWTSecret},+ {"OPENSANDBOX_REGION", spec.Region},+ {"OPENSANDBOX_CELL_ID", spec.CellID},+ {"OPENSANDBOX_MAX_CAPACITY", itoa(spec.MaxCapacity)},+ {"OPENSANDBOX_DEFAULT_SANDBOX_MEMORY_MB", itoa(spec.DefaultMemoryMB)},+ {"OPENSANDBOX_DEFAULT_SANDBOX_CPUS", itoa(spec.DefaultCPUs)},+ {"OPENSANDBOX_DEFAULT_SANDBOX_DISK_MB", itoa(spec.DefaultDiskMB)},+ {"OPENSANDBOX_DATABASE_URL", spec.DatabaseURL},+ {"OPENSANDBOX_REDIS_URL", spec.RedisURL},+ {"OPENSANDBOX_S3_BUCKET", spec.S3Bucket},+ {"OPENSANDBOX_S3_REGION", spec.S3Region},+ {"OPENSANDBOX_S3_ENDPOINT", spec.S3Endpoint},+ {"OPENSANDBOX_S3_ACCESS_KEY_ID", spec.S3AccessKeyID},+ {"OPENSANDBOX_S3_SECRET_ACCESS_KEY", spec.S3SecretAccessKey},+ {"OPENSANDBOX_S3_FORCE_PATH_STYLE", boolStr(spec.S3ForcePathStyle)},+ {"OPENSANDBOX_SANDBOX_DOMAIN", spec.SandboxDomain},+ {"SEGMENT_WRITE_KEY", spec.SegmentWriteKey},+ {"OPENSANDBOX_CF_EVENT_ENDPOINT", spec.CFEventEndpoint},+ {"OPENSANDBOX_CF_EVENT_SECRET", spec.CFEventSecret},+ {"OPENSANDBOX_CF_ADMIN_SECRET", spec.CFAdminSecret},+ {"OPENSANDBOX_SESSION_JWT_SECRET", spec.SessionJWTSecret},+ {"OPENSANDBOX_SECRETS_ARN", spec.SecretsRef},+ })+}++type envLine struct{ key, value string }++func buildEnvLines(lines []envLine) string {+ var n int+ for _, l := range lines {+ n += len(l.key) + len(l.value) + 2+ }+ out := make([]byte, 0, n)+ for _, l := range lines {+ if l.value == "" {+ continue // omit empty values rather than write "KEY=" lines+ }+ out = append(out, l.key...)+ out = append(out, '=')+ out = append(out, l.value...)+ out = append(out, '\n')+ }+ return string(out)+}++func itoa(n int) string {+ if n == 0 {+ return ""+ }+ // inline conversion to avoid pulling strconv just for this+ if n < 0 {+ return "-" + itoa(-n)+ }+ digits := []byte{}+ for n > 0 {+ digits = append([]byte{byte('0' + n%10)}, digits...)+ n /= 10+ }+ return string(digits)+}++func boolStr(b bool) string {+ if b {+ return "true"+ }+ return ""+}diff --git a/internal/config/config.go b/internal/config/config.goindex 9b408524..5d0d7fdc 100644--- a/internal/config/config.go+++ b/internal/config/config.go@@ -151,6 +151,17 @@ type Config struct {// CF halt-list endpoint. The halt_reconciler goroutine pulls this every 60s// to catch missed halt webhooks. Empty disables the reconciler.HaltListURL string++ // Multi-cloud abstraction. Selects which compute pool the autoscaler uses.+ // Valid values: "azure", "aws", "" (autodetect from existing fields).+ // Adding a new cloud means a new compute.Pool implementation + a new+ // case in cmd/server/main.go pool selection.+ ComputeProvider string++ // SecretsProvider selects the runtime secrets backend.+ // Valid values: "keyvault" (Azure), "secretsmanager" (AWS), "env" (env-var only).+ // Defaults to "env" if unset.+ SecretsProvider string}// Load reads configuration from environment variables with sensible defaults.@@ -254,6 +265,9 @@ func Load() (*Config, error) {CFAdminSecret: os.Getenv("OPENSANDBOX_CF_ADMIN_SECRET"),SessionJWTSecret: os.Getenv("OPENSANDBOX_SESSION_JWT_SECRET"),HaltListURL: os.Getenv("OPENSANDBOX_HALT_LIST_URL"),++ ComputeProvider: os.Getenv("OPENSANDBOX_COMPUTE_PROVIDER"),+ SecretsProvider: envOrDefault("OPENSANDBOX_SECRETS_PROVIDER", "env"),}if cfg.SentryEnvironment == "" {diff --git a/internal/secrets/backend.go b/internal/secrets/backend.gonew file mode 100644index 00000000..afd9b3cd--- /dev/null+++ b/internal/secrets/backend.go@@ -0,0 +1,43 @@+// Package secrets provides a cloud-neutral runtime secrets fetcher.+//+// Implementations:+// - EnvBackend (default; reads from OS env vars)+// - KeyVaultBackend (Azure Key Vault, in keyvault.go — build-tag isolated)+// - SecretsManagerBackend (AWS Secrets Manager, in secretsmanager.go — build-tag isolated)+//+// The CP picks a backend based on cfg.SecretsProvider at startup. Most+// callers can use the default Env backend; cloud-specific code paths+// (e.g., AzurePool's dynamic image refresh) take a Backend explicitly.+package secrets++import (+ "context"+ "errors"+ "os"+)++// ErrNotFound means the requested key has no value in this backend.+var ErrNotFound = errors.New("secret not found")++// Backend retrieves a single secret value by key. Implementations should be+// safe for concurrent use — they're typically goroutine-shared at startup.+type Backend interface {+ Get(ctx context.Context, key string) (string, error)+}++// EnvBackend reads secrets from process environment variables.+// Useful for local development and as a fallback when no cloud backend+// is configured.+type EnvBackend struct{}++// NewEnvBackend returns a Backend that reads from os.Getenv.+func NewEnvBackend() *EnvBackend { return &EnvBackend{} }++// Get returns the value of the env var named by key, or ErrNotFound.+func (b *EnvBackend) Get(_ context.Context, key string) (string, error) {+ v := os.Getenv(key)+ if v == "" {+ return "", ErrNotFound+ }+ return v, nil+}diff --git a/internal/secrets/json_bundle.go b/internal/secrets/json_bundle.gonew file mode 100644index 00000000..db9c159e--- /dev/null+++ b/internal/secrets/json_bundle.go@@ -0,0 +1,20 @@+package secrets++import (+ "encoding/json"+ "fmt"+)++// parseBundleJSON returns secrets[key] from a JSON-encoded object string.+// Used by Backend implementations that store multiple secrets per ARN/version.+func parseBundleJSON(s, key string) (string, error) {+ var bundle map[string]string+ if err := json.Unmarshal([]byte(s), &bundle); err != nil {+ return "", fmt.Errorf("secrets: bundle JSON parse: %w", err)+ }+ v, ok := bundle[key]+ if !ok {+ return "", fmt.Errorf("secrets: %w (key %q not in bundle)", ErrNotFound, key)+ }+ return v, nil+}diff --git a/internal/secrets/secretsmanager.go b/internal/secrets/secretsmanager.gonew file mode 100644index 00000000..655aab10--- /dev/null+++ b/internal/secrets/secretsmanager.go@@ -0,0 +1,105 @@+package secrets++import (+ "context"+ "fmt"+ "strings"++ awsconfig "github.com/aws/aws-sdk-go-v2/config"+ "github.com/aws/aws-sdk-go-v2/service/secretsmanager"+)++// SecretsManagerBackend reads secrets from AWS Secrets Manager.+//+// Two access patterns are supported:+//+// 1. Get("arn:aws:secretsmanager:us-east-1:123:secret:my-secret-XYZ") returns+// the SecretString of that secret directly. Useful when each secret is+// a single value.+//+// 2. Get("KEY_NAME") with BundledARN configured returns secrets[KEY_NAME]+// from a JSON-encoded bundle stored at BundledARN. Mirrors the existing+// OPENSANDBOX_SECRETS_ARN bootstrap pattern.+type SecretsManagerBackend struct {+ client *secretsmanager.Client+ bundledARN string // optional: JSON bundle keyed by secret name+}++// NewSecretsManagerBackend constructs a backend using the default AWS+// credential chain (IAM instance role preferred; env vars fallback).+//+// region may be empty — if so, derived from bundledARN or AWS_REGION env var.+// bundledARN may be empty if all callers pass full ARNs to Get.+func NewSecretsManagerBackend(ctx context.Context, region, bundledARN string) (*SecretsManagerBackend, error) {+ var opts []func(*awsconfig.LoadOptions) error+ if region != "" {+ opts = append(opts, awsconfig.WithRegion(region))+ } else if r := regionFromARN(bundledARN); r != "" {+ opts = append(opts, awsconfig.WithRegion(r))+ }+ cfg, err := awsconfig.LoadDefaultConfig(ctx, opts...)+ if err != nil {+ return nil, fmt.Errorf("secretsmanager: load AWS config: %w", err)+ }+ return &SecretsManagerBackend{+ client: secretsmanager.NewFromConfig(cfg),+ bundledARN: bundledARN,+ }, nil+}++// Get returns the secret value for key. If key looks like an ARN+// (starts with "arn:"), reads it as a standalone secret. Otherwise,+// reads BundledARN as a JSON bundle and returns secrets[key].+func (b *SecretsManagerBackend) Get(ctx context.Context, key string) (string, error) {+ if strings.HasPrefix(key, "arn:") {+ return b.getRaw(ctx, key)+ }+ if b.bundledARN == "" {+ return "", fmt.Errorf("secretsmanager: %w (key %q not an ARN and no BundledARN configured)", ErrNotFound, key)+ }+ bundle, err := b.getRaw(ctx, b.bundledARN)+ if err != nil {+ return "", err+ }+ v, err := lookupBundledSecret(bundle, key)+ if err != nil {+ return "", err+ }+ return v, nil+}++func (b *SecretsManagerBackend) getRaw(ctx context.Context, arn string) (string, error) {+ out, err := b.client.GetSecretValue(ctx, &secretsmanager.GetSecretValueInput{+ SecretId: &arn,+ })+ if err != nil {+ return "", fmt.Errorf("secretsmanager: GetSecretValue %s: %w", arn, err)+ }+ if out.SecretString == nil {+ return "", fmt.Errorf("secretsmanager: %s has no string value", arn)+ }+ return *out.SecretString, nil+}++// regionFromARN extracts the region from "arn:aws:secretsmanager:REGION:..."+func regionFromARN(arn string) string {+ if !strings.HasPrefix(arn, "arn:") {+ return ""+ }+ parts := strings.Split(arn, ":")+ if len(parts) < 4 {+ return ""+ }+ return parts[3]+}++// lookupBundledSecret parses a JSON object and returns the value for key.+// Implemented inline rather than encoding/json so the keyvault backend can+// reuse the same shape if needed.+func lookupBundledSecret(jsonStr, key string) (string, error) {+ // Minimal JSON parse: find "key":"value" pairs without bringing the full+ // encoding/json import path into a hot bootstrap path.+ // For simplicity here we DO use encoding/json — the perf concern is+ // premature.+ return parseBundleJSON(jsonStr, key)+}