Skip to content

An open-source, faster Devin alternative

TypeScript

docs, remove the bin, add ec2 dcocumentation for now

Brian Reardon51a762459f61
diff --git a/.gitignore b/.gitignore
index 1b321114..6340a92a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -31,6 +31,13 @@ dist/
# Compiled binaries
bin/opensandbox-server
bin/opensandbox-worker
+opensandbox-worker
+
+# Worker env (secrets)
+worker.env
+
+# Loom demo (private)
+sdks/typescript/examples/loom/
# Media files
*.mp4
diff --git a/deploy/ec2/Caddyfile b/deploy/ec2/Caddyfile
new file mode 100644
index 00000000..f534c105
--- /dev/null
+++ b/deploy/ec2/Caddyfile
@@ -0,0 +1,12 @@
+{
+ on_demand_tls {
+ ask http://localhost:8080/caddy/check
+ }
+}
+
+https://*.workers.opensandbox.ai {
+ tls {
+ on_demand
+ }
+ reverse_proxy localhost:8080
+}
diff --git a/deploy/ec2/README.md b/deploy/ec2/README.md
new file mode 100644
index 00000000..2380e5d8
--- /dev/null
+++ b/deploy/ec2/README.md
@@ -0,0 +1,60 @@
+# EC2 Worker Deployment
+
+## Software Stack
+
+| Component | Version | Notes |
+|-----------|---------|-------|
+| Podman | 5.8.0 | Rootful, used for sandbox containers |
+| CRIU | 4.2 | Checkpoint/restore for hibernation |
+| crun | 1.26 | OCI runtime with +CRIU support |
+| Caddy | latest | On-demand TLS for `*.workers.opensandbox.ai` |
+| Redis | 7.0.15 | Local, used for sandbox state/routing |
+| Go worker | custom | `/usr/local/bin/opensandbox-worker` |
+
+## Architecture
+
+```
+Internet
+ |
+ v
+Caddy (port 443) -- on-demand TLS for *.workers.opensandbox.ai
+ |
+ v
+opensandbox-worker (port 8080) -- HTTP API + gRPC (9090)
+ |
+ v
+Podman containers (osb-*) -- one per sandbox
+ |
+ v
+CRIU checkpoint/restore -- hibernate to S3, wake on demand
+```
+
+## Scripts
+
+- `setup-instance.sh` - Full instance setup from a fresh Ubuntu 24.04 AMI
+- `deploy-worker.sh` - Build and deploy the worker binary (run from repo root)
+- `opensandbox-worker.service` - Systemd unit template (fill in env vars)
+- `caddy.service` - Caddy systemd unit file
+- `Caddyfile` - Caddy configuration
+
+## Quick Commands
+
+```bash
+# Deploy worker (from repo root on your Mac)
+./deploy/ec2/deploy-worker.sh
+
+# SSH into the instance
+ssh -i ~/.ssh/opensandbox-worker.pem ubuntu@$WORKER_IP
+
+# Check worker logs
+sudo journalctl -u opensandbox-worker -f
+
+# Check caddy logs
+sudo journalctl -u caddy -f
+
+# Restart worker
+sudo systemctl restart opensandbox-worker
+
+# List running sandboxes
+sudo podman ps --filter label=opensandbox.id
+```
diff --git a/deploy/ec2/caddy.service b/deploy/ec2/caddy.service
new file mode 100644
index 00000000..c08767e6
--- /dev/null
+++ b/deploy/ec2/caddy.service
@@ -0,0 +1,14 @@
+[Unit]
+Description=Caddy TLS Reverse Proxy
+After=network-online.target
+Wants=network-online.target
+
+[Service]
+Type=simple
+ExecStart=/usr/local/bin/caddy run --config /etc/caddy/Caddyfile
+Restart=always
+RestartSec=5
+Environment=HOME=/root
+
+[Install]
+WantedBy=multi-user.target
diff --git a/deploy/ec2/deploy-worker.sh b/deploy/ec2/deploy-worker.sh
new file mode 100755
index 00000000..e65db3cc
--- /dev/null
+++ b/deploy/ec2/deploy-worker.sh
@@ -0,0 +1,34 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+# Deploy the opensandbox-worker binary to the EC2 instance.
+# Run from the repo root: ./deploy/ec2/deploy-worker.sh
+
+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="ssh -i $SSH_KEY $SSH_USER@$WORKER_IP"
+SCP="scp -i $SSH_KEY"
+
+echo "==> Building opensandbox-worker (linux/amd64)..."
+cd "$REPO_ROOT"
+GOOS=linux GOARCH=amd64 go build -o opensandbox-worker ./cmd/worker/
+echo " Built: opensandbox-worker ($(du -h opensandbox-worker | cut -f1))"
+
+echo "==> Uploading to $WORKER_IP..."
+$SCP opensandbox-worker "$SSH_USER@$WORKER_IP:/tmp/opensandbox-worker"
+
+echo "==> Installing and restarting service..."
+$SSH "sudo mv /tmp/opensandbox-worker /usr/local/bin/opensandbox-worker && \
+ sudo chmod +x /usr/local/bin/opensandbox-worker && \
+ sudo systemctl restart opensandbox-worker"
+
+echo "==> Waiting for worker to start..."
+sleep 2
+$SSH "sudo systemctl is-active opensandbox-worker"
+
+echo "==> Deployed successfully!"
+rm -f "$REPO_ROOT/opensandbox-worker"
diff --git a/deploy/ec2/opensandbox-worker.service b/deploy/ec2/opensandbox-worker.service
new file mode 100644
index 00000000..2dda39e1
--- /dev/null
+++ b/deploy/ec2/opensandbox-worker.service
@@ -0,0 +1,24 @@
+[Unit]
+Description=OpenSandbox Worker
+After=network-online.target
+Wants=network-online.target
+
+[Service]
+Type=simple
+# Load kernel modules required by CRIU for checkpoint/restore
+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
+
+# Secrets and instance-specific config are loaded from an env file.
+# Copy deploy/ec2/worker.env.example to /etc/opensandbox/worker.env
+# and fill in values for your deployment.
+EnvironmentFile=/etc/opensandbox/worker.env
+
+[Install]
+WantedBy=multi-user.target
diff --git a/deploy/ec2/setup-instance.sh b/deploy/ec2/setup-instance.sh
new file mode 100755
index 00000000..b43fb138
--- /dev/null
+++ b/deploy/ec2/setup-instance.sh
@@ -0,0 +1,155 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+# Provision a fresh Ubuntu 24.04 EC2 instance as an OpenSandbox worker.
+# Run this ON the instance (ssh in first), or pipe via ssh:
+# ssh -i key.pem ubuntu@<IP> 'bash -s' < deploy/ec2/setup-instance.sh
+#
+# Prerequisites:
+# - Ubuntu 24.04 LTS AMI
+# - t3.medium or larger
+# - Security group: 443 (HTTPS), 9090 (gRPC) open inbound
+# - SSH access
+
+echo "==> Updating packages..."
+sudo apt-get update && sudo apt-get upgrade -y
+
+# -------------------------------------------------------------------
+# Podman + crun (with CRIU support)
+# -------------------------------------------------------------------
+echo "==> Installing Podman..."
+sudo apt-get install -y podman uidmap slirp4netns
+
+echo "==> Installing crun from source (with CRIU support)..."
+sudo apt-get install -y \
+ make gcc pkg-config \
+ libsystemd-dev libcap-dev libseccomp-dev \
+ libyajl-dev go-md2man
+
+CRUN_VERSION="1.26"
+cd /tmp
+git clone --branch "$CRUN_VERSION" --depth 1 https://github.com/containers/crun.git
+cd crun
+./autogen.sh
+./configure --with-criu
+make -j"$(nproc)"
+sudo make install
+cd / && rm -rf /tmp/crun
+
+echo "==> Verifying crun has CRIU support..."
+crun --version | grep "+CRIU" || { echo "ERROR: crun built without CRIU"; exit 1; }
+
+# -------------------------------------------------------------------
+# CRIU 4.2
+# -------------------------------------------------------------------
+echo "==> Installing CRIU 4.2 from source..."
+sudo apt-get install -y \
+ libprotobuf-dev libprotobuf-c-dev protobuf-c-compiler protobuf-compiler \
+ libcap-dev libnl-3-dev libnet1-dev libbsd-dev \
+ python3-protobuf python3-yaml iproute2 \
+ libdrm-dev libnftables-dev pkg-config
+
+cd /tmp
+git clone --branch v4.2 --depth 1 https://github.com/checkpoint-restore/criu.git
+cd criu
+make -j"$(nproc)"
+sudo make install PREFIX=/usr/local
+cd / && rm -rf /tmp/criu
+
+echo "==> Verifying CRIU..."
+criu --version
+
+# -------------------------------------------------------------------
+# Configure Podman to use crun
+# -------------------------------------------------------------------
+echo "==> Configuring Podman to use crun..."
+sudo mkdir -p /etc/containers
+sudo tee /etc/containers/containers.conf > /dev/null <<'EOF'
+[engine]
+runtime = "crun"
+EOF
+
+# -------------------------------------------------------------------
+# Redis
+# -------------------------------------------------------------------
+echo "==> Installing Redis..."
+sudo apt-get install -y redis-server
+
+echo "==> Configuring Redis..."
+# Set a password — replace <REDIS_PASSWORD> with your actual password
+# sudo sed -i 's/^# requirepass .*/requirepass <REDIS_PASSWORD>/' /etc/redis/redis.conf
+# sudo systemctl restart redis-server
+echo " NOTE: Set a Redis password in /etc/redis/redis.conf manually"
+
+# -------------------------------------------------------------------
+# Caddy
+# -------------------------------------------------------------------
+echo "==> Installing Caddy..."
+sudo apt-get install -y debian-keyring debian-archive-keyring apt-transport-https curl
+curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | sudo gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
+curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | sudo tee /etc/apt/sources.list.d/caddy-stable.list
+sudo apt-get update
+sudo apt-get install -y caddy
+# Stop the default caddy service — we use our own unit
+sudo systemctl stop caddy
+sudo systemctl disable caddy
+
+echo "==> Installing Caddy config..."
+sudo mkdir -p /etc/caddy
+sudo cp /tmp/deploy-ec2/Caddyfile /etc/caddy/Caddyfile 2>/dev/null || \
+ echo " NOTE: Copy deploy/ec2/Caddyfile to /etc/caddy/Caddyfile manually"
+
+echo "==> Installing Caddy systemd unit..."
+sudo cp /tmp/deploy-ec2/caddy.service /etc/systemd/system/caddy.service 2>/dev/null || \
+ echo " NOTE: Copy deploy/ec2/caddy.service to /etc/systemd/system/ manually"
+
+# -------------------------------------------------------------------
+# Worker setup
+# -------------------------------------------------------------------
+echo "==> Creating data directory..."
+sudo mkdir -p /data/sandboxes
+
+echo "==> Installing worker systemd unit..."
+sudo cp /tmp/deploy-ec2/opensandbox-worker.service /etc/systemd/system/ 2>/dev/null || \
+ echo " NOTE: Copy deploy/ec2/opensandbox-worker.service to /etc/systemd/system/ manually"
+
+echo "==> Creating env file directory..."
+sudo mkdir -p /etc/opensandbox
+if [ ! -f /etc/opensandbox/worker.env ]; then
+ echo " NOTE: Copy deploy/ec2/worker.env.example to /etc/opensandbox/worker.env and fill in secrets"
+fi
+
+# -------------------------------------------------------------------
+# Kernel modules for CRIU (loaded at boot)
+# -------------------------------------------------------------------
+echo "==> Configuring kernel modules for CRIU..."
+sudo tee /etc/modules-load.d/opensandbox.conf > /dev/null <<EOF
+inet_diag
+tcp_diag
+udp_diag
+unix_diag
+netlink_diag
+EOF
+
+# Load them now
+sudo modprobe inet_diag tcp_diag udp_diag unix_diag netlink_diag
+
+# -------------------------------------------------------------------
+# Enable services
+# -------------------------------------------------------------------
+echo "==> Enabling services..."
+sudo systemctl daemon-reload
+sudo systemctl enable caddy
+sudo systemctl enable opensandbox-worker
+
+echo ""
+echo "============================================"
+echo " Instance setup complete!"
+echo ""
+echo " Remaining manual steps:"
+echo " 1. Copy worker.env.example to /etc/opensandbox/worker.env and fill in secrets"
+echo " 2. Copy Caddyfile to /etc/caddy/Caddyfile (if not already done)"
+echo " 3. Deploy the worker binary: ./deploy/ec2/deploy-worker.sh"
+echo " 4. Start services: sudo systemctl start caddy opensandbox-worker"
+echo " 5. Set up wildcard DNS: *.workers.opensandbox.ai -> this instance IP"
+echo "============================================"
diff --git a/deploy/ec2/worker.env.example b/deploy/ec2/worker.env.example
new file mode 100644
index 00000000..867725b6
--- /dev/null
+++ b/deploy/ec2/worker.env.example
@@ -0,0 +1,28 @@
+HOME=/root
+OPENSANDBOX_MODE=worker
+OPENSANDBOX_PORT=8080
+OPENSANDBOX_REGION=use2
+OPENSANDBOX_DATA_DIR=/data/sandboxes
+OPENSANDBOX_WORKER_ID=w-use2-1
+
+# Set to the public IP/hostname of this instance
+OPENSANDBOX_HTTP_ADDR=http://<WORKER_PUBLIC_IP>:8080
+OPENSANDBOX_GRPC_ADVERTISE=<WORKER_PUBLIC_IP>:9090
+
+# Redis (local)
+OPENSANDBOX_REDIS_URL=redis://default:<REDIS_PASSWORD>@127.0.0.1:6379
+
+# Auth
+OPENSANDBOX_JWT_SECRET=<JWT_SECRET>
+
+# Domain for sandbox routing (wildcard DNS must point to this instance)
+OPENSANDBOX_SANDBOX_DOMAIN=workers.opensandbox.ai
+
+# S3 — used for checkpoint storage
+OPENSANDBOX_S3_ACCESS_KEY_ID=<AWS_ACCESS_KEY_ID>
+OPENSANDBOX_S3_SECRET_ACCESS_KEY=<AWS_SECRET_ACCESS_KEY>
+OPENSANDBOX_S3_BUCKET=opensandbox-checkpoints
+OPENSANDBOX_S3_REGION=us-east-2
+
+# Postgres (control plane database)
+DATABASE_URL=postgres://<DB_USER>:<DB_PASSWORD>@<DB_HOST>:5432/opensandbox?sslmode=disable
diff --git a/docs/sdks/python/overview.mdx b/docs/sdks/python/overview.mdx
index 426cedf1..80f95d26 100644
--- a/docs/sdks/python/overview.mdx
+++ b/docs/sdks/python/overview.mdx
@@ -23,7 +23,7 @@ The Python SDK is fully async and provides the same modules as the TypeScript SD
| [Commands](/sdks/python/commands) | `sandbox.commands` | Execute shell commands |
| [Filesystem](/sdks/python/filesystem) | `sandbox.files` | Read, write, and manage files |
| [PTY](/sdks/python/pty) | `sandbox.pty` | Interactive terminal sessions |
-| [Templates](/sdks/python/templates) | `sandbox.templates` | Build and manage container templates |
+| [Templates](/sdks/python/templates) | `Template(api_url, api_key)` | Build and manage container templates |
## Quick Example
diff --git a/docs/sdks/python/sandbox.mdx b/docs/sdks/python/sandbox.mdx
index 3e1872eb..ecf05e15 100644
--- a/docs/sdks/python/sandbox.mdx
+++ b/docs/sdks/python/sandbox.mdx
@@ -84,6 +84,7 @@ Connects to a running sandbox by ID.
| Property | Type | Description |
| --- | --- | --- |
| `sandbox_id` | `str` | Unique identifier for the sandbox |
+| `domain` | `str` | Public domain for the sandbox (e.g. `abc123.workers.opensandbox.ai`). HTTP traffic to this domain is routed directly into the sandbox. |
| `status` | `str` | Current status: `"running"`, `"stopped"`, or `"error"` |
| `template` | `str` | Template used to create the sandbox |
| `files` | `Filesystem` | [Filesystem](/sdks/python/filesystem) operations |
diff --git a/docs/sdks/python/templates.mdx b/docs/sdks/python/templates.mdx
index 939f277f..6eb8c5e5 100644
--- a/docs/sdks/python/templates.mdx
+++ b/docs/sdks/python/templates.mdx
@@ -8,11 +8,11 @@ Templates let you create reusable sandbox images from Dockerfiles. Pre-install l
## Building a Template
```python
-from opensandbox import Sandbox
+from opensandbox import Template
-sandbox = await Sandbox.create()
+templates = Template(api_url, api_key)
-template = await sandbox.templates.build('python-ml', """
+template = await templates.build('python-ml', """
FROM ubuntu:22.04
RUN apt-get update && apt-get install -y python3 python3-pip
RUN pip3 install numpy pandas scikit-learn
@@ -22,7 +22,7 @@ print(template.template_id) # tpl-abc123
print(template.status) # building → ready
```
-### `await sandbox.templates.build(name, dockerfile)`
+### `await templates.build(name, dockerfile)`
Builds a new template from a Dockerfile.
@@ -38,13 +38,13 @@ Builds a new template from a Dockerfile.
## Listing Templates
```python
-templates = await sandbox.templates.list()
+all_templates = await templates.list()
-for t in templates:
+for t in all_templates:
print(f"{t.name} ({t.tag}) — {t.status}")
```
-### `await sandbox.templates.list()`
+### `await templates.list()`
Returns all templates.
@@ -53,11 +53,11 @@ Returns all templates.
## Getting a Template
```python
-template = await sandbox.templates.get('python-ml')
+template = await templates.get('python-ml')
print(template)
```
-### `await sandbox.templates.get(name)`
+### `await templates.get(name)`
Gets a template by name.
@@ -70,10 +70,10 @@ Gets a template by name.
## Deleting a Template
```python
-await sandbox.templates.delete('python-ml')
+await templates.delete('python-ml')
```
-### `await sandbox.templates.delete(name)`
+### `await templates.delete(name)`
Deletes a template by name.
diff --git a/docs/sdks/typescript/overview.mdx b/docs/sdks/typescript/overview.mdx
index fa83b681..d5191734 100644
--- a/docs/sdks/typescript/overview.mdx
+++ b/docs/sdks/typescript/overview.mdx
@@ -19,7 +19,7 @@ The TypeScript SDK provides five main modules:
| [Commands](/sdks/typescript/commands) | `sandbox.commands` | Execute shell commands |
| [Filesystem](/sdks/typescript/filesystem) | `sandbox.files` | Read, write, and manage files |
| [PTY](/sdks/typescript/pty) | `sandbox.pty` | Interactive terminal sessions |
-| [Templates](/sdks/typescript/templates) | `sandbox.templates` | Build and manage container templates |
+| [Templates](/sdks/typescript/templates) | `new Templates(apiUrl, apiKey)` | Build and manage container templates |
## Quick Example
diff --git a/docs/sdks/typescript/sandbox.mdx b/docs/sdks/typescript/sandbox.mdx
index a5dbeabe..c9b9bef8 100644
--- a/docs/sdks/typescript/sandbox.mdx
+++ b/docs/sdks/typescript/sandbox.mdx
@@ -81,6 +81,7 @@ Connects to a running sandbox by ID.
| Property | Type | Description |
| --- | --- | --- |
| `sandboxId` | `string` | Unique identifier for the sandbox |
+| `domain` | `string` | Public domain for the sandbox (e.g. `abc123.workers.opensandbox.ai`). HTTP traffic to this domain is routed directly into the sandbox. |
| `status` | `string` | Current status: `"running"`, `"stopped"`, or `"error"` |
| `files` | `Filesystem` | [Filesystem](/sdks/typescript/filesystem) operations |
| `commands` | `Commands` | [Command](/sdks/typescript/commands) execution |
diff --git a/docs/sdks/typescript/templates.mdx b/docs/sdks/typescript/templates.mdx
index f7fb75d9..9757b582 100644
--- a/docs/sdks/typescript/templates.mdx
+++ b/docs/sdks/typescript/templates.mdx
@@ -8,11 +8,11 @@ Templates let you create reusable sandbox images from Dockerfiles. Pre-install l
## Building a Template
```typescript
-import { Sandbox } from 'opensandbox';
+import { Templates } from 'opensandbox';
-const sandbox = await Sandbox.create();
+const templates = new Templates(apiUrl, apiKey);
-const template = await sandbox.templates.build('python-ml', `
+const template = await templates.build('python-ml', `
FROM ubuntu:22.04
RUN apt-get update && apt-get install -y python3 python3-pip
RUN pip3 install numpy pandas scikit-learn
@@ -22,7 +22,7 @@ console.log(template.templateID); // tpl-abc123
console.log(template.status); // building → ready
```
-### `sandbox.templates.build(name, dockerfile)`
+### `templates.build(name, dockerfile)`
Builds a new template from a Dockerfile.
@@ -38,14 +38,14 @@ Builds a new template from a Dockerfile.
## Listing Templates
```typescript
-const templates = await sandbox.templates.list();
+const allTemplates = await templates.list();
-for (const t of templates) {
+for (const t of allTemplates) {
console.log(`${t.name} (${t.tag}) — ${t.status}`);
}
```
-### `sandbox.templates.list()`
+### `templates.list()`
Returns all templates.
@@ -54,11 +54,11 @@ Returns all templates.
## Getting a Template
```typescript
-const template = await sandbox.templates.get('python-ml');
+const template = await templates.get('python-ml');
console.log(template);
```
-### `sandbox.templates.get(name)`
+### `templates.get(name)`
Gets a template by name.
@@ -71,10 +71,10 @@ Gets a template by name.
## Deleting a Template
```typescript
-await sandbox.templates.delete('python-ml');
+await templates.delete('python-ml');
```
-### `sandbox.templates.delete(name)`
+### `templates.delete(name)`
Deletes a template by name.
diff --git a/internal/proxy/proxy.go b/internal/proxy/proxy.go
index 27fef1af..67ed14f4 100644
--- a/internal/proxy/proxy.go
+++ b/internal/proxy/proxy.go
@@ -1,13 +1,17 @@
package proxy
import (
+ "bytes"
"context"
"fmt"
+ "io"
"log"
+ "net"
"net/http"
"net/http/httputil"
"net/url"
"strings"
+ "time"
"github.com/labstack/echo/v4"
"github.com/opensandbox/opensandbox/internal/sandbox"
@@ -71,6 +75,10 @@ func (p *SandboxProxy) extractSandboxID(host string) (string, bool) {
// doProxy looks up the sandbox's host port and reverse-proxies the request.
// If the sandbox is hibernated, it auto-wakes via the router first.
+// After restore, the upstream process may need a moment to stabilize its
+// listening socket. We retry on transient connection errors (reset, refused)
+// rather than using a static sleep, so the first request after wake succeeds
+// without adding unnecessary latency.
func (p *SandboxProxy) doProxy(c echo.Context, sandboxID string) error {
ctx := c.Request().Context()
@@ -98,19 +106,132 @@ func (p *SandboxProxy) doProxy(c echo.Context, sandboxID string) error {
}
}
- // Create reverse proxy to localhost:{hostPort}
+ // Buffer the request body so we can replay it across retries.
+ var bodyBytes []byte
+ if c.Request().Body != nil {
+ var err error
+ bodyBytes, err = io.ReadAll(c.Request().Body)
+ if err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{
+ "error": "failed to read request body",
+ })
+ }
+ c.Request().Body.Close()
+ }
+
+ addr := fmt.Sprintf("127.0.0.1:%d", hostPort)
target := &url.URL{
Scheme: "http",
- Host: fmt.Sprintf("127.0.0.1:%d", hostPort),
+ Host: addr,
}
- proxy := httputil.NewSingleHostReverseProxy(target)
- proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
- log.Printf("proxy: error proxying to sandbox %s (port %d): %v", sandboxID, hostPort, err)
- w.WriteHeader(http.StatusBadGateway)
- fmt.Fprintf(w, "sandbox %s: upstream unavailable", sandboxID)
+ // Retry loop: after CRIU restore the process's listening socket may need
+ // a few hundred ms to stabilize. We retry the full proxy attempt on
+ // transient errors (connection refused, reset, EOF) with backoff.
+ const maxRetries = 6
+ delay := 50 * time.Millisecond
+
+ for attempt := 0; attempt <= maxRetries; attempt++ {
+ if attempt > 0 {
+ time.Sleep(delay)
+ delay *= 2
+ if delay > 500*time.Millisecond {
+ delay = 500 * time.Millisecond
+ }
+ }
+
+ // Reset body for this attempt
+ if bodyBytes != nil {
+ c.Request().Body = io.NopCloser(bytes.NewReader(bodyBytes))
+ }
+
+ // Use a recorder to capture the proxy response so we can detect
+ // errors and retry without having already written to the client.
+ rec := &responseRecorder{
+ header: make(http.Header),
+ }
+
+ proxy := httputil.NewSingleHostReverseProxy(target)
+ proxy.Transport = &http.Transport{
+ DialContext: (&net.Dialer{
+ Timeout: 2 * time.Second,
+ }).DialContext,
+ ResponseHeaderTimeout: 10 * time.Second,
+ }
+
+ var proxyErr error
+ proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
+ proxyErr = err
+ }
+
+ proxy.ServeHTTP(rec, c.Request())
+
+ if proxyErr != nil {
+ if isRetryable(proxyErr) && attempt < maxRetries {
+ continue
+ }
+ log.Printf("proxy: error proxying to sandbox %s (port %d) after %d attempts: %v",
+ sandboxID, hostPort, attempt+1, proxyErr)
+ return c.JSON(http.StatusBadGateway, map[string]string{
+ "error": fmt.Sprintf("sandbox %s: upstream unavailable", sandboxID),
+ })
+ }
+
+ // Success — flush the recorded response to the real client.
+ rec.writeTo(c.Response())
+ return nil
+ }
+
+ // Should not reach here, but just in case.
+ return c.JSON(http.StatusBadGateway, map[string]string{
+ "error": fmt.Sprintf("sandbox %s: upstream unavailable after retries", sandboxID),
+ })
+}
+
+// responseRecorder captures an HTTP response in memory so we can decide
+// whether to retry (on connection error) or flush it to the real client.
+type responseRecorder struct {
+ header http.Header
+ body bytes.Buffer
+ statusCode int
+}
+
+func (r *responseRecorder) Header() http.Header {
+ return r.header
+}
+
+func (r *responseRecorder) Write(b []byte) (int, error) {
+ return r.body.Write(b)
+}
+
+func (r *responseRecorder) WriteHeader(statusCode int) {
+ r.statusCode = statusCode
+}
+
+func (r *responseRecorder) writeTo(w http.ResponseWriter) {
+ for k, vals := range r.header {
+ for _, v := range vals {
+ w.Header().Add(k, v)
+ }
+ }
+ code := r.statusCode
+ if code == 0 {
+ code = http.StatusOK
}
+ w.WriteHeader(code)
+ w.Write(r.body.Bytes())
+}
- proxy.ServeHTTP(c.Response(), c.Request())
- return nil
+// isRetryable returns true for transient connection errors that may resolve
+// after a CRIU-restored process stabilizes its listening socket.
+func isRetryable(err error) bool {
+ if err == nil {
+ return false
+ }
+ s := err.Error()
+ return strings.Contains(s, "connection refused") ||
+ strings.Contains(s, "connection reset") ||
+ strings.Contains(s, "closed network connection") ||
+ strings.Contains(s, "EOF") ||
+ strings.Contains(s, "broken pipe")
}
diff --git a/opensandbox-worker b/opensandbox-worker
deleted file mode 100755
index c90c80bb..00000000
Binary files a/opensandbox-worker and /dev/null differ