An open-source, faster Devin alternative
TypeScript
Add PR preview environments, terraform infra, and EC2 deploy scripts
motatoesd48232640184
diff --git a/.github/workflows/preview-env-destroy.yml b/.github/workflows/preview-env-destroy.ymlnew file mode 100644index 00000000..3804a70f--- /dev/null+++ b/.github/workflows/preview-env-destroy.yml@@ -0,0 +1,79 @@+name: Preview Environment — Destroy++on:+ pull_request:+ types: [closed]++permissions:+ contents: read+ pull-requests: write+ id-token: write++env:+ ENV_NAME: dev-pr-${{ github.event.pull_request.number }}+ TF_DIR: deploy/terraform++concurrency:+ group: preview-env-${{ github.event.pull_request.number }}++jobs:+ destroy:+ name: Destroy Preview Environment+ runs-on: ubuntu-latest+ steps:+ - name: Checkout code+ uses: actions/checkout@v4++ - name: Setup Terraform+ uses: hashicorp/setup-terraform@v3+ with:+ terraform_wrapper: false++ - name: Configure AWS credentials (OIDC)+ uses: aws-actions/configure-aws-credentials@v4+ with:+ role-to-assume: ${{ secrets.AWS_ROLE_ARN }}+ aws-region: us-east-1++ - name: Terraform Init+ working-directory: ${{ env.TF_DIR }}+ run: |+ terraform init \+ -backend-config="bucket=${{ secrets.TF_STATE_BUCKET }}" \+ -backend-config="key=pr-${{ github.event.pull_request.number }}/terraform.tfstate" \+ -backend-config="dynamodb_table=${{ secrets.TF_LOCK_TABLE }}" \+ -backend-config="region=us-east-1"++ - name: Terraform Destroy+ working-directory: ${{ env.TF_DIR }}+ run: |+ terraform destroy -auto-approve \+ -var="environment=${{ env.ENV_NAME }}" \+ -var="key_pair_name=${{ secrets.KEY_PAIR_NAME || 'opensandbox-dev' }}" \+ -var="api_key=pr-${{ github.event.pull_request.number }}-key" \+ -var="jwt_secret=pr-${{ github.event.pull_request.number }}-jwt"++ - name: Clean up state from S3+ run: |+ aws s3 rm "s3://${{ secrets.TF_STATE_BUCKET }}/pr-${{ github.event.pull_request.number }}/" --recursive || true++ - name: Comment on PR+ uses: actions/github-script@v7+ with:+ script: |+ const prNumber = context.payload.pull_request.number;+ const merged = context.payload.pull_request.merged;+ const action = merged ? 'merged' : 'closed';+ const body = [+ `## Preview Environment Destroyed`,+ ``,+ `The preview environment \`${{ env.ENV_NAME }}\` has been torn down (PR ${action}).`,+ `All AWS resources for this environment have been cleaned up.`,+ ].join('\n');++ await github.rest.issues.createComment({+ owner: context.repo.owner,+ repo: context.repo.repo,+ issue_number: prNumber,+ body,+ });diff --git a/.github/workflows/preview-env.yml b/.github/workflows/preview-env.ymlnew file mode 100644index 00000000..7b0e8767--- /dev/null+++ b/.github/workflows/preview-env.yml@@ -0,0 +1,235 @@+name: Preview Environment — Deploy++on:+ pull_request:+ types: [opened, synchronize, reopened]++permissions:+ contents: read+ pull-requests: write+ id-token: write++env:+ ENV_NAME: dev-pr-${{ github.event.pull_request.number }}+ TF_DIR: deploy/terraform+ SSH_USER: ubuntu+ REMOTE_DIR: /home/ubuntu/opensandbox++concurrency:+ group: preview-env-${{ github.event.pull_request.number }}+ cancel-in-progress: true++jobs:+ deploy:+ name: Deploy Preview Environment+ runs-on: ubuntu-latest+ steps:+ - name: Checkout code+ uses: actions/checkout@v4++ - name: Setup Terraform+ uses: hashicorp/setup-terraform@v3+ with:+ terraform_wrapper: false++ - name: Configure AWS credentials (OIDC)+ uses: aws-actions/configure-aws-credentials@v4+ with:+ role-to-assume: ${{ secrets.AWS_ROLE_ARN }}+ aws-region: us-east-1++ - name: Terraform Init+ working-directory: ${{ env.TF_DIR }}+ run: |+ terraform init \+ -backend-config="bucket=${{ secrets.TF_STATE_BUCKET }}" \+ -backend-config="key=pr-${{ github.event.pull_request.number }}/terraform.tfstate" \+ -backend-config="dynamodb_table=${{ secrets.TF_LOCK_TABLE }}" \+ -backend-config="region=us-east-1"++ - name: Terraform Apply+ working-directory: ${{ env.TF_DIR }}+ run: |+ terraform apply -auto-approve \+ -var="environment=${{ env.ENV_NAME }}" \+ -var="key_pair_name=${{ secrets.KEY_PAIR_NAME || 'opensandbox-dev' }}" \+ -var="api_key=pr-${{ github.event.pull_request.number }}-key" \+ -var="jwt_secret=pr-${{ github.event.pull_request.number }}-jwt"++ - name: Get instance IP+ id: tf_output+ working-directory: ${{ env.TF_DIR }}+ run: |+ DEV_IP=$(terraform output -raw dev_host_public_ip)+ echo "dev_ip=$DEV_IP" >> "$GITHUB_OUTPUT"++ - name: Configure SSH+ run: |+ mkdir -p ~/.ssh+ echo "${{ secrets.PREVIEW_SSH_PRIVATE_KEY }}" > ~/.ssh/preview.pem+ chmod 600 ~/.ssh/preview.pem+ # Retry ssh-keyscan a few times while instance boots+ for i in 1 2 3 4 5; do+ ssh-keyscan -H ${{ steps.tf_output.outputs.dev_ip }} >> ~/.ssh/known_hosts 2>/dev/null && break+ echo "Waiting for SSH to become available (attempt $i)..."+ sleep 15+ done++ - name: Wait for instance to be ready+ run: |+ for i in $(seq 1 30); do+ if ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 -i ~/.ssh/preview.pem \+ ${{ env.SSH_USER }}@${{ steps.tf_output.outputs.dev_ip }} "echo ready" 2>/dev/null; then+ echo "Instance is ready"+ break+ fi+ echo "Waiting for instance... (attempt $i/30)"+ sleep 10+ done++ - name: Provision instance (idempotent)+ run: |+ ssh -o StrictHostKeyChecking=no -i ~/.ssh/preview.pem \+ ${{ env.SSH_USER }}@${{ steps.tf_output.outputs.dev_ip }} \+ "if command -v firecracker &>/dev/null; then echo 'Already provisioned, skipping'; else echo 'First deploy — running setup...'; fi"+ ssh -o StrictHostKeyChecking=no -i ~/.ssh/preview.pem \+ ${{ env.SSH_USER }}@${{ steps.tf_output.outputs.dev_ip }} \+ 'sudo bash -s' < deploy/ec2/setup-single-host.sh++ - name: Rsync repo to instance+ run: |+ rsync -az --delete \+ -e "ssh -o StrictHostKeyChecking=no -i ~/.ssh/preview.pem" \+ --exclude='.git' \+ --exclude='bin/' \+ --exclude='node_modules/' \+ --exclude='web/dist/' \+ --exclude='.claude/' \+ ./ ${{ env.SSH_USER }}@${{ steps.tf_output.outputs.dev_ip }}:${{ env.REMOTE_DIR }}/++ - name: Build binaries on instance+ run: |+ ssh -o StrictHostKeyChecking=no -i ~/.ssh/preview.pem \+ ${{ env.SSH_USER }}@${{ steps.tf_output.outputs.dev_ip }} "+ export PATH=\$PATH:/usr/local/go/bin+ cd ${{ env.REMOTE_DIR }}+ mkdir -p bin+ echo 'Building opensandbox-server...'+ CGO_ENABLED=0 go build -o bin/opensandbox-server ./cmd/server/+ echo 'Building opensandbox-worker...'+ CGO_ENABLED=0 go build -o bin/opensandbox-worker ./cmd/worker/+ echo 'Building osb-agent...'+ CGO_ENABLED=0 go build -o bin/osb-agent ./cmd/agent/+ sudo cp bin/opensandbox-server /usr/local/bin/opensandbox-server+ sudo cp bin/opensandbox-worker /usr/local/bin/opensandbox-worker+ sudo cp bin/osb-agent /usr/local/bin/osb-agent+ sudo chmod +x /usr/local/bin/opensandbox-server /usr/local/bin/opensandbox-worker /usr/local/bin/osb-agent+ echo 'Binaries installed'+ "++ - name: Build rootfs (idempotent)+ run: |+ ssh -o StrictHostKeyChecking=no -i ~/.ssh/preview.pem \+ ${{ env.SSH_USER }}@${{ steps.tf_output.outputs.dev_ip }} "+ if [ -f /data/firecracker/images/default.ext4 ]; then+ echo 'Rootfs already exists, skipping'+ else+ export PATH=\$PATH:/usr/local/go/bin+ cd ${{ env.REMOTE_DIR }}+ echo 'Building rootfs with Docker...'+ sudo bash ./deploy/ec2/build-rootfs-docker.sh /usr/local/bin/osb-agent /data/firecracker/images default+ fi+ "++ - name: Install env files and restart services+ run: |+ ssh -o StrictHostKeyChecking=no -i ~/.ssh/preview.pem \+ ${{ env.SSH_USER }}@${{ steps.tf_output.outputs.dev_ip }} "+ sudo bash ${{ env.REMOTE_DIR }}/deploy/ec2/setup-dev-env.sh 'pr-${{ github.event.pull_request.number }}-key'+ sudo systemctl restart opensandbox-server+ sudo systemctl restart opensandbox-worker+ echo 'Services restarted'+ "++ - name: Wait for services and seed database+ run: |+ sleep 5+ ssh -o StrictHostKeyChecking=no -i ~/.ssh/preview.pem \+ ${{ env.SSH_USER }}@${{ steps.tf_output.outputs.dev_ip }} "+ API_KEY='pr-${{ github.event.pull_request.number }}-key'+ for i in \$(seq 1 15); do+ sudo docker exec postgres psql -U opensandbox -d opensandbox -q -c 'SELECT 1 FROM orgs LIMIT 0' 2>/dev/null && break+ echo 'Waiting for migrations...'+ sleep 2+ done+ sudo docker exec postgres psql -U opensandbox -d opensandbox -q -c \"+ INSERT INTO orgs (name, slug) VALUES ('PR ${{ github.event.pull_request.number }}', 'pr-${{ github.event.pull_request.number }}') ON CONFLICT (slug) DO NOTHING;+ INSERT INTO api_keys (org_id, key_hash, key_prefix, name)+ SELECT id, encode(sha256('\${API_KEY}'::bytea), 'hex'), '\${API_KEY}', 'PR Key'+ FROM orgs WHERE slug = 'pr-${{ github.event.pull_request.number }}'+ ON CONFLICT (key_hash) DO NOTHING;+ \" && echo 'Database seeded' || echo 'WARNING: Seed failed'+ "++ - name: Health check+ run: |+ sleep 3+ ssh -o StrictHostKeyChecking=no -i ~/.ssh/preview.pem \+ ${{ env.SSH_USER }}@${{ steps.tf_output.outputs.dev_ip }} \+ "curl -sf http://localhost:8080/health > /dev/null 2>&1 && echo 'Server health: OK' || echo 'Server health: waiting...'"++ - name: Comment on PR+ uses: actions/github-script@v7+ with:+ script: |+ const ip = '${{ steps.tf_output.outputs.dev_ip }}';+ const prNumber = context.payload.pull_request.number;+ const apiKey = `pr-${prNumber}-key`;+ const body = [+ `## Preview Environment Ready`,+ ``,+ `| Resource | Value |`,+ `|----------|-------|`,+ `| **Server URL** | \`http://${ip}:8080\` |`,+ `| **API Key** | \`${apiKey}\` |`,+ `| **Environment** | \`${{ env.ENV_NAME }}\` |`,+ ``,+ `### Quick test`,+ `\`\`\`bash`,+ `curl -X POST http://${ip}:8080/api/sandboxes \\`,+ ` -H 'Content-Type: application/json' \\`,+ ` -H 'X-API-Key: ${apiKey}' \\`,+ ` -d '{"templateID":"default"}'`,+ `\`\`\``,+ ``,+ `### SSH access`,+ `\`\`\`bash`,+ `ssh -i ~/.ssh/opensandbox-dev.pem ubuntu@${ip}`,+ `\`\`\``,+ ``,+ `> This environment will be destroyed when the PR is closed or merged.`,+ ].join('\n');++ // Find and update existing comment, or create new one+ const marker = '## Preview Environment';+ const { data: comments } = await github.rest.issues.listComments({+ owner: context.repo.owner,+ repo: context.repo.repo,+ issue_number: prNumber,+ });+ const existing = comments.find(c => c.body.startsWith(marker));+ if (existing) {+ await github.rest.issues.updateComment({+ owner: context.repo.owner,+ repo: context.repo.repo,+ comment_id: existing.id,+ body,+ });+ } else {+ await github.rest.issues.createComment({+ owner: context.repo.owner,+ repo: context.repo.repo,+ issue_number: prNumber,+ body,+ });+ }diff --git a/.gitignore b/.gitignoreindex ed43e51b..333f3707 100644--- a/.gitignore+++ b/.gitignore@@ -43,6 +43,13 @@ sdks/typescript/examples/loom/*.mp4*.gif+# Terraform+deploy/terraform/.terraform/+deploy/terraform/.terraform.lock.hcl+deploy/terraform/terraform.tfstate*+deploy/terraform/terraform.tfvars+# Temp files*.tmp*.log+delmediff --git a/deploy/ec2/build-rootfs-docker.sh b/deploy/ec2/build-rootfs-docker.shnew file mode 100755index 00000000..06a3f7db--- /dev/null+++ b/deploy/ec2/build-rootfs-docker.sh@@ -0,0 +1,180 @@+#!/usr/bin/env bash+# build-rootfs-docker.sh — Build ext4 rootfs images using Docker (no Podman needed)+#+# Designed to run ON an EC2 instance (Amazon Linux 2023) where Podman isn't available.+# Uses Docker instead for the container build + export steps.+#+# Usage:+# sudo ./deploy/ec2/build-rootfs-docker.sh AGENT_BIN IMAGES_DIR [IMAGE_NAME]+#+# Example:+# sudo ./deploy/ec2/build-rootfs-docker.sh /usr/local/bin/osb-agent /data/firecracker/images default+#+# Requirements:+# - Docker (installed by user_data)+# - e2fsprogs (installed by user_data)+# - Root privileges (for mount/umount)++set -euo pipefail++AGENT_BIN="${1:?Usage: $0 AGENT_BIN IMAGES_DIR [IMAGE_NAME]}"+IMAGES_DIR="${2:?Usage: $0 AGENT_BIN IMAGES_DIR [IMAGE_NAME]}"+IMAGE_NAME="${3:-default}"+EXT4_SIZE_MB="${EXT4_SIZE_MB:-4096}"++SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"+DOCKERFILE_DIR="$PROJECT_ROOT/deploy/firecracker/rootfs"+DOCKERFILE="$DOCKERFILE_DIR/Dockerfile.${IMAGE_NAME}"++log() { echo "[build-rootfs-docker] $*"; }+err() { echo "[build-rootfs-docker] ERROR: $*" >&2; }++# Validate+if [ "$(id -u)" -ne 0 ]; then+ err "This script requires root privileges (for mount/umount)."+ err "Run with: sudo $0 $*"+ exit 1+fi++if [ ! -f "$AGENT_BIN" ]; then+ err "Agent binary not found: $AGENT_BIN"+ exit 1+fi++if [ ! -f "$DOCKERFILE" ]; then+ err "Dockerfile not found: $DOCKERFILE"+ exit 1+fi++command -v docker &>/dev/null || { err "Docker not found"; exit 1; }+command -v mkfs.ext4 &>/dev/null || { err "mkfs.ext4 not found (install e2fsprogs)"; exit 1; }++log "Building $IMAGE_NAME rootfs from $DOCKERFILE"++TMPDIR=$(mktemp -d /tmp/osb-rootfs-docker-XXXXXXXX)+trap 'rm -rf $TMPDIR' EXIT++# Copy Dockerfile to build context+cp "$DOCKERFILE" "$TMPDIR/Dockerfile"++# Copy agent binary+cp "$AGENT_BIN" "$TMPDIR/osb-agent"+chmod +x "$TMPDIR/osb-agent"++# Generate init script (same as scripts/build-rootfs.sh)+cat > "$TMPDIR/init" << 'INIT_EOF'+#!/bin/busybox sh+# OpenSandbox VM init script — PID 1 inside Firecracker microVM++mount -t proc proc /proc+mount -t sysfs sysfs /sys+mount -t devtmpfs devtmpfs /dev+mount -t tmpfs tmpfs /tmp+mount -t tmpfs tmpfs /run++[ -c /dev/null ] || mknod -m 666 /dev/null c 1 3+[ -c /dev/zero ] || mknod -m 666 /dev/zero c 1 5+[ -c /dev/random ] || mknod -m 444 /dev/random c 1 8+[ -c /dev/urandom ] || mknod -m 444 /dev/urandom c 1 9+[ -c /dev/tty ] || mknod -m 666 /dev/tty c 5 0+[ -c /dev/console ] || mknod -m 600 /dev/console c 5 1+[ -d /dev/pts ] || mkdir -p /dev/pts+mount -t devpts devpts /dev/pts+[ -d /dev/shm ] || mkdir -p /dev/shm+mount -t tmpfs tmpfs /dev/shm++mkdir -p /workspace+mount /dev/vdb /workspace 2>/dev/null || {+ echo "init: warning: could not mount /dev/vdb, trying /dev/vdb1"+ mount /dev/vdb1 /workspace 2>/dev/null || echo "init: warning: workspace mount failed"+}++for param in $(cat /proc/cmdline); do+ case "$param" in+ ip=*)+ IP_CONFIG="${param#ip=}"+ GUEST_IP=$(echo "$IP_CONFIG" | cut -d: -f1)+ GATEWAY=$(echo "$IP_CONFIG" | cut -d: -f3)+ NETMASK=$(echo "$IP_CONFIG" | cut -d: -f4)+ IFACE=$(echo "$IP_CONFIG" | cut -d: -f6)+ ;;+ osb.gateway=*)+ GATEWAY="${param#osb.gateway=}"+ ;;+ esac+done++if [ -n "$GUEST_IP" ] && [ -n "$IFACE" ]; then+ ip link set lo up+ ip addr add "${GUEST_IP}/30" dev "$IFACE"+ ip link set "$IFACE" up+ if [ -n "$GATEWAY" ]; then+ ip route add default via "$GATEWAY" dev "$IFACE"+ fi+fi++echo "nameserver 8.8.8.8" > /etc/resolv.conf+echo "nameserver 8.8.4.4" >> /etc/resolv.conf++hostname sandbox++exec /usr/local/bin/osb-agent+INIT_EOF+chmod +x "$TMPDIR/init"++# Append agent/init injection to Dockerfile+cat >> "$TMPDIR/Dockerfile" << 'INJECT_EOF'++# --- OpenSandbox agent injection ---+COPY osb-agent /usr/local/bin/osb-agent+RUN chmod +x /usr/local/bin/osb-agent+COPY init /sbin/init+RUN chmod +x /sbin/init+RUN mkdir -p /workspace+INJECT_EOF++# Build with Docker+log "Building container image..."+docker build -t "osb-rootfs-${IMAGE_NAME}:build" -f "$TMPDIR/Dockerfile" "$TMPDIR"++# Create container and export filesystem+log "Exporting filesystem..."+docker rm -f osb-rootfs-tmp 2>/dev/null || true+docker create --name osb-rootfs-tmp "osb-rootfs-${IMAGE_NAME}:build" /bin/true+docker export osb-rootfs-tmp -o "$TMPDIR/rootfs.tar"+docker rm -f osb-rootfs-tmp++# Convert tar to ext4+log "Converting to ext4 (${EXT4_SIZE_MB}MB sparse)..."+EXT4_PATH="$TMPDIR/rootfs.ext4"+truncate -s "${EXT4_SIZE_MB}M" "$EXT4_PATH"+mkfs.ext4 -q -F -L rootfs "$EXT4_PATH"++MNT_DIR="$TMPDIR/mnt"+mkdir -p "$MNT_DIR"+mount -o loop "$EXT4_PATH" "$MNT_DIR"++tar xf "$TMPDIR/rootfs.tar" -C "$MNT_DIR"++# Ensure key directories exist+for dir in proc sys dev dev/pts dev/shm tmp workspace run; do+ mkdir -p "$MNT_DIR/$dir"+done++sync+umount "$MNT_DIR"++# Shrink to minimum size+log "Shrinking ext4 image..."+resize2fs -M "$EXT4_PATH" 2>/dev/null || log "resize2fs -M failed (non-fatal)"++# Place in output directory+mkdir -p "$IMAGES_DIR"+cp "$EXT4_PATH" "$IMAGES_DIR/${IMAGE_NAME}.ext4"++# Clean up Docker image+docker rmi -f "osb-rootfs-${IMAGE_NAME}:build" &>/dev/null || true++FINAL_SIZE=$(du -h "$IMAGES_DIR/${IMAGE_NAME}.ext4" | cut -f1)+log "Done: $IMAGES_DIR/${IMAGE_NAME}.ext4 ($FINAL_SIZE)"diff --git a/deploy/ec2/deploy-single-host.sh b/deploy/ec2/deploy-single-host.shnew file mode 100755index 00000000..d0942089--- /dev/null+++ b/deploy/ec2/deploy-single-host.sh@@ -0,0 +1,306 @@+#!/usr/bin/env bash+set -euo pipefail++# Deploy OpenSandbox (server + worker) to a single EC2 instance.+#+# Run from repo root:+# WORKER_IP=54.167.9.152 ./deploy/ec2/deploy-single-host.sh+#+# Prerequisites:+# - Instance provisioned with: deploy/ec2/setup-single-host.sh+# - SSH access to the instance+#+# This script:+# 1. Provisions the instance (if --setup flag passed)+# 2. Rsyncs the repo to the instance+# 3. Builds server, worker, and agent binaries (on instance)+# 4. Starts PostgreSQL + Redis via Docker+# 5. Downloads the Firecracker kernel+# 6. Builds the default rootfs image+# 7. Starts the worker (port 8081, gRPC 9090)+# 8. Starts the server / control plane (port 8080)+# 9. Seeds test data and runs a smoke test++SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"++SSH_KEY="${SSH_KEY:-$HOME/.ssh/opensandbox-worker.pem}"+WORKER_IP="${WORKER_IP:?Set WORKER_IP to the EC2 instance public IP}"+SSH_USER="${SSH_USER:-ubuntu}"+SSH_OPTS="-o StrictHostKeyChecking=no -o ConnectTimeout=10"+SSH="ssh $SSH_OPTS -i $SSH_KEY $SSH_USER@$WORKER_IP"+SCP="scp $SSH_OPTS -i $SSH_KEY"++REMOTE_DIR="/home/${SSH_USER}/opensandbox"++# Detect instance architecture+REMOTE_ARCH=$($SSH "uname -m")+case "$REMOTE_ARCH" in+ x86_64) GOARCH="amd64"; KERNEL_SUFFIX="x86_64" ;;+ aarch64) GOARCH="arm64"; KERNEL_SUFFIX="arm64" ;;+ *) echo "ERROR: Unsupported architecture: $REMOTE_ARCH"; exit 1 ;;+esac+echo "==> Target: $WORKER_IP ($REMOTE_ARCH / $GOARCH)"++# ===================================================================+# Step 0 (optional): Provision the instance+# ===================================================================+if [[ "${1:-}" == "--setup" ]]; then+ echo "==> Step 0: Provisioning instance..."+ $SSH 'bash -s' < "$SCRIPT_DIR/setup-single-host.sh"+ echo "==> Provisioning complete. Re-run without --setup to deploy."+ exit 0+fi++# ===================================================================+# Step 1: Rsync the repo+# ===================================================================+echo "==> Step 1: Syncing repo to instance..."+rsync -az --delete \+ -e "ssh $SSH_OPTS -i $SSH_KEY" \+ --exclude='.git' \+ --exclude='bin/' \+ --exclude='node_modules/' \+ --exclude='web/dist/' \+ --exclude='.claude/' \+ --exclude='delme/' \+ "$REPO_ROOT/" "$SSH_USER@$WORKER_IP:$REMOTE_DIR/"+echo " Synced to $REMOTE_DIR"++# ===================================================================+# Step 2: Build binaries on instance+# ===================================================================+echo "==> Step 2: Building binaries on instance..."+$SSH "export PATH=\$PATH:/usr/local/go/bin && \+ cd $REMOTE_DIR && \+ mkdir -p bin && \+ echo ' Building opensandbox-server...' && \+ CGO_ENABLED=0 go build -o bin/opensandbox-server ./cmd/server/ && \+ echo ' Building opensandbox-worker...' && \+ CGO_ENABLED=0 go build -o bin/opensandbox-worker ./cmd/worker/ && \+ echo ' Building osb-agent...' && \+ CGO_ENABLED=0 go build -o bin/osb-agent ./cmd/agent/ && \+ echo ' Done:' && \+ ls -lh bin/opensandbox-server bin/opensandbox-worker bin/osb-agent"++# Install binaries+echo " Installing binaries..."+$SSH "sudo cp $REMOTE_DIR/bin/opensandbox-server /usr/local/bin/opensandbox-server && \+ sudo cp $REMOTE_DIR/bin/opensandbox-worker /usr/local/bin/opensandbox-worker && \+ sudo cp $REMOTE_DIR/bin/osb-agent /usr/local/bin/osb-agent && \+ sudo chmod +x /usr/local/bin/opensandbox-server /usr/local/bin/opensandbox-worker /usr/local/bin/osb-agent"++# ===================================================================+# Step 3: Start PostgreSQL + Redis via Docker+# ===================================================================+echo "==> Step 3: Starting PostgreSQL + Redis..."+$SSH 'docker rm -f postgres redis 2>/dev/null || true++echo " Starting PostgreSQL..."+docker run -d --name postgres --restart unless-stopped \+ -e POSTGRES_DB=opensandbox -e POSTGRES_USER=opensandbox -e POSTGRES_PASSWORD=opensandbox \+ -p 5432:5432 postgres:16-alpine++echo " Starting Redis..."+docker run -d --name redis --restart unless-stopped \+ -p 6379:6379 redis:7-alpine++echo " Waiting for PostgreSQL to be ready..."+for i in $(seq 1 30); do+ if docker exec postgres pg_isready -U opensandbox -q 2>/dev/null; then+ echo " PostgreSQL ready"+ break+ fi+ sleep 1+done++echo " Waiting for Redis to be ready..."+for i in $(seq 1 10); do+ if docker exec redis redis-cli ping 2>/dev/null | grep -q PONG; then+ echo " Redis ready"+ break+ fi+ sleep 1+done'++# ===================================================================+# Step 4: Download Firecracker kernel+# ===================================================================+echo "==> Step 4: Downloading Firecracker kernel..."+# Firecracker doesn't ship kernels in releases since v1.8+.+# Use the quickstart kernel from the Firecracker S3 bucket.+case "$REMOTE_ARCH" in+ x86_64) KERNEL_URL="https://s3.amazonaws.com/spec.ccfc.min/img/quickstart_guide/x86_64/kernels/vmlinux.bin" ;;+ aarch64) KERNEL_URL="https://s3.amazonaws.com/spec.ccfc.min/img/quickstart_guide/aarch64/kernels/vmlinux.bin" ;;+esac++$SSH "sudo mkdir -p /data/firecracker && \+ if [ -f /data/firecracker/vmlinux-${KERNEL_SUFFIX} ]; then+ echo ' Kernel already exists, skipping download'+ else+ echo ' Downloading kernel from ${KERNEL_URL}...'+ curl -fSL -o /tmp/vmlinux '${KERNEL_URL}' && \+ sudo mv /tmp/vmlinux /data/firecracker/vmlinux-${KERNEL_SUFFIX} && \+ echo ' Kernel installed: \$(ls -lh /data/firecracker/vmlinux-${KERNEL_SUFFIX})'+ fi"++# ===================================================================+# Step 5: Build rootfs image+# ===================================================================+echo "==> Step 5: Building default rootfs image..."+$SSH "export PATH=\$PATH:/usr/local/go/bin && \+ cd $REMOTE_DIR && \+ if [ -f /data/firecracker/images/default.ext4 ]; then+ echo ' Rootfs image already exists, skipping build'+ echo ' (delete /data/firecracker/images/default.ext4 to rebuild)'+ else+ echo ' Building rootfs (this takes a few minutes)...'+ sudo AGENT_BIN=$REMOTE_DIR/bin/osb-agent IMAGES_DIR=/data/firecracker/images \+ ./scripts/build-rootfs.sh default+ fi"++# ===================================================================+# Step 6: Stop existing services and start the worker+# ===================================================================+echo "==> Step 6: Starting worker..."++# Stop any existing instances+$SSH 'sudo systemctl stop opensandbox-worker 2>/dev/null || true+sudo systemctl stop opensandbox-server 2>/dev/null || true+# Kill any manually-started instances+sudo pkill -f "opensandbox-worker" 2>/dev/null || true+sudo pkill -f "opensandbox-server" 2>/dev/null || true+sleep 1'++# Write worker env file+$SSH "sudo tee /etc/opensandbox/worker.env > /dev/null << 'ENV'+HOME=/root+OPENSANDBOX_MODE=worker+OPENSANDBOX_PORT=8081+OPENSANDBOX_JWT_SECRET=dev-secret+OPENSANDBOX_WORKER_ID=w-test-1+OPENSANDBOX_REGION=use1+OPENSANDBOX_HTTP_ADDR=http://${WORKER_IP}:8081+OPENSANDBOX_GRPC_ADVERTISE=127.0.0.1:9090+OPENSANDBOX_DATA_DIR=/data/sandboxes+OPENSANDBOX_FIRECRACKER_BIN=/usr/local/bin/firecracker+OPENSANDBOX_KERNEL_PATH=/data/firecracker/vmlinux-${KERNEL_SUFFIX}+OPENSANDBOX_IMAGES_DIR=/data/firecracker/images+OPENSANDBOX_MAX_CAPACITY=10+OPENSANDBOX_DEFAULT_SANDBOX_MEMORY_MB=512+OPENSANDBOX_DEFAULT_SANDBOX_CPUS=1+OPENSANDBOX_REDIS_URL=redis://localhost:6379+DATABASE_URL=postgres://opensandbox:opensandbox@localhost:5432/opensandbox?sslmode=disable+ENV"++$SSH "sudo systemctl start opensandbox-worker"+echo " Worker starting on port 8081 (gRPC 9090)..."+sleep 3++# Check worker status+$SSH "sudo systemctl is-active opensandbox-worker && \+ echo ' Worker is running' || \+ (echo ' ERROR: Worker failed to start. Logs:' && sudo journalctl -u opensandbox-worker --no-pager -n 20 && exit 1)"++# ===================================================================+# Step 7: Start the server (control plane)+# ===================================================================+echo "==> Step 7: Starting server (control plane)..."++# Write server env file+$SSH "sudo tee /etc/opensandbox/server.env > /dev/null << 'ENV'+OPENSANDBOX_MODE=server+OPENSANDBOX_PORT=8080+OPENSANDBOX_API_KEY=test-key+OPENSANDBOX_JWT_SECRET=dev-secret+OPENSANDBOX_REGION=use1+OPENSANDBOX_WORKER_ID=cp-test-1+OPENSANDBOX_HTTP_ADDR=http://${WORKER_IP}:8080+OPENSANDBOX_DATA_DIR=/tmp/opensandbox-data+OPENSANDBOX_DATABASE_URL=postgres://opensandbox:opensandbox@localhost:5432/opensandbox?sslmode=disable+OPENSANDBOX_REDIS_URL=redis://localhost:6379+ENV"++$SSH "sudo systemctl start opensandbox-server"+echo " Server starting on port 8080..."+sleep 3++# Check server status+$SSH "sudo systemctl is-active opensandbox-server && \+ echo ' Server is running' || \+ (echo ' ERROR: Server failed to start. Logs:' && sudo journalctl -u opensandbox-server --no-pager -n 20 && exit 1)"++# ===================================================================+# Step 8: Seed test data and smoke test+# ===================================================================+echo "==> Step 8: Seeding test data and running smoke test..."++# Wait for migrations to complete+sleep 2++$SSH "PGPASSWORD=opensandbox psql -h localhost -U opensandbox -d opensandbox -q -c \"+ INSERT INTO orgs (name, slug) VALUES ('Test Org', 'test-org') ON CONFLICT (slug) DO NOTHING;+ INSERT INTO api_keys (org_id, key_hash, key_prefix, name)+ SELECT id, encode(sha256('test-key'::bytea), 'hex'), 'test-key', 'Dev Key'+ FROM orgs WHERE slug = 'test-org'+ ON CONFLICT (key_hash) DO NOTHING;+\" && echo ' Test org and API key seeded'"++# Verify worker registered in Redis+echo " Checking worker registration..."+$SSH 'docker exec redis redis-cli GET worker:w-test-1 | python3 -c "+import json, sys+data = json.loads(sys.stdin.read())+print(f\" Worker registered: id={data[\"worker_id\"]}, region={data[\"region\"]}, grpc={data[\"grpc_addr\"]}\")+" 2>/dev/null || echo " WARNING: Worker not yet registered in Redis (may need a few more seconds)"'++# Smoke test: create a sandbox+echo " Creating test sandbox..."+RESULT=$($SSH "curl -s -w '\n%{http_code}' -X POST http://localhost:8080/api/sandboxes \+ -H 'Content-Type: application/json' \+ -H 'X-API-Key: test-key' \+ -d '{\"templateID\":\"default\"}'")++HTTP_CODE=$(echo "$RESULT" | tail -1)+BODY=$(echo "$RESULT" | head -n -1)++if [ "$HTTP_CODE" = "200" ] || [ "$HTTP_CODE" = "201" ]; then+ SANDBOX_ID=$(echo "$BODY" | python3 -c "import json,sys; print(json.loads(sys.stdin.read()).get('sandboxID','?'))" 2>/dev/null || echo "?")+ echo " Sandbox created successfully (HTTP $HTTP_CODE): $SANDBOX_ID"++ # Execute a command in the sandbox to verify end-to-end+ echo " Executing test command..."+ sleep 2+ CMD_RESULT=$($SSH "curl -s -X POST http://localhost:8080/api/sandboxes/${SANDBOX_ID}/commands \+ -H 'Content-Type: application/json' \+ -H 'X-API-Key: test-key' \+ -d '{\"cmd\":\"echo Hello from Firecracker && uname -a\"}'")+ echo " $CMD_RESULT"+else+ echo " WARNING: Sandbox creation returned HTTP $HTTP_CODE"+ echo " $BODY"+fi++echo ""+echo "============================================"+echo " Deployment complete!"+echo ""+echo " Services:"+echo " Server (CP): http://$WORKER_IP:8080"+echo " Worker: http://$WORKER_IP:8081"+echo " Worker gRPC: $WORKER_IP:9090"+echo " PostgreSQL: localhost:5432"+echo " Redis: localhost:6379"+echo ""+echo " Test commands:"+echo " # Create sandbox:"+echo " curl -X POST http://$WORKER_IP:8080/api/sandboxes \\"+echo " -H 'Content-Type: application/json' \\"+echo " -H 'X-API-Key: test-key' \\"+echo " -d '{\"templateID\":\"default\"}'"+echo ""+echo " Logs:"+echo " ssh -i $SSH_KEY $SSH_USER@$WORKER_IP"+echo " sudo journalctl -u opensandbox-server -f"+echo " sudo journalctl -u opensandbox-worker -f"+echo "============================================"diff --git a/deploy/ec2/opensandbox-server.service b/deploy/ec2/opensandbox-server.servicenew file mode 100644index 00000000..dfeb9108--- /dev/null+++ b/deploy/ec2/opensandbox-server.service@@ -0,0 +1,14 @@+[Unit]+Description=OpenSandbox Server (Control Plane)+After=network-online.target+Wants=network-online.target++[Service]+Type=simple+ExecStart=/usr/local/bin/opensandbox-server+Restart=always+RestartSec=5+EnvironmentFile=/etc/opensandbox/server.env++[Install]+WantedBy=multi-user.targetdiff --git a/deploy/ec2/setup-dev-env.sh b/deploy/ec2/setup-dev-env.shnew file mode 100644index 00000000..0e44368a--- /dev/null+++ b/deploy/ec2/setup-dev-env.sh@@ -0,0 +1,60 @@+#!/usr/bin/env bash+# setup-dev-env.sh — Install env files + systemd units for dev deployment+# Called by: make deploy-dev (via SSH after rsync)+# Usage: sudo bash setup-dev-env.sh <API_KEY>+set -euo pipefail++API_KEY="${1:?Usage: $0 API_KEY}"+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"++# Get private IP via IMDSv2+TOKEN=$(curl -s -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")+PRIVATE_IP=$(curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/local-ipv4)++KERNEL_PATH="/opt/opensandbox/vmlinux"++# Create directories+mkdir -p /etc/opensandbox /opt/opensandbox /data/sandboxes /data/firecracker/images /data/checkpoints++# Server env+cat > /etc/opensandbox/server.env << EOF+OPENSANDBOX_MODE=server+OPENSANDBOX_PORT=8080+OPENSANDBOX_API_KEY=${API_KEY}+OPENSANDBOX_JWT_SECRET=dev-secret+OPENSANDBOX_HTTP_ADDR=http://0.0.0.0:8080+OPENSANDBOX_WORKER_ID=cp-dev-1+OPENSANDBOX_REGION=use1+OPENSANDBOX_DATABASE_URL=postgres://opensandbox:opensandbox@localhost:5432/opensandbox?sslmode=disable+OPENSANDBOX_REDIS_URL=redis://localhost:6379+EOF+chmod 644 /etc/opensandbox/server.env++# Worker env+cat > /etc/opensandbox/worker.env << EOF+HOME=/root+OPENSANDBOX_MODE=worker+OPENSANDBOX_PORT=8081+OPENSANDBOX_HTTP_ADDR=http://${PRIVATE_IP}:8081+OPENSANDBOX_GRPC_ADVERTISE=${PRIVATE_IP}:9090+OPENSANDBOX_JWT_SECRET=dev-secret+OPENSANDBOX_WORKER_ID=w-dev-1+OPENSANDBOX_REGION=use1+OPENSANDBOX_DATA_DIR=/data/sandboxes+OPENSANDBOX_FIRECRACKER_BIN=/usr/local/bin/firecracker+OPENSANDBOX_KERNEL_PATH=${KERNEL_PATH}+OPENSANDBOX_IMAGES_DIR=/data/firecracker/images+OPENSANDBOX_MAX_CAPACITY=10+OPENSANDBOX_DEFAULT_SANDBOX_MEMORY_MB=512+OPENSANDBOX_DEFAULT_SANDBOX_CPUS=1+OPENSANDBOX_REDIS_URL=redis://localhost:6379+DATABASE_URL=postgres://opensandbox:opensandbox@localhost:5432/opensandbox?sslmode=disable+EOF+chmod 644 /etc/opensandbox/worker.env++# Install systemd units from repo+cp "$SCRIPT_DIR/opensandbox-server.service" /etc/systemd/system/+cp "$SCRIPT_DIR/opensandbox-worker.service" /etc/systemd/system/+systemctl daemon-reload++echo "Env files and systemd units installed (private_ip=$PRIVATE_IP)"diff --git a/deploy/ec2/setup-single-host.sh b/deploy/ec2/setup-single-host.shnew file mode 100755index 00000000..2b2bc303--- /dev/null+++ b/deploy/ec2/setup-single-host.sh@@ -0,0 +1,258 @@+#!/usr/bin/env bash+set -euo pipefail++# setup-single-host.sh — Provision an Ubuntu 24.04 EC2 instance for OpenSandbox+#+# Runs BOTH control plane (server) and Firecracker worker on the same instance.+# This is the SINGLE source of truth for instance provisioning — both user_data+# (terraform) and manual setup call this script.+#+# Usage (manual):+# ssh -i key.pem ubuntu@<IP> 'bash -s' < deploy/ec2/setup-single-host.sh+#+# Usage (terraform user_data):+# Called automatically on first boot.+#+# What gets installed:+# - Docker (for PostgreSQL + Redis containers)+# - Go 1.24.1 (for building binaries on-instance)+# - Firecracker v1.9.1 (microVM runtime)+# - Firecracker kernel (from S3 quickstart bucket)+# - Podman + e2fsprogs (for rootfs builds)+# - PostgreSQL client (for seeding/debugging)+# - sysctl tuning + IP forwarding for VM networking+# - PostgreSQL + Redis containers+# - systemd units for server + worker+#+# Supports both x86_64 and aarch64.++# Detect architecture+ARCH=$(uname -m)+case "$ARCH" in+ x86_64) GOARCH="amd64"; FC_ARCH="x86_64" ;;+ aarch64) GOARCH="arm64"; FC_ARCH="aarch64" ;;+ *) echo "ERROR: Unsupported architecture: $ARCH"; exit 1 ;;+esac+echo "==> Detected architecture: $ARCH ($GOARCH)"++###############################################################################+# 1. System packages+###############################################################################+echo "==> Updating packages..."+export DEBIAN_FRONTEND=noninteractive+sudo apt-get update && sudo apt-get upgrade -y++echo "==> Installing build dependencies..."+sudo apt-get install -y e2fsprogs git podman uidmap slirp4netns postgresql-client++###############################################################################+# 2. Docker+###############################################################################+echo "==> Installing Docker..."+if ! command -v docker &>/dev/null; then+ curl -fsSL https://get.docker.com | sudo sh+ sudo usermod -aG docker "${USER}"+fi+sudo systemctl enable docker+sudo systemctl start docker+echo " Docker $(docker --version)"++###############################################################################+# 3. Go+###############################################################################+echo "==> Installing Go..."+GO_VERSION="1.24.1"+if [ ! -d /usr/local/go ] || ! /usr/local/go/bin/go version 2>/dev/null | grep -q "$GO_VERSION"; then+ curl -fSL -o /tmp/go.tar.gz "https://go.dev/dl/go${GO_VERSION}.linux-${GOARCH}.tar.gz"+ sudo rm -rf /usr/local/go+ sudo tar -C /usr/local -xzf /tmp/go.tar.gz+ rm -f /tmp/go.tar.gz+fi+# Make Go available system-wide+sudo tee /etc/profile.d/golang.sh > /dev/null << 'GOENV'+export GOROOT=/usr/local/go+export GOPATH=$HOME/go+export PATH=$GOROOT/bin:$GOPATH/bin:$PATH+GOENV+sudo chmod +x /etc/profile.d/golang.sh+export PATH=/usr/local/go/bin:$PATH+echo " Go $(/usr/local/go/bin/go version)"++###############################################################################+# 4. Firecracker+###############################################################################+echo "==> Installing Firecracker..."+FC_VERSION="v1.9.1"+if ! command -v firecracker &>/dev/null; then+ FC_RELEASE="firecracker-${FC_VERSION}-${FC_ARCH}"+ FC_URL="https://github.com/firecracker-microvm/firecracker/releases/download/${FC_VERSION}/${FC_RELEASE}.tgz"+ cd /tmp+ curl -fSL -o firecracker.tgz "$FC_URL"+ tar xzf firecracker.tgz+ sudo cp "release-${FC_VERSION}-${FC_ARCH}/firecracker-${FC_VERSION}-${FC_ARCH}" /usr/local/bin/firecracker+ sudo chmod +x /usr/local/bin/firecracker+ rm -rf firecracker.tgz "release-${FC_VERSION}-${FC_ARCH}"+ cd /+fi+echo " Firecracker $(firecracker --version 2>&1 | head -1)"++# Verify KVM access+if [ ! -e /dev/kvm ]; then+ echo "WARNING: /dev/kvm not found. Firecracker requires bare-metal or nested virt."+fi+sudo chmod 666 /dev/kvm 2>/dev/null || true++###############################################################################+# 5. Firecracker kernel+###############################################################################+echo "==> Downloading Firecracker kernel..."+sudo mkdir -p /opt/opensandbox+if [ ! -f /opt/opensandbox/vmlinux ]; then+ case "$ARCH" in+ x86_64) KERNEL_URL="https://s3.amazonaws.com/spec.ccfc.min/img/quickstart_guide/x86_64/kernels/vmlinux.bin" ;;+ aarch64) KERNEL_URL="https://s3.amazonaws.com/spec.ccfc.min/img/quickstart_guide/aarch64/kernels/vmlinux.bin" ;;+ esac+ sudo curl -fSL -o /opt/opensandbox/vmlinux "$KERNEL_URL"+ sudo chmod 644 /opt/opensandbox/vmlinux+ echo " Kernel downloaded: $(ls -lh /opt/opensandbox/vmlinux)"+else+ echo " Kernel already exists, skipping"+fi++###############################################################################+# 6. KVM modules + sysctl tuning+###############################################################################+echo "==> Configuring KVM and sysctl..."+sudo modprobe kvm || echo " kvm module not loadable (may be built-in)"+if [ "$ARCH" = "aarch64" ]; then+ sudo modprobe kvm_arm || true+else+ sudo modprobe kvm_intel || sudo modprobe kvm_amd || true+fi++sudo tee /etc/modules-load.d/kvm.conf > /dev/null << 'MODULES'+kvm+MODULES++sudo tee /etc/sysctl.d/99-opensandbox.conf > /dev/null << 'SYSCTL'+net.ipv4.ip_forward = 1+net.ipv4.neigh.default.gc_thresh1 = 1024+net.ipv4.neigh.default.gc_thresh2 = 4096+net.ipv4.neigh.default.gc_thresh3 = 8192+fs.file-max = 1000000+fs.inotify.max_user_instances = 8192+fs.inotify.max_user_watches = 524288+SYSCTL+sudo sysctl --system++###############################################################################+# 7. Create directory structure+###############################################################################+echo "==> Creating directory structure..."+sudo mkdir -p /data/sandboxes /data/firecracker/images /data/checkpoints /etc/opensandbox++###############################################################################+# 8. PostgreSQL + Redis containers+###############################################################################+echo "==> Starting PostgreSQL + Redis containers..."+if ! docker ps --format '{{.Names}}' | grep -q '^postgres$'; then+ docker rm -f postgres 2>/dev/null || true+ docker run -d \+ --name postgres \+ --restart unless-stopped \+ -p 5432:5432 \+ -e POSTGRES_USER=opensandbox \+ -e POSTGRES_PASSWORD=opensandbox \+ -e POSTGRES_DB=opensandbox \+ -v pgdata:/var/lib/postgresql/data \+ postgres:16+ echo " PostgreSQL started"+else+ echo " PostgreSQL already running"+fi++if ! docker ps --format '{{.Names}}' | grep -q '^redis$'; then+ docker rm -f redis 2>/dev/null || true+ docker run -d \+ --name redis \+ --restart unless-stopped \+ -p 6379:6379 \+ redis:7-alpine+ echo " Redis started"+else+ echo " Redis already running"+fi++echo " Waiting for PostgreSQL to be ready..."+for i in $(seq 1 30); do+ if docker exec postgres pg_isready -U opensandbox -q 2>/dev/null; then+ echo " PostgreSQL ready"+ break+ fi+ sleep 1+done++###############################################################################+# 9. Systemd units+###############################################################################+echo "==> Installing systemd units..."+sudo tee /etc/systemd/system/opensandbox-worker.service > /dev/null << 'SVC'+[Unit]+Description=OpenSandbox Worker (Firecracker)+After=network-online.target docker.service+Wants=network-online.target+Requires=docker.service++[Service]+Type=simple+ExecStartPre=/sbin/modprobe inet_diag+ExecStartPre=/sbin/modprobe tcp_diag+ExecStartPre=/sbin/modprobe udp_diag+ExecStartPre=/sbin/modprobe unix_diag+ExecStartPre=/sbin/modprobe netlink_diag+ExecStart=/usr/local/bin/opensandbox-worker+Restart=always+RestartSec=5+EnvironmentFile=/etc/opensandbox/worker.env+KillMode=process+TimeoutStopSec=300+LimitNOFILE=1000000+LimitNPROC=65536++[Install]+WantedBy=multi-user.target+SVC++sudo tee /etc/systemd/system/opensandbox-server.service > /dev/null << 'SVC'+[Unit]+Description=OpenSandbox Server (Control Plane)+After=network-online.target docker.service+Wants=network-online.target+Requires=docker.service++[Service]+Type=simple+ExecStart=/usr/local/bin/opensandbox-server+Restart=always+RestartSec=5+EnvironmentFile=/etc/opensandbox/server.env++[Install]+WantedBy=multi-user.target+SVC++sudo systemctl daemon-reload++echo ""+echo "============================================"+echo " Instance setup complete! ($ARCH)"+echo ""+echo " Installed:"+echo " - Firecracker $(firecracker --version 2>&1 | head -1)"+echo " - Docker $(docker --version | head -1)"+echo " - Podman $(podman --version)"+echo " - Go $(/usr/local/go/bin/go version | awk '{print $3}')"+echo " - Kernel: $(ls -lh /opt/opensandbox/vmlinux | awk '{print $5}')"+echo ""+echo " Next: run 'make deploy-dev' from your laptop"+echo "============================================"diff --git a/deploy/terraform/.gitignore b/deploy/terraform/.gitignorenew file mode 100644index 00000000..0b31fb34--- /dev/null+++ b/deploy/terraform/.gitignore@@ -0,0 +1,5 @@+terraform.tfvars+.terraform/+.terraform.lock.hcl+*.tfstate+*.tfstate.*diff --git a/deploy/terraform/backend-setup/main.tf b/deploy/terraform/backend-setup/main.tfnew file mode 100644index 00000000..20ca6dca--- /dev/null+++ b/deploy/terraform/backend-setup/main.tf@@ -0,0 +1,112 @@+# One-time bootstrap: creates the S3 bucket and DynamoDB lock table+# used by all PR preview environments.+#+# Usage:+# cd deploy/terraform/backend-setup+# terraform init+# terraform apply -var="bucket_name=opensandbox-tf-state" -var="lock_table_name=opensandbox-tf-lock"+#+# After applying, store the bucket name and table name as GitHub secrets:+# TF_STATE_BUCKET = <bucket_name>+# TF_LOCK_TABLE = <lock_table_name>++terraform {+ required_version = ">= 1.5.0"++ required_providers {+ aws = {+ source = "hashicorp/aws"+ version = ">= 6.0"+ }+ }+}++variable "aws_region" {+ description = "AWS region for the state bucket and lock table"+ type = string+ default = "us-east-1"+}++variable "bucket_name" {+ description = "S3 bucket name for Terraform state"+ type = string+}++variable "lock_table_name" {+ description = "DynamoDB table name for state locking"+ type = string+}++provider "aws" {+ region = var.aws_region++ default_tags {+ tags = {+ Project = "opensandbox"+ ManagedBy = "terraform"+ Purpose = "tf-state-backend"+ }+ }+}++resource "aws_s3_bucket" "tfstate" {+ bucket = var.bucket_name++ lifecycle {+ prevent_destroy = true+ }+}++resource "aws_s3_bucket_versioning" "tfstate" {+ bucket = aws_s3_bucket.tfstate.id++ versioning_configuration {+ status = "Enabled"+ }+}++resource "aws_s3_bucket_server_side_encryption_configuration" "tfstate" {+ bucket = aws_s3_bucket.tfstate.id++ rule {+ apply_server_side_encryption_by_default {+ sse_algorithm = "AES256"+ }+ }+}++resource "aws_s3_bucket_public_access_block" "tfstate" {+ bucket = aws_s3_bucket.tfstate.id++ block_public_acls = true+ block_public_policy = true+ ignore_public_acls = true+ restrict_public_buckets = true+}++resource "aws_dynamodb_table" "tflock" {+ name = var.lock_table_name+ billing_mode = "PAY_PER_REQUEST"+ hash_key = "LockID"++ attribute {+ name = "LockID"+ type = "S"+ }++ lifecycle {+ prevent_destroy = true+ }+}++output "bucket_name" {+ value = aws_s3_bucket.tfstate.bucket+}++output "lock_table_name" {+ value = aws_dynamodb_table.tflock.name+}++output "bucket_arn" {+ value = aws_s3_bucket.tfstate.arn+}diff --git a/deploy/terraform/backend.tf b/deploy/terraform/backend.tfnew file mode 100644index 00000000..8f08f6f5--- /dev/null+++ b/deploy/terraform/backend.tf@@ -0,0 +1,22 @@+# S3 backend for remote state — use partial configuration at init time.+#+# For PR preview environments:+# terraform init \+# -backend-config="bucket=$TF_STATE_BUCKET" \+# -backend-config="key=pr-<number>/terraform.tfstate" \+# -backend-config="dynamodb_table=$TF_LOCK_TABLE" \+# -backend-config="region=us-east-1"+#+# For local development (no remote state):+# Remove or comment out this block and use local state.++terraform {+ backend "s3" {+ # All values supplied via -backend-config at init time.+ # bucket = "..."+ # key = "..."+ # region = "..."+ # dynamodb_table = "..."+ encrypt = true+ }+}diff --git a/deploy/terraform/main.tf b/deploy/terraform/main.tfnew file mode 100644index 00000000..e54e6d93--- /dev/null+++ b/deploy/terraform/main.tf@@ -0,0 +1,183 @@+# --- Data Sources ---++data "aws_caller_identity" "current" {}+data "aws_region" "current" {}++# Look up latest Ubuntu 24.04 LTS x86_64 AMI if none provided+data "aws_ami" "ubuntu" {+ count = var.ami_id == "" ? 1 : 0+ most_recent = true+ owners = ["099720109477"] # Canonical++ filter {+ name = "name"+ values = ["ubuntu/images/hvm-ssd-gp3/ubuntu-noble-24.04-amd64-server-*"]+ }++ filter {+ name = "state"+ values = ["available"]+ }++ filter {+ name = "architecture"+ values = ["x86_64"]+ }+}++locals {+ ami_id = var.ami_id != "" ? var.ami_id : data.aws_ami.ubuntu[0].id+ is_dev = startswith(var.environment, "dev")+ is_prod = !startswith(var.environment, "dev")+ account_id = data.aws_caller_identity.current.account_id+ region = data.aws_region.current.region+}++# --- Always Created ---++module "networking" {+ source = "./modules/networking"++ project_name = var.project_name+ environment = var.environment+ vpc_cidr = var.vpc_cidr+ create_nat_gateway = local.is_prod+}++module "security" {+ source = "./modules/security"++ project_name = var.project_name+ environment = var.environment+ vpc_id = module.networking.vpc_id+ vpc_cidr_block = module.networking.vpc_cidr_block+}++# --- Dev Mode: Single Host (just VPC + SG + EC2) ---++module "dev_host" {+ count = local.is_dev ? 1 : 0+ source = "./modules/dev_host"++ project_name = var.project_name+ environment = var.environment+ subnet_id = module.networking.public_subnet_ids[0]+ security_group_id = module.security.dev_sg_id+ instance_type = var.dev_host_instance_type+ key_pair_name = var.key_pair_name+ ami_id = local.ami_id+}++# --- Prod Mode: Separate Components ---++module "ecr" {+ count = local.is_prod ? 1 : 0+ source = "./modules/ecr"++ project_name = var.project_name+ environment = var.environment+}++module "secrets" {+ count = local.is_prod ? 1 : 0+ source = "./modules/secrets"++ project_name = var.project_name+ environment = var.environment+ database_url = module.database[0].connection_url+ redis_url = module.redis[0].connection_url+ jwt_secret = var.jwt_secret+ api_key = var.api_key+ ecr_server_repo_arn = module.ecr[0].server_repo_arn+ ecr_worker_repo_arn = module.ecr[0].worker_repo_arn+}++module "database" {+ count = local.is_prod ? 1 : 0+ source = "./modules/database"++ project_name = var.project_name+ environment = var.environment+ subnet_ids = module.networking.private_subnet_ids+ security_group_id = module.security.rds_sg_id+ instance_class = var.db_instance_class+ db_name = var.db_name+ db_username = var.db_username+}++module "redis" {+ count = local.is_prod ? 1 : 0+ source = "./modules/redis"++ project_name = var.project_name+ environment = var.environment+ subnet_ids = module.networking.private_subnet_ids+ security_group_id = module.security.redis_sg_id+ node_type = var.redis_node_type+}++module "server" {+ count = local.is_prod ? 1 : 0+ source = "./modules/server"++ project_name = var.project_name+ environment = var.environment+ subnet_id = module.networking.private_subnet_ids[0]+ security_group_id = module.security.server_sg_id+ instance_type = var.server_instance_type+ key_pair_name = var.key_pair_name+ instance_profile_name = module.secrets[0].instance_profile_name+ server_secret_arn = module.secrets[0].server_secret_arn+ ecr_server_repo_url = module.ecr[0].server_repo_url+ server_image_tag = var.server_image_tag+ database_url = module.database[0].connection_url+ redis_url = module.redis[0].connection_url+ worker_private_ip = module.worker[0].private_ip+ ami_id = local.ami_id+}++module "alb" {+ count = local.is_prod ? 1 : 0+ source = "./modules/alb"++ project_name = var.project_name+ environment = var.environment+ vpc_id = module.networking.vpc_id+ subnet_ids = module.networking.public_subnet_ids+ security_group_id = module.security.alb_sg_id+ acm_certificate_arn = var.acm_certificate_arn+ server_instance_id = module.server[0].instance_id+}++# --- Route 53 alias record (prod only, when domain is configured) ---++resource "aws_route53_record" "app" {+ count = local.is_prod && var.hosted_zone_id != "" && var.domain_name != "" ? 1 : 0++ zone_id = var.hosted_zone_id+ name = var.domain_name+ type = "A"++ alias {+ name = module.alb[0].dns_name+ zone_id = module.alb[0].zone_id+ evaluate_target_health = true+ }+}++module "worker" {+ count = local.is_prod ? 1 : 0+ source = "./modules/worker"++ project_name = var.project_name+ environment = var.environment+ subnet_id = module.networking.private_subnet_ids[0]+ security_group_id = module.security.worker_sg_id+ instance_type = var.worker_instance_type+ key_pair_name = var.key_pair_name+ instance_profile_name = module.secrets[0].instance_profile_name+ worker_secret_arn = module.secrets[0].worker_secret_arn+ database_url = module.database[0].connection_url+ redis_url = module.redis[0].connection_url+ ami_id = local.ami_id+}diff --git a/deploy/terraform/modules/alb/main.tf b/deploy/terraform/modules/alb/main.tfnew file mode 100644index 00000000..7dc51866--- /dev/null+++ b/deploy/terraform/modules/alb/main.tf@@ -0,0 +1,125 @@+###############################################################################+# Locals+###############################################################################++locals {+ enable_https = var.acm_certificate_arn != ""++ common_tags = {+ Project = var.project_name+ Environment = var.environment+ ManagedBy = "terraform"+ }+}++###############################################################################+# Application Load Balancer+###############################################################################++resource "aws_lb" "main" {+ name = "${var.project_name}-${var.environment}-alb"+ internal = false+ load_balancer_type = "application"+ security_groups = [var.security_group_id]+ subnets = var.subnet_ids++ tags = merge(local.common_tags, {+ Name = "${var.project_name}-${var.environment}-alb"+ })+}++###############################################################################+# Target Group+###############################################################################++resource "aws_lb_target_group" "server" {+ name = "${var.project_name}-${var.environment}-tg"+ port = 8080+ protocol = "HTTP"+ vpc_id = var.vpc_id++ health_check {+ enabled = true+ path = "/health"+ port = "traffic-port"+ protocol = "HTTP"+ healthy_threshold = 3+ unhealthy_threshold = 3+ timeout = 5+ interval = 30+ matcher = "200"+ }++ tags = merge(local.common_tags, {+ Name = "${var.project_name}-${var.environment}-tg"+ })+}++###############################################################################+# Target Group Attachment+###############################################################################++resource "aws_lb_target_group_attachment" "server" {+ target_group_arn = aws_lb_target_group.server.arn+ target_id = var.server_instance_id+ port = 8080+}++###############################################################################+# HTTPS Listener (conditional — only when ACM certificate is provided)+###############################################################################++resource "aws_lb_listener" "https" {+ count = local.enable_https ? 1 : 0++ load_balancer_arn = aws_lb.main.arn+ port = 443+ protocol = "HTTPS"+ ssl_policy = "ELBSecurityPolicy-TLS13-1-2-2021-06"+ certificate_arn = var.acm_certificate_arn++ default_action {+ type = "forward"+ target_group_arn = aws_lb_target_group.server.arn+ }++ tags = merge(local.common_tags, {+ Name = "${var.project_name}-${var.environment}-https-listener"+ })+}++###############################################################################+# HTTP Listener — redirect to HTTPS when certificate is provided,+# otherwise forward directly to target group+###############################################################################++resource "aws_lb_listener" "http" {+ load_balancer_arn = aws_lb.main.arn+ port = 80+ protocol = "HTTP"++ dynamic "default_action" {+ for_each = local.enable_https ? [1] : []+ content {+ type = "redirect"++ redirect {+ port = "443"+ protocol = "HTTPS"+ status_code = "HTTP_301"+ }+ }+ }++ dynamic "default_action" {+ for_each = local.enable_https ? [] : [1]+ content {+ type = "forward"+ target_group_arn = aws_lb_target_group.server.arn+ }+ }++ tags = merge(local.common_tags, {+ Name = "${var.project_name}-${var.environment}-http-listener"+ })+}diff --git a/deploy/terraform/modules/alb/outputs.tf b/deploy/terraform/modules/alb/outputs.tfnew file mode 100644index 00000000..8d9c35ba--- /dev/null+++ b/deploy/terraform/modules/alb/outputs.tf@@ -0,0 +1,19 @@+output "dns_name" {+ description = "DNS name of the Application Load Balancer"+ value = aws_lb.main.dns_name+}++output "zone_id" {+ description = "Canonical hosted zone ID of the ALB (for Route 53 alias records)"+ value = aws_lb.main.zone_id+}++output "target_group_arn" {+ description = "ARN of the target group"+ value = aws_lb_target_group.server.arn+}++output "arn" {+ description = "ARN of the Application Load Balancer"+ value = aws_lb.main.arn+}diff --git a/deploy/terraform/modules/alb/variables.tf b/deploy/terraform/modules/alb/variables.tfnew file mode 100644index 00000000..27e013af--- /dev/null+++ b/deploy/terraform/modules/alb/variables.tf@@ -0,0 +1,35 @@+variable "project_name" {+ description = "Name of the project, used for resource naming and tagging"+ type = string+}++variable "environment" {+ description = "Deployment environment (e.g. dev, staging, prod)"+ type = string+}++variable "vpc_id" {+ description = "ID of the VPC where the ALB resources will be created"+ type = string+}++variable "subnet_ids" {+ description = "List of public subnet IDs for the ALB"+ type = list(string)+}++variable "security_group_id" {+ description = "Security group ID to attach to the ALB"+ type = string+}++variable "acm_certificate_arn" {+ description = "ARN of the ACM certificate for HTTPS. If empty, only HTTP listener is created"+ type = string+ default = ""+}++variable "server_instance_id" {+ description = "EC2 instance ID of the server to register in the target group"+ type = string+}diff --git a/deploy/terraform/modules/database/main.tf b/deploy/terraform/modules/database/main.tfnew file mode 100644index 00000000..4d6516d2--- /dev/null+++ b/deploy/terraform/modules/database/main.tf@@ -0,0 +1,43 @@+resource "random_password" "db_password" {+ length = 32+ special = false+}++resource "aws_db_subnet_group" "this" {+ name = "${var.project_name}-${var.environment}-db-subnet-group"+ subnet_ids = var.subnet_ids++ tags = {+ Name = "${var.project_name}-${var.environment}-db-subnet-group"+ Project = var.project_name+ Environment = var.environment+ }+}++resource "aws_db_instance" "this" {+ identifier = "${var.project_name}-${var.environment}-postgres"++ engine = "postgres"+ engine_version = "16"+ instance_class = var.instance_class++ allocated_storage = 20+ max_allocated_storage = 100+ storage_encrypted = true++ db_name = var.db_name+ username = var.db_username+ password = random_password.db_password.result++ db_subnet_group_name = aws_db_subnet_group.this.name+ vpc_security_group_ids = [var.security_group_id]++ multi_az = false+ skip_final_snapshot = true++ tags = {+ Name = "${var.project_name}-${var.environment}-postgres"+ Project = var.project_name+ Environment = var.environment+ }+}diff --git a/deploy/terraform/modules/database/outputs.tf b/deploy/terraform/modules/database/outputs.tfnew file mode 100644index 00000000..a5d33dde--- /dev/null+++ b/deploy/terraform/modules/database/outputs.tf@@ -0,0 +1,16 @@+output "endpoint" {+ description = "RDS instance endpoint (host:port)"+ value = aws_db_instance.this.endpoint+}++output "connection_url" {+ description = "Full PostgreSQL connection URL"+ value = "postgres://${aws_db_instance.this.username}:${random_password.db_password.result}@${aws_db_instance.this.endpoint}/${aws_db_instance.this.db_name}"+ sensitive = true+}++output "db_password" {+ description = "Generated database password"+ value = random_password.db_password.result+ sensitive = true+}diff --git a/deploy/terraform/modules/database/variables.tf b/deploy/terraform/modules/database/variables.tfnew file mode 100644index 00000000..5fd7d180--- /dev/null+++ b/deploy/terraform/modules/database/variables.tf@@ -0,0 +1,37 @@+variable "project_name" {+ description = "Name of the project, used for resource naming"+ type = string+}++variable "environment" {+ description = "Deployment environment (e.g. dev, staging, prod)"+ type = string+}++variable "subnet_ids" {+ description = "List of private subnet IDs for the DB subnet group"+ type = list(string)+}++variable "security_group_id" {+ description = "Security group ID to attach to the RDS instance"+ type = string+}++variable "instance_class" {+ description = "RDS instance class"+ type = string+ default = "db.t4g.micro"+}++variable "db_name" {+ description = "Name of the database to create"+ type = string+ default = "opensandbox"+}++variable "db_username" {+ description = "Master username for the database"+ type = string+ default = "opensandbox"+}diff --git a/deploy/terraform/modules/dev_host/main.tf b/deploy/terraform/modules/dev_host/main.tfnew file mode 100644index 00000000..f544f143--- /dev/null+++ b/deploy/terraform/modules/dev_host/main.tf@@ -0,0 +1,78 @@+###############################################################################+# Data Sources+###############################################################################++# Look up the latest Ubuntu 24.04 LTS x86_64 AMI when no ami_id is provided.+data "aws_ami" "ubuntu" {+ count = var.ami_id == "" ? 1 : 0+ most_recent = true+ owners = ["099720109477"] # Canonical++ filter {+ name = "name"+ values = ["ubuntu/images/hvm-ssd-gp3/ubuntu-noble-24.04-amd64-server-*"]+ }++ filter {+ name = "architecture"+ values = ["x86_64"]+ }++ filter {+ name = "virtualization-type"+ values = ["hvm"]+ }++ filter {+ name = "state"+ values = ["available"]+ }+}++###############################################################################+# Locals+###############################################################################++locals {+ ami_id = var.ami_id != "" ? var.ami_id : data.aws_ami.ubuntu[0].id++ common_tags = {+ Project = var.project_name+ Environment = var.environment+ ManagedBy = "terraform"+ }+}++###############################################################################+# EC2 Instance+###############################################################################++resource "aws_instance" "dev_host" {+ ami = local.ami_id+ instance_type = var.instance_type+ subnet_id = var.subnet_id+ vpc_security_group_ids = [var.security_group_id]+ key_name = var.key_pair_name++ associate_public_ip_address = true++ cpu_options {+ nested_virtualization = "enabled"+ }++ root_block_device {+ volume_size = 100+ volume_type = "gp3"+ delete_on_termination = true+ }++ # No user_data — run `make deploy-dev` after terraform apply to provision.++ tags = merge(local.common_tags, {+ Name = "${var.project_name}-${var.environment}-dev-host"+ })++ lifecycle {+ ignore_changes = [ami]+ }+}diff --git a/deploy/terraform/modules/dev_host/outputs.tf b/deploy/terraform/modules/dev_host/outputs.tfnew file mode 100644index 00000000..4f91f5c1--- /dev/null+++ b/deploy/terraform/modules/dev_host/outputs.tf@@ -0,0 +1,14 @@+output "instance_id" {+ description = "ID of the dev host EC2 instance"+ value = aws_instance.dev_host.id+}++output "public_ip" {+ description = "Public IP address of the dev host"+ value = aws_instance.dev_host.public_ip+}++output "private_ip" {+ description = "Private IP address of the dev host"+ value = aws_instance.dev_host.private_ip+}diff --git a/deploy/terraform/modules/dev_host/variables.tf b/deploy/terraform/modules/dev_host/variables.tfnew file mode 100644index 00000000..c95b46fd--- /dev/null+++ b/deploy/terraform/modules/dev_host/variables.tf@@ -0,0 +1,35 @@+variable "project_name" {+ description = "Name of the project, used as a prefix for resource naming"+ type = string+}++variable "environment" {+ description = "Deployment environment (e.g. dev, staging, prod)"+ type = string+}++variable "subnet_id" {+ description = "ID of the public subnet to launch the instance in"+ type = string+}++variable "security_group_id" {+ description = "ID of the security group to attach to the instance"+ type = string+}++variable "instance_type" {+ description = "EC2 instance type (must be bare-metal for Firecracker KVM, e.g. c6g.metal)"+ type = string+}++variable "key_pair_name" {+ description = "Name of the EC2 key pair for SSH access"+ type = string+}++variable "ami_id" {+ description = "AMI ID to use. If empty, the latest Ubuntu 24.04 LTS x86_64 AMI is looked up automatically."+ type = string+ default = ""+}diff --git a/deploy/terraform/modules/ecr/main.tf b/deploy/terraform/modules/ecr/main.tfnew file mode 100644index 00000000..e4fefd1e--- /dev/null+++ b/deploy/terraform/modules/ecr/main.tf@@ -0,0 +1,61 @@+resource "aws_ecr_repository" "server" {+ name = "${var.project_name}-${var.environment}-server"+ image_tag_mutability = "MUTABLE"+ force_delete = true++ image_scanning_configuration {+ scan_on_push = true+ }+}++resource "aws_ecr_repository" "worker" {+ name = "${var.project_name}-${var.environment}-worker"+ image_tag_mutability = "MUTABLE"+ force_delete = true++ image_scanning_configuration {+ scan_on_push = true+ }+}++resource "aws_ecr_lifecycle_policy" "server" {+ repository = aws_ecr_repository.server.name++ policy = jsonencode({+ rules = [+ {+ rulePriority = 1+ description = "Keep last 10 untagged images"+ selection = {+ tagStatus = "untagged"+ countType = "imageCountMoreThan"+ countNumber = 10+ }+ action = {+ type = "expire"+ }+ }+ ]+ })+}++resource "aws_ecr_lifecycle_policy" "worker" {+ repository = aws_ecr_repository.worker.name++ policy = jsonencode({+ rules = [+ {+ rulePriority = 1+ description = "Keep last 10 untagged images"+ selection = {+ tagStatus = "untagged"+ countType = "imageCountMoreThan"+ countNumber = 10+ }+ action = {+ type = "expire"+ }+ }+ ]+ })+}diff --git a/deploy/terraform/modules/ecr/outputs.tf b/deploy/terraform/modules/ecr/outputs.tfnew file mode 100644index 00000000..bafa3752--- /dev/null+++ b/deploy/terraform/modules/ecr/outputs.tf@@ -0,0 +1,19 @@+output "server_repo_url" {+ description = "The URL of the server ECR repository"+ value = aws_ecr_repository.server.repository_url+}++output "worker_repo_url" {+ description = "The URL of the worker ECR repository"+ value = aws_ecr_repository.worker.repository_url+}++output "server_repo_arn" {+ description = "The ARN of the server ECR repository"+ value = aws_ecr_repository.server.arn+}++output "worker_repo_arn" {+ description = "The ARN of the worker ECR repository"+ value = aws_ecr_repository.worker.arn+}diff --git a/deploy/terraform/modules/ecr/variables.tf b/deploy/terraform/modules/ecr/variables.tfnew file mode 100644index 00000000..f3a6c4f5--- /dev/null+++ b/deploy/terraform/modules/ecr/variables.tf@@ -0,0 +1,9 @@+variable "project_name" {+ description = "The name of the project, used as a prefix for ECR repository names"+ type = string+}++variable "environment" {+ description = "The deployment environment (e.g. dev, staging, prod)"+ type = string+}diff --git a/deploy/terraform/modules/networking/main.tf b/deploy/terraform/modules/networking/main.tfnew file mode 100644index 00000000..32f724d0--- /dev/null+++ b/deploy/terraform/modules/networking/main.tf@@ -0,0 +1,158 @@+###############################################################################+# Data Sources+###############################################################################++data "aws_availability_zones" "available" {+ state = "available"+}++locals {+ azs = slice(data.aws_availability_zones.available.names, 0, 2)++ public_subnet_cidrs = ["10.0.1.0/24", "10.0.2.0/24"]+ private_subnet_cidrs = ["10.0.10.0/24", "10.0.11.0/24"]++ common_tags = {+ Project = var.project_name+ Environment = var.environment+ ManagedBy = "terraform"+ }+}++###############################################################################+# VPC+###############################################################################++resource "aws_vpc" "main" {+ cidr_block = var.vpc_cidr+ enable_dns_support = true+ enable_dns_hostnames = true++ tags = merge(local.common_tags, {+ Name = "${var.project_name}-${var.environment}-vpc"+ })+}++###############################################################################+# Internet Gateway+###############################################################################++resource "aws_internet_gateway" "main" {+ vpc_id = aws_vpc.main.id++ tags = merge(local.common_tags, {+ Name = "${var.project_name}-${var.environment}-igw"+ })+}++###############################################################################+# Public Subnets+###############################################################################++resource "aws_subnet" "public" {+ count = 2++ vpc_id = aws_vpc.main.id+ cidr_block = local.public_subnet_cidrs[count.index]+ availability_zone = local.azs[count.index]+ map_public_ip_on_launch = true++ tags = merge(local.common_tags, {+ Name = "${var.project_name}-${var.environment}-public-${local.azs[count.index]}"+ Tier = "public"+ })+}++###############################################################################+# Private Subnets+###############################################################################++resource "aws_subnet" "private" {+ count = 2++ vpc_id = aws_vpc.main.id+ cidr_block = local.private_subnet_cidrs[count.index]+ availability_zone = local.azs[count.index]++ tags = merge(local.common_tags, {+ Name = "${var.project_name}-${var.environment}-private-${local.azs[count.index]}"+ Tier = "private"+ })+}++###############################################################################+# NAT Gateway (conditional — prod mode only)+###############################################################################++resource "aws_eip" "nat" {+ count = var.create_nat_gateway ? 1 : 0+ domain = "vpc"++ tags = merge(local.common_tags, {+ Name = "${var.project_name}-${var.environment}-nat-eip"+ })+}++resource "aws_nat_gateway" "main" {+ count = var.create_nat_gateway ? 1 : 0++ allocation_id = aws_eip.nat[0].id+ subnet_id = aws_subnet.public[0].id++ tags = merge(local.common_tags, {+ Name = "${var.project_name}-${var.environment}-nat-gw"+ })++ depends_on = [aws_internet_gateway.main]+}++###############################################################################+# Public Route Table+###############################################################################++resource "aws_route_table" "public" {+ vpc_id = aws_vpc.main.id++ route {+ cidr_block = "0.0.0.0/0"+ gateway_id = aws_internet_gateway.main.id+ }++ tags = merge(local.common_tags, {+ Name = "${var.project_name}-${var.environment}-public-rt"+ })+}++resource "aws_route_table_association" "public" {+ count = 2++ subnet_id = aws_subnet.public[count.index].id+ route_table_id = aws_route_table.public.id+}++###############################################################################+# Private Route Table+###############################################################################++resource "aws_route_table" "private" {+ vpc_id = aws_vpc.main.id++ tags = merge(local.common_tags, {+ Name = "${var.project_name}-${var.environment}-private-rt"+ })+}++resource "aws_route" "private_nat" {+ count = var.create_nat_gateway ? 1 : 0++ route_table_id = aws_route_table.private.id+ destination_cidr_block = "0.0.0.0/0"+ nat_gateway_id = aws_nat_gateway.main[0].id+}++resource "aws_route_table_association" "private" {+ count = 2++ subnet_id = aws_subnet.private[count.index].id+ route_table_id = aws_route_table.private.id+}diff --git a/deploy/terraform/modules/networking/outputs.tf b/deploy/terraform/modules/networking/outputs.tfnew file mode 100644index 00000000..78699fbc--- /dev/null+++ b/deploy/terraform/modules/networking/outputs.tf@@ -0,0 +1,24 @@+output "vpc_id" {+ description = "ID of the VPC"+ value = aws_vpc.main.id+}++output "vpc_cidr_block" {+ description = "CIDR block of the VPC"+ value = aws_vpc.main.cidr_block+}++output "public_subnet_ids" {+ description = "List of public subnet IDs"+ value = aws_subnet.public[*].id+}++output "private_subnet_ids" {+ description = "List of private subnet IDs"+ value = aws_subnet.private[*].id+}++output "availability_zones" {+ description = "List of availability zones used"+ value = local.azs+}diff --git a/deploy/terraform/modules/networking/variables.tf b/deploy/terraform/modules/networking/variables.tfnew file mode 100644index 00000000..bae4a3f4--- /dev/null+++ b/deploy/terraform/modules/networking/variables.tf@@ -0,0 +1,21 @@+variable "project_name" {+ description = "Name of the project, used for resource naming and tagging"+ type = string+}++variable "environment" {+ description = "Deployment environment (e.g. dev, staging, prod)"+ type = string+}++variable "vpc_cidr" {+ description = "CIDR block for the VPC"+ type = string+ default = "10.0.0.0/16"+}++variable "create_nat_gateway" {+ description = "Whether to create a NAT Gateway for private subnet internet access (typically true for prod)"+ type = bool+ default = false+}diff --git a/deploy/terraform/modules/redis/main.tf b/deploy/terraform/modules/redis/main.tfnew file mode 100644index 00000000..c8289923--- /dev/null+++ b/deploy/terraform/modules/redis/main.tf@@ -0,0 +1,32 @@+resource "aws_elasticache_subnet_group" "this" {+ name = "${var.project_name}-${var.environment}-redis"+ subnet_ids = var.subnet_ids++ tags = {+ Name = "${var.project_name}-${var.environment}-redis"+ Project = var.project_name+ Environment = var.environment+ }+}++resource "aws_elasticache_replication_group" "this" {+ replication_group_id = "${var.project_name}-${var.environment}"+ description = "Redis cluster for ${var.project_name} ${var.environment}"++ engine = "redis"+ engine_version = "7.0"+ node_type = var.node_type+ num_cache_clusters = 1+ automatic_failover_enabled = false++ subnet_group_name = aws_elasticache_subnet_group.this.name+ security_group_ids = [var.security_group_id]++ port = 6379++ tags = {+ Name = "${var.project_name}-${var.environment}-redis"+ Project = var.project_name+ Environment = var.environment+ }+}diff --git a/deploy/terraform/modules/redis/outputs.tf b/deploy/terraform/modules/redis/outputs.tfnew file mode 100644index 00000000..d0f58ea8--- /dev/null+++ b/deploy/terraform/modules/redis/outputs.tf@@ -0,0 +1,9 @@+output "endpoint" {+ description = "Primary endpoint address of the Redis replication group"+ value = aws_elasticache_replication_group.this.primary_endpoint_address+}++output "connection_url" {+ description = "Full Redis connection URL"+ value = "redis://${aws_elasticache_replication_group.this.primary_endpoint_address}:6379"+}diff --git a/deploy/terraform/modules/redis/variables.tf b/deploy/terraform/modules/redis/variables.tfnew file mode 100644index 00000000..18bcbeec--- /dev/null+++ b/deploy/terraform/modules/redis/variables.tf@@ -0,0 +1,25 @@+variable "project_name" {+ description = "Name of the project, used for resource naming"+ type = string+}++variable "environment" {+ description = "Deployment environment (e.g. dev, staging, prod)"+ type = string+}++variable "subnet_ids" {+ description = "List of private subnet IDs for the ElastiCache subnet group"+ type = list(string)+}++variable "security_group_id" {+ description = "Security group ID to attach to the Redis cluster"+ type = string+}++variable "node_type" {+ description = "ElastiCache node instance type"+ type = string+ default = "cache.t4g.micro"+}diff --git a/deploy/terraform/modules/secrets/main.tf b/deploy/terraform/modules/secrets/main.tfnew file mode 100644index 00000000..66db65fe--- /dev/null+++ b/deploy/terraform/modules/secrets/main.tf@@ -0,0 +1,108 @@+###############################################################################+# Secrets Manager – server secret+###############################################################################+resource "aws_secretsmanager_secret" "server" {+ name = "${var.project_name}-${var.environment}-server"+ description = "Server secrets for ${var.project_name} ${var.environment}"+ recovery_window_in_days = 0+}++resource "aws_secretsmanager_secret_version" "server" {+ secret_id = aws_secretsmanager_secret.server.id+ secret_string = jsonencode({+ OPENSANDBOX_DATABASE_URL = var.database_url+ OPENSANDBOX_REDIS_URL = var.redis_url+ OPENSANDBOX_JWT_SECRET = var.jwt_secret+ OPENSANDBOX_API_KEY = var.api_key+ })+}++###############################################################################+# Secrets Manager – worker secret+###############################################################################+resource "aws_secretsmanager_secret" "worker" {+ name = "${var.project_name}-${var.environment}-worker"+ description = "Worker secrets for ${var.project_name} ${var.environment}"+ recovery_window_in_days = 0+}++resource "aws_secretsmanager_secret_version" "worker" {+ secret_id = aws_secretsmanager_secret.worker.id+ secret_string = jsonencode({+ OPENSANDBOX_JWT_SECRET = var.jwt_secret+ DATABASE_URL = var.database_url+ OPENSANDBOX_REDIS_URL = var.redis_url+ })+}++###############################################################################+# IAM role for EC2 instances+###############################################################################+data "aws_iam_policy_document" "ec2_assume_role" {+ statement {+ effect = "Allow"+ actions = ["sts:AssumeRole"]++ principals {+ type = "Service"+ identifiers = ["ec2.amazonaws.com"]+ }+ }+}++resource "aws_iam_role" "ec2_opensandbox" {+ name = "ec2-opensandbox-${var.environment}"+ assume_role_policy = data.aws_iam_policy_document.ec2_assume_role.json+}++###############################################################################+# Inline policy – secrets, ECR, S3+###############################################################################+data "aws_iam_policy_document" "ec2_permissions" {+ # Secrets Manager access – scoped to the two secrets+ statement {+ effect = "Allow"+ actions = [+ "secretsmanager:GetSecretValue",+ ]+ resources = [+ aws_secretsmanager_secret.server.arn,+ aws_secretsmanager_secret.worker.arn,+ ]+ }++ # ECR access – token + image pull+ statement {+ effect = "Allow"+ actions = [+ "ecr:GetAuthorizationToken",+ "ecr:BatchGetImage",+ "ecr:GetDownloadUrlForLayer",+ ]+ resources = ["*"]+ }++ # S3 access – rootfs / kernel storage+ statement {+ effect = "Allow"+ actions = [+ "s3:GetObject",+ "s3:PutObject",+ ]+ resources = ["*"]+ }+}++resource "aws_iam_role_policy" "ec2_opensandbox" {+ name = "ec2-opensandbox-${var.environment}-policy"+ role = aws_iam_role.ec2_opensandbox.id+ policy = data.aws_iam_policy_document.ec2_permissions.json+}++###############################################################################+# Instance profile+###############################################################################+resource "aws_iam_instance_profile" "ec2_opensandbox" {+ name = "ec2-opensandbox-${var.environment}"+ role = aws_iam_role.ec2_opensandbox.name+}diff --git a/deploy/terraform/modules/secrets/outputs.tf b/deploy/terraform/modules/secrets/outputs.tfnew file mode 100644index 00000000..443d3b4f--- /dev/null+++ b/deploy/terraform/modules/secrets/outputs.tf@@ -0,0 +1,19 @@+output "server_secret_arn" {+ description = "ARN of the server Secrets Manager secret"+ value = aws_secretsmanager_secret.server.arn+}++output "worker_secret_arn" {+ description = "ARN of the worker Secrets Manager secret"+ value = aws_secretsmanager_secret.worker.arn+}++output "instance_profile_name" {+ description = "Name of the IAM instance profile for EC2 instances"+ value = aws_iam_instance_profile.ec2_opensandbox.name+}++output "iam_role_arn" {+ description = "ARN of the IAM role for EC2 instances"+ value = aws_iam_role.ec2_opensandbox.arn+}diff --git a/deploy/terraform/modules/secrets/variables.tf b/deploy/terraform/modules/secrets/variables.tfnew file mode 100644index 00000000..270d50b2--- /dev/null+++ b/deploy/terraform/modules/secrets/variables.tf@@ -0,0 +1,43 @@+variable "project_name" {+ description = "Name of the project, used as a prefix for resource naming"+ type = string+}++variable "environment" {+ description = "Deployment environment (e.g. dev, staging, prod)"+ type = string+}++variable "database_url" {+ description = "PostgreSQL connection string for the server"+ type = string+ sensitive = true+}++variable "redis_url" {+ description = "Redis connection string"+ type = string+ sensitive = true+}++variable "jwt_secret" {+ description = "JWT signing secret shared between server and worker"+ type = string+ sensitive = true+}++variable "api_key" {+ description = "API key for the server"+ type = string+ sensitive = true+}++variable "ecr_server_repo_arn" {+ description = "ARN of the ECR repository for server images"+ type = string+}++variable "ecr_worker_repo_arn" {+ description = "ARN of the ECR repository for worker images"+ type = string+}diff --git a/deploy/terraform/modules/security/main.tf b/deploy/terraform/modules/security/main.tfnew file mode 100644index 00000000..7588f173--- /dev/null+++ b/deploy/terraform/modules/security/main.tf@@ -0,0 +1,276 @@+###############################################################################+# Security module — conditional SG creation based on environment+#+# Dev mode (var.environment == "dev"): single permissive SG+# Prod mode (var.environment != "dev"): ALB, Server, Worker, RDS, Redis SGs+###############################################################################++locals {+ is_dev = startswith(var.environment, "dev")+ is_prod = !local.is_dev+}++###############################################################################+# DEV MODE — single security group+###############################################################################++resource "aws_security_group" "dev" {+ count = local.is_dev ? 1 : 0++ name = "${var.project_name}-${var.environment}-dev-sg"+ description = "Dev-mode security group: API + SSH inbound, all outbound"+ vpc_id = var.vpc_id++ # Server API+ ingress {+ description = "Server API"+ from_port = 8080+ to_port = 8080+ protocol = "tcp"+ cidr_blocks = ["0.0.0.0/0"]+ }++ # SSH+ ingress {+ description = "SSH"+ from_port = 22+ to_port = 22+ protocol = "tcp"+ cidr_blocks = ["0.0.0.0/0"]+ }++ # All outbound+ egress {+ description = "All outbound"+ from_port = 0+ to_port = 0+ protocol = "-1"+ cidr_blocks = ["0.0.0.0/0"]+ }++ tags = {+ Name = "${var.project_name}-${var.environment}-dev-sg"+ Environment = var.environment+ }+}++###############################################################################+# PROD MODE — ALB security group+###############################################################################++resource "aws_security_group" "alb" {+ count = local.is_prod ? 1 : 0++ name = "${var.project_name}-${var.environment}-alb-sg"+ description = "ALB security group: HTTP + HTTPS inbound"+ vpc_id = var.vpc_id++ ingress {+ description = "HTTP"+ from_port = 80+ to_port = 80+ protocol = "tcp"+ cidr_blocks = ["0.0.0.0/0"]+ }++ ingress {+ description = "HTTPS"+ from_port = 443+ to_port = 443+ protocol = "tcp"+ cidr_blocks = ["0.0.0.0/0"]+ }++ egress {+ description = "All outbound"+ from_port = 0+ to_port = 0+ protocol = "-1"+ cidr_blocks = ["0.0.0.0/0"]+ }++ tags = {+ Name = "${var.project_name}-${var.environment}-alb-sg"+ Environment = var.environment+ }+}++###############################################################################+# PROD MODE — Server security group+###############################################################################++resource "aws_security_group" "server" {+ count = local.is_prod ? 1 : 0++ name = "${var.project_name}-${var.environment}-server-sg"+ description = "Server security group: API from ALB, SSH from VPC"+ vpc_id = var.vpc_id++ ingress {+ description = "API from ALB"+ from_port = 8080+ to_port = 8080+ protocol = "tcp"+ security_groups = [aws_security_group.alb[0].id]+ }++ ingress {+ description = "SSH from VPC"+ from_port = 22+ to_port = 22+ protocol = "tcp"+ cidr_blocks = [var.vpc_cidr_block]+ }++ egress {+ description = "All outbound"+ from_port = 0+ to_port = 0+ protocol = "-1"+ cidr_blocks = ["0.0.0.0/0"]+ }++ tags = {+ Name = "${var.project_name}-${var.environment}-server-sg"+ Environment = var.environment+ }+}++###############################################################################+# PROD MODE — Worker security group+###############################################################################++resource "aws_security_group" "worker" {+ count = local.is_prod ? 1 : 0++ name = "${var.project_name}-${var.environment}-worker-sg"+ description = "Worker security group: API + gRPC + metrics from Server, SSH from VPC"+ vpc_id = var.vpc_id++ ingress {+ description = "Worker API from Server"+ from_port = 8080+ to_port = 8080+ protocol = "tcp"+ security_groups = [aws_security_group.server[0].id]+ }++ ingress {+ description = "gRPC from Server"+ from_port = 9090+ to_port = 9090+ protocol = "tcp"+ security_groups = [aws_security_group.server[0].id]+ }++ ingress {+ description = "Metrics from Server"+ from_port = 9091+ to_port = 9091+ protocol = "tcp"+ security_groups = [aws_security_group.server[0].id]+ }++ ingress {+ description = "SSH from VPC"+ from_port = 22+ to_port = 22+ protocol = "tcp"+ cidr_blocks = [var.vpc_cidr_block]+ }++ egress {+ description = "All outbound"+ from_port = 0+ to_port = 0+ protocol = "-1"+ cidr_blocks = ["0.0.0.0/0"]+ }++ tags = {+ Name = "${var.project_name}-${var.environment}-worker-sg"+ Environment = var.environment+ }+}++###############################################################################+# PROD MODE — RDS security group+###############################################################################++resource "aws_security_group" "rds" {+ count = local.is_prod ? 1 : 0++ name = "${var.project_name}-${var.environment}-rds-sg"+ description = "RDS security group: PostgreSQL from Server + Worker"+ vpc_id = var.vpc_id++ ingress {+ description = "PostgreSQL from Server"+ from_port = 5432+ to_port = 5432+ protocol = "tcp"+ security_groups = [aws_security_group.server[0].id]+ }++ ingress {+ description = "PostgreSQL from Worker"+ from_port = 5432+ to_port = 5432+ protocol = "tcp"+ security_groups = [aws_security_group.worker[0].id]+ }++ egress {+ description = "All outbound"+ from_port = 0+ to_port = 0+ protocol = "-1"+ cidr_blocks = ["0.0.0.0/0"]+ }++ tags = {+ Name = "${var.project_name}-${var.environment}-rds-sg"+ Environment = var.environment+ }+}++###############################################################################+# PROD MODE — Redis security group+###############################################################################++resource "aws_security_group" "redis" {+ count = local.is_prod ? 1 : 0++ name = "${var.project_name}-${var.environment}-redis-sg"+ description = "Redis security group: Redis from Server + Worker"+ vpc_id = var.vpc_id++ ingress {+ description = "Redis from Server"+ from_port = 6379+ to_port = 6379+ protocol = "tcp"+ security_groups = [aws_security_group.server[0].id]+ }++ ingress {+ description = "Redis from Worker"+ from_port = 6379+ to_port = 6379+ protocol = "tcp"+ security_groups = [aws_security_group.worker[0].id]+ }++ egress {+ description = "All outbound"+ from_port = 0+ to_port = 0+ protocol = "-1"+ cidr_blocks = ["0.0.0.0/0"]+ }++ tags = {+ Name = "${var.project_name}-${var.environment}-redis-sg"+ Environment = var.environment+ }+}diff --git a/deploy/terraform/modules/security/outputs.tf b/deploy/terraform/modules/security/outputs.tfnew file mode 100644index 00000000..a588e094--- /dev/null+++ b/deploy/terraform/modules/security/outputs.tf@@ -0,0 +1,37 @@+###############################################################################+# Dev mode output — populated only when environment == "dev"+###############################################################################++output "dev_sg_id" {+ description = "Security group ID for the dev-mode combined SG (empty string in prod)"+ value = length(aws_security_group.dev) > 0 ? aws_security_group.dev[0].id : ""+}++###############################################################################+# Prod mode outputs — populated only when environment != "dev"+###############################################################################++output "alb_sg_id" {+ description = "Security group ID for the ALB (empty string in dev)"+ value = length(aws_security_group.alb) > 0 ? aws_security_group.alb[0].id : ""+}++output "server_sg_id" {+ description = "Security group ID for the Server instances (empty string in dev)"+ value = length(aws_security_group.server) > 0 ? aws_security_group.server[0].id : ""+}++output "worker_sg_id" {+ description = "Security group ID for the Worker instances (empty string in dev)"+ value = length(aws_security_group.worker) > 0 ? aws_security_group.worker[0].id : ""+}++output "rds_sg_id" {+ description = "Security group ID for the RDS instance (empty string in dev)"+ value = length(aws_security_group.rds) > 0 ? aws_security_group.rds[0].id : ""+}++output "redis_sg_id" {+ description = "Security group ID for the Redis cluster (empty string in dev)"+ value = length(aws_security_group.redis) > 0 ? aws_security_group.redis[0].id : ""+}diff --git a/deploy/terraform/modules/security/variables.tf b/deploy/terraform/modules/security/variables.tfnew file mode 100644index 00000000..16f9bfa2--- /dev/null+++ b/deploy/terraform/modules/security/variables.tf@@ -0,0 +1,19 @@+variable "project_name" {+ description = "Project name used as a prefix for resource naming"+ type = string+}++variable "environment" {+ description = "Environment name (dev, staging, prod). Dev mode creates a single SG; any other value creates prod-style SGs."+ type = string+}++variable "vpc_id" {+ description = "ID of the VPC in which to create security groups"+ type = string+}++variable "vpc_cidr_block" {+ description = "CIDR block of the VPC, used for intra-VPC SSH access in prod mode"+ type = string+}diff --git a/deploy/terraform/modules/server/main.tf b/deploy/terraform/modules/server/main.tfnew file mode 100644index 00000000..893c48e9--- /dev/null+++ b/deploy/terraform/modules/server/main.tf@@ -0,0 +1,81 @@+###############################################################################+# AMI lookup – Amazon Linux 2023 ARM64 (used when var.ami_id is empty)+###############################################################################+data "aws_ami" "al2023_arm64" {+ count = var.ami_id == "" ? 1 : 0+ most_recent = true+ owners = ["amazon"]++ filter {+ name = "name"+ values = ["al2023-ami-*-arm64"]+ }++ filter {+ name = "architecture"+ values = ["arm64"]+ }++ filter {+ name = "virtualization-type"+ values = ["hvm"]+ }+}++locals {+ ami_id = var.ami_id != "" ? var.ami_id : data.aws_ami.al2023_arm64[0].id+ ecr_image = "${var.ecr_server_repo_url}:${var.server_image_tag}"++ # Extract the ECR registry URL (everything before the first '/') for docker login+ ecr_registry = regex("^([^/]+)", var.ecr_server_repo_url)[0]+ aws_region = regex("\\.([a-z0-9-]+)\\.amazonaws\\.com", var.ecr_server_repo_url)[0]+}++###############################################################################+# EC2 Instance – OpenSandbox Server+###############################################################################+resource "aws_instance" "server" {+ ami = local.ami_id+ instance_type = var.instance_type+ subnet_id = var.subnet_id+ vpc_security_group_ids = [var.security_group_id]+ key_name = var.key_pair_name+ iam_instance_profile = var.instance_profile_name++ associate_public_ip_address = false++ user_data = base64encode(<<-EOF+ #!/bin/bash+ set -euo pipefail++ # Install Docker+ dnf install -y docker+ systemctl enable docker+ systemctl start docker++ # ECR login+ aws ecr get-login-password --region ${local.aws_region} | docker login --username AWS --password-stdin ${local.ecr_registry}++ # Pull and run the server container+ docker pull ${local.ecr_image}++ docker run -d \+ --name opensandbox-server \+ --restart unless-stopped \+ -p 8080:8080 \+ -e OPENSANDBOX_MODE=server \+ -e OPENSANDBOX_SECRETS_ARN=${var.server_secret_arn} \+ -e OPENSANDBOX_DATABASE_URL=${var.database_url} \+ -e OPENSANDBOX_REDIS_URL=${var.redis_url} \+ -e OPENSANDBOX_WORKER_INTERNAL_URL=http://${var.worker_private_ip}:8080 \+ ${local.ecr_image}+ EOF+ )++ tags = {+ Name = "${var.project_name}-${var.environment}-server"+ Project = var.project_name+ Environment = var.environment+ Role = "server"+ }+}diff --git a/deploy/terraform/modules/server/outputs.tf b/deploy/terraform/modules/server/outputs.tfnew file mode 100644index 00000000..0ee0180d--- /dev/null+++ b/deploy/terraform/modules/server/outputs.tf@@ -0,0 +1,9 @@+output "instance_id" {+ description = "ID of the server EC2 instance"+ value = aws_instance.server.id+}++output "private_ip" {+ description = "Private IP address of the server EC2 instance"+ value = aws_instance.server.private_ip+}diff --git a/deploy/terraform/modules/server/variables.tf b/deploy/terraform/modules/server/variables.tfnew file mode 100644index 00000000..c6655693--- /dev/null+++ b/deploy/terraform/modules/server/variables.tf@@ -0,0 +1,74 @@+variable "project_name" {+ description = "Name of the project, used as a prefix for resource naming"+ type = string+}++variable "environment" {+ description = "Deployment environment (e.g. dev, staging, prod)"+ type = string+}++variable "subnet_id" {+ description = "ID of the private subnet to launch the instance in"+ type = string+}++variable "security_group_id" {+ description = "ID of the security group to attach to the instance"+ type = string+}++variable "instance_type" {+ description = "EC2 instance type for the server"+ type = string+ default = "t3.medium"+}++variable "key_pair_name" {+ description = "Name of the EC2 key pair for SSH access"+ type = string+}++variable "instance_profile_name" {+ description = "Name of the IAM instance profile (from secrets module)"+ type = string+}++variable "server_secret_arn" {+ description = "ARN of the Secrets Manager secret for the server"+ type = string+}++variable "ecr_server_repo_url" {+ description = "Full ECR repository URL for the server image (e.g. 123456789.dkr.ecr.us-east-1.amazonaws.com/opensandbox-server)"+ type = string+}++variable "server_image_tag" {+ description = "Docker image tag for the server (e.g. latest, v1.0.0, sha-abc1234)"+ type = string+ default = "latest"+}++variable "database_url" {+ description = "PostgreSQL connection string for the server"+ type = string+ sensitive = true+}++variable "redis_url" {+ description = "Redis connection string"+ type = string+ sensitive = true+}++variable "worker_private_ip" {+ description = "Private IP address of the worker instance"+ type = string+}++variable "ami_id" {+ description = "AMI ID to use. If empty, the latest Amazon Linux 2023 ARM64 AMI is looked up automatically."+ type = string+ default = ""+}diff --git a/deploy/terraform/modules/worker/main.tf b/deploy/terraform/modules/worker/main.tfnew file mode 100644index 00000000..abfb46f3--- /dev/null+++ b/deploy/terraform/modules/worker/main.tf@@ -0,0 +1,145 @@+###############################################################################+# Data Sources+###############################################################################++# Look up the latest Amazon Linux 2023 ARM64 AMI when no ami_id is provided.+data "aws_ami" "al2023_arm64" {+ count = var.ami_id == "" ? 1 : 0+ most_recent = true+ owners = ["amazon"]++ filter {+ name = "name"+ values = ["al2023-ami-*-kernel-*-arm64"]+ }++ filter {+ name = "architecture"+ values = ["arm64"]+ }++ filter {+ name = "virtualization-type"+ values = ["hvm"]+ }++ filter {+ name = "state"+ values = ["available"]+ }+}++###############################################################################+# Locals+###############################################################################++locals {+ ami_id = var.ami_id != "" ? var.ami_id : data.aws_ami.al2023_arm64[0].id++ common_tags = {+ Project = var.project_name+ Environment = var.environment+ ManagedBy = "terraform"+ }+}++###############################################################################+# EC2 Instance — bare-metal worker (private subnet, no public IP)+###############################################################################++resource "aws_instance" "worker" {+ ami = local.ami_id+ instance_type = var.instance_type+ subnet_id = var.subnet_id+ vpc_security_group_ids = [var.security_group_id]+ key_name = var.key_pair_name+ iam_instance_profile = var.instance_profile_name++ associate_public_ip_address = false++ root_block_device {+ volume_size = 200+ volume_type = "gp3"+ delete_on_termination = true+ }++ user_data = <<-USERDATA+ #!/usr/bin/env bash+ set -euo pipefail++ # ---------------------------------------------------------------+ # 1. Enable KVM+ # ---------------------------------------------------------------+ modprobe kvm+ # Use the appropriate KVM module for the CPU vendor+ modprobe kvm_intel 2>/dev/null || modprobe kvm_amd 2>/dev/null || true+ chmod 666 /dev/kvm++ # ---------------------------------------------------------------+ # 2. Sysctl tuning for Firecracker VM networking+ # ---------------------------------------------------------------+ cat > /etc/sysctl.d/99-opensandbox.conf << 'SYSCTL'+ net.ipv4.ip_forward = 1+ net.ipv4.conf.all.proxy_arp = 1+ SYSCTL+ sysctl --system++ # ---------------------------------------------------------------+ # 3. Create /opt/opensandbox directory structure+ # ---------------------------------------------------------------+ mkdir -p /opt/opensandbox/data+ mkdir -p /opt/opensandbox/rootfs++ # ---------------------------------------------------------------+ # 4. Download Firecracker-compatible kernel+ # ---------------------------------------------------------------+ wget -q -O /opt/opensandbox/vmlinux \+ https://github.com/diggerhq/opencomputer/releases/download/kernel-v1/vmlinux-arm64++ # ---------------------------------------------------------------+ # 5. Create systemd unit for opensandbox-worker+ # ---------------------------------------------------------------+ cat > /etc/systemd/system/opensandbox-worker.service << 'SVC'+ [Unit]+ Description=OpenSandbox Worker (Firecracker)+ After=network-online.target+ Wants=network-online.target++ [Service]+ Type=simple+ ExecStart=/opt/opensandbox/opensandbox-worker+ Restart=always+ RestartSec=5+ WorkingDirectory=/opt/opensandbox++ Environment=OPENSANDBOX_MODE=worker+ Environment=OPENSANDBOX_PORT=8080+ Environment=OPENSANDBOX_SECRETS_ARN=${var.worker_secret_arn}+ Environment=DATABASE_URL=${var.database_url}+ Environment=OPENSANDBOX_REDIS_URL=${var.redis_url}+ Environment=OPENSANDBOX_DATA_DIR=/opt/opensandbox/data++ KillMode=process+ TimeoutStopSec=300+ LimitNOFILE=1000000+ LimitNPROC=65536++ [Install]+ WantedBy=multi-user.target+ SVC++ systemctl daemon-reload+ # NOTE: Worker binary is deployed separately via Makefile.+ # Once the binary is placed at /opt/opensandbox/opensandbox-worker, enable+ # and start the service with:+ # systemctl enable --now opensandbox-worker+ USERDATA++ tags = merge(local.common_tags, {+ Name = "${var.project_name}-${var.environment}-worker"+ })++ lifecycle {+ ignore_changes = [ami]+ }+}diff --git a/deploy/terraform/modules/worker/outputs.tf b/deploy/terraform/modules/worker/outputs.tfnew file mode 100644index 00000000..017d52b0--- /dev/null+++ b/deploy/terraform/modules/worker/outputs.tf@@ -0,0 +1,9 @@+output "instance_id" {+ description = "ID of the worker EC2 instance"+ value = aws_instance.worker.id+}++output "private_ip" {+ description = "Private IP address of the worker EC2 instance"+ value = aws_instance.worker.private_ip+}diff --git a/deploy/terraform/modules/worker/variables.tf b/deploy/terraform/modules/worker/variables.tfnew file mode 100644index 00000000..9bfa1184--- /dev/null+++ b/deploy/terraform/modules/worker/variables.tf@@ -0,0 +1,58 @@+variable "project_name" {+ description = "Name of the project, used as a prefix for resource naming"+ type = string+}++variable "environment" {+ description = "Deployment environment (e.g. dev, staging, prod)"+ type = string+}++variable "subnet_id" {+ description = "ID of the private subnet to launch the instance in"+ type = string+}++variable "security_group_id" {+ description = "ID of the security group to attach to the instance"+ type = string+}++variable "instance_type" {+ description = "EC2 instance type for the worker (must support bare-metal / KVM)"+ type = string+ default = "c5.metal"+}++variable "key_pair_name" {+ description = "Name of the EC2 key pair for SSH access"+ type = string+}++variable "instance_profile_name" {+ description = "Name of the IAM instance profile (from secrets module)"+ type = string+}++variable "worker_secret_arn" {+ description = "ARN of the Secrets Manager secret for the worker"+ type = string+}++variable "database_url" {+ description = "PostgreSQL connection string for the worker"+ type = string+ sensitive = true+}++variable "redis_url" {+ description = "Redis connection string"+ type = string+ sensitive = true+}++variable "ami_id" {+ description = "AMI ID to use. If empty, the latest Amazon Linux 2023 ARM64 AMI is looked up automatically."+ type = string+ default = ""+}diff --git a/deploy/terraform/outputs.tf b/deploy/terraform/outputs.tfnew file mode 100644index 00000000..4a931b38--- /dev/null+++ b/deploy/terraform/outputs.tf@@ -0,0 +1,75 @@+locals {+ _is_dev = startswith(var.environment, "dev")+}++# Dev mode outputs+output "dev_host_public_ip" {+ description = "Public IP of the dev host (dev mode only)"+ value = local._is_dev ? module.dev_host[0].public_ip : null+}++output "dev_server_url" {+ description = "Server URL for dev mode"+ value = local._is_dev ? "http://${module.dev_host[0].public_ip}:8080" : null+}++output "server_url" {+ description = "Server URL (ALB in prod, direct IP in dev)"+ value = local._is_dev ? (+ "http://${module.dev_host[0].public_ip}:8080"+ ) : (+ var.domain_name != "" ? "https://${var.domain_name}" : "http://${module.alb[0].dns_name}"+ )+}++output "api_key" {+ description = "API key for authenticating requests"+ value = var.api_key+ sensitive = true+}++# Prod mode outputs+output "ecr_server_repo_url" {+ description = "ECR repository URL for the server image (prod only)"+ value = local._is_dev ? null : module.ecr[0].server_repo_url+}++output "ecr_worker_repo_url" {+ description = "ECR repository URL for the worker image (prod only)"+ value = local._is_dev ? null : module.ecr[0].worker_repo_url+}++output "alb_dns_name" {+ description = "ALB DNS name (prod mode only)"+ value = local._is_dev ? null : module.alb[0].dns_name+}++output "server_private_ip" {+ description = "Server private IP (prod mode only)"+ value = local._is_dev ? null : module.server[0].private_ip+}++output "worker_private_ip" {+ description = "Worker private IP (prod mode only)"+ value = local._is_dev ? null : module.worker[0].private_ip+}++output "database_endpoint" {+ description = "RDS endpoint (prod mode only)"+ value = local._is_dev ? null : module.database[0].endpoint+}++output "redis_endpoint" {+ description = "ElastiCache endpoint (prod mode only)"+ value = local._is_dev ? null : module.redis[0].endpoint+}++output "secrets_server_arn" {+ description = "ARN of the server secrets in Secrets Manager (prod only)"+ value = local._is_dev ? null : module.secrets[0].server_secret_arn+}++output "secrets_worker_arn" {+ description = "ARN of the worker secrets in Secrets Manager (prod only)"+ value = local._is_dev ? null : module.secrets[0].worker_secret_arn+}diff --git a/deploy/terraform/terraform.tfvars.example b/deploy/terraform/terraform.tfvars.examplenew file mode 100644index 00000000..01855937--- /dev/null+++ b/deploy/terraform/terraform.tfvars.example@@ -0,0 +1,20 @@+# Required+environment = "dev" # "dev" or "prod"+aws_region = "us-east-1"+key_pair_name = "my-key-pair"+api_key = "change-me-to-a-secure-key"+jwt_secret = "change-me-to-a-secure-secret"++# Optional overrides+# project_name = "opensandbox"+# vpc_cidr = "10.0.0.0/16"+# server_instance_type = "t3.medium" # prod only+# worker_instance_type = "c5.metal"+# dev_host_instance_type = "c5.metal" # dev only+# db_instance_class = "db.t4g.micro" # prod only+# redis_node_type = "cache.t4g.micro" # prod only+# acm_certificate_arn = "" # prod: set for HTTPS (from terraform-dns output)+# domain_name = "" # prod: your domain (from terraform-dns output)+# hosted_zone_id = "" # prod: Route 53 zone for alias record+# ami_id = "" # leave empty for latest Ubuntu 24.04 LTS+# server_image_tag = "latest"diff --git a/deploy/terraform/variables.tf b/deploy/terraform/variables.tfnew file mode 100644index 00000000..d1ddae7e--- /dev/null+++ b/deploy/terraform/variables.tf@@ -0,0 +1,136 @@+variable "environment" {+ description = "Environment name: 'dev', 'dev-<name>' (e.g. dev-mohamed, dev-ci), or 'prod'. Use unique dev-<name> values to run multiple dev environments without clashes."+ type = string+ default = "dev"++ validation {+ condition = startswith(var.environment, "dev") || var.environment == "prod"+ error_message = "Environment must be 'dev', 'dev-<name>' (e.g. dev-mohamed), or 'prod'."+ }+}++variable "aws_region" {+ description = "AWS region to deploy into"+ type = string+ default = "us-east-1"+}++variable "project_name" {+ description = "Project name used for resource naming"+ type = string+ default = "opensandbox"+}++# --- Networking ---++variable "vpc_cidr" {+ description = "CIDR block for the VPC"+ type = string+ default = "10.0.0.0/16"+}++# --- EC2 ---++variable "key_pair_name" {+ description = "Name of the EC2 key pair for SSH access"+ type = string+ default = "opensandbox-dev"+}++variable "server_instance_type" {+ description = "Instance type for the server EC2 (prod only)"+ type = string+ default = "t3.medium"+}++variable "worker_instance_type" {+ description = "Bare-metal instance type for the worker EC2"+ type = string+ default = "c5.metal"+}++variable "dev_host_instance_type" {+ description = "EC2 instance type for the dev single-host. Use bare-metal (e.g. c7g.metal) for Firecracker KVM support, or regular instances (e.g. c8i.xlarge) for control plane dev without sandboxes."+ type = string+ default = "c8i.xlarge"+}++# --- Database (prod only) ---++variable "db_instance_class" {+ description = "RDS instance class"+ type = string+ default = "db.t4g.micro"+}++variable "db_name" {+ description = "PostgreSQL database name"+ type = string+ default = "opensandbox"+}++variable "db_username" {+ description = "PostgreSQL master username"+ type = string+ default = "opensandbox"+}++# --- Redis (prod only) ---++variable "redis_node_type" {+ description = "ElastiCache node type"+ type = string+ default = "cache.t4g.micro"+}++# --- ALB (prod only) ---++variable "acm_certificate_arn" {+ description = "ACM certificate ARN for HTTPS listener (prod only, optional)"+ type = string+ default = ""+}++variable "domain_name" {+ description = "Domain name for the server (used in ALB, Route 53, and outputs)"+ type = string+ default = ""+}++variable "hosted_zone_id" {+ description = "Route 53 hosted zone ID for creating an alias record pointing to the ALB (prod only)"+ type = string+ default = ""+}++# --- Secrets ---++variable "api_key" {+ description = "API key for authenticating requests. In dev mode, defaults to 'test-key' if not set."+ type = string+ sensitive = true+ default = "test-key"+}++variable "jwt_secret" {+ description = "JWT secret for token signing. In dev mode, defaults to 'dev-secret' if not set."+ type = string+ sensitive = true+ default = "dev-secret"+}++# --- AMI ---++variable "ami_id" {+ description = "AMI ID for EC2 instances (Ubuntu 24.04 x86_64 recommended). If empty, latest Ubuntu 24.04 LTS is used."+ type = string+ default = ""+}++# --- Server Docker image ---++variable "server_image_tag" {+ description = "Docker image tag for the server (defaults to 'latest')"+ type = string+ default = "latest"+}diff --git a/deploy/terraform/versions.tf b/deploy/terraform/versions.tfnew file mode 100644index 00000000..430a793e--- /dev/null+++ b/deploy/terraform/versions.tf@@ -0,0 +1,26 @@+terraform {+ required_version = ">= 1.5.0"++ required_providers {+ aws = {+ source = "hashicorp/aws"+ version = ">= 6.0"+ }+ random = {+ source = "hashicorp/random"+ version = "~> 3.5"+ }+ }+}++provider "aws" {+ region = var.aws_region++ default_tags {+ tags = {+ Project = "opensandbox"+ Environment = var.environment+ ManagedBy = "terraform"+ }+ }+}