Skip to content

An open-source, faster Devin alternative

TypeScript

route creates through a runtime-agnostic Backend seam

Brian Reardon66c5bbe8b82b
diff --git a/.gitignore b/.gitignore
index 32f016a4..22ecb664 100644
--- a/.gitignore
+++ b/.gitignore
@@ -90,3 +90,7 @@ cloudflare-workers/api-edge/wrangler.ci.toml
# Wrangler local build/cache/state (never source)
.wrangler/
+
+# stray binaries from `go build ./cmd/...` without -o
+/microvm-hooks
+/microvm-harness
diff --git a/cmd/agent/listen_linux.go b/cmd/agent/listen_linux.go
index 5fe83351..90cc2d34 100644
--- a/cmd/agent/listen_linux.go
+++ b/cmd/agent/listen_linux.go
@@ -15,6 +15,26 @@ import (
// listenVsock creates the main agent listener.
// Tries virtio-serial first (QEMU), then vsock (Firecracker), then Unix socket (testing).
func listenVsock() (net.Listener, error) {
+ // TCP first, and only when explicitly asked for. On AWS Lambda MicroVMs
+ // there is no virtio-serial and no vsock: the only way in is Lambda's HTTPS
+ // proxy, which forwards to a guest TCP port when the caller presents a JWE
+ // in X-aws-proxy-auth and the port in X-aws-proxy-port. Listening on TCP is
+ // what lets the whole agent protocol — exec, files, PTY, streaming — carry
+ // over to that backend unchanged.
+ //
+ // Env-gated rather than auto-detected on purpose: a TCP listener on a QEMU
+ // box would be reachable from the guest's own network namespace, which the
+ // virtio-serial/vsock channels deliberately are not. Opt in only where the
+ // platform leaves no alternative.
+ if addr := os.Getenv("OSB_AGENT_LISTEN_TCP"); addr != "" {
+ lis, err := net.Listen("tcp", addr)
+ if err != nil {
+ return nil, fmt.Errorf("agent: tcp listen %s: %w", addr, err)
+ }
+ log.Printf("agent: listening on tcp %s (OSB_AGENT_LISTEN_TCP)", addr)
+ return lis, nil
+ }
+
// Try virtio-serial first — survives QEMU live migration.
// The device path depends on the virtio device index (vportNpM where N is
// the virtio-serial controller index). Check common paths.
diff --git a/cmd/microvm-harness/main.go b/cmd/microvm-harness/main.go
new file mode 100644
index 00000000..26cc464f
--- /dev/null
+++ b/cmd/microvm-harness/main.go
@@ -0,0 +1,437 @@
+// Command microvm-harness measures the AWS Lambda MicroVM backend end to end:
+// fill a warm pool, claim from it, exec through Lambda's auth proxy, tear down.
+//
+// It exists to answer two questions that no amount of documentation settles,
+// and that decide whether this backend is viable:
+//
+// 1. Does gRPC actually survive Lambda's JWE proxy? The proxy is documented to
+// support HTTP/2, and gRPC is HTTP/2 — but "supports HTTP/2" and "forwards
+// long-lived bidirectional HTTP/2 streams with custom headers intact" are
+// different claims. If this fails, the agent transport has to change.
+//
+// 2. What does a claim+exec actually cost at burst width? The pool design
+// exists because RunMicrovm is 5/s and ResumeMicrovm is 5/s, so a burst
+// cannot make AWS calls at all. This measures whether the claim path really
+// is free and where the remaining latency sits.
+//
+// It is a measurement tool, not a service: it creates only MicroVMs from the
+// image it is pointed at, and terminates everything it created before exiting.
+//
+// go run ./cmd/microvm-harness -image <ARN> -stock 5 -burst 5
+package main
+
+import (
+ "context"
+ "flag"
+ "fmt"
+ "io"
+ "log"
+ "net/http"
+ "os"
+ "os/signal"
+ "sort"
+ "strings"
+ "sync"
+ "syscall"
+ "time"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ awsconfig "github.com/aws/aws-sdk-go-v2/config"
+ "github.com/gorilla/websocket"
+ "github.com/opensandbox/opensandbox/internal/awsvm"
+ "github.com/opensandbox/opensandbox/pkg/types"
+)
+
+// Ports the image declares: hooks on 8080 (the one Lambda already reaches
+// during the build) and osb-agent's gRPC on 8081.
+const (
+ hookPort int32 = 8080
+ agentPort int32 = 8081
+)
+
+func main() {
+ var (
+ image = flag.String("image", os.Getenv("MICROVM_IMAGE_ARN"), "MicroVM image ARN or name (required)")
+ role = flag.String("role", os.Getenv("MICROVM_EXECUTION_ROLE_ARN"), "execution role ARN assumed by the guest")
+ region = flag.String("region", envOr("AWS_REGION", "us-east-1"), "AWS region")
+ stock = flag.Int("stock", 5, "warm pool depth to fill before claiming")
+ burst = flag.Int("burst", 5, "how many sandboxes to claim+exec simultaneously")
+ command = flag.String("cmd", "node -v", "command to exec in each sandbox")
+ fillWait = flag.Duration("fill-timeout", 5*time.Minute, "how long to wait for the pool to fill")
+ keep = flag.Bool("keep", false, "leave MicroVMs running on exit (for manual poking)")
+ probe = flag.Bool("probe", false, "instead of exec, probe plain HTTP /healthz on the hook port to isolate proxy reachability from gRPC")
+ // Defaults to the hook port: Lambda forwards only there, and the hook
+ // server bridges to the agent. 8081 is kept reachable via this flag
+ // purely to re-demonstrate that a direct agent port returns 502.
+ gPort = flag.Int("agent-port", int(hookPort), "guest port to send gRPC to")
+ // More than one exec per box separates cold-channel cost from steady state.
+ execsPer = flag.Int("execs", 3, "execs per sandbox; the first is cold, the rest warm")
+ )
+ flag.Parse()
+
+ if *image == "" {
+ log.Fatal("-image is required (the MicroVM image ARN built by deploy/microvm/publish.sh)")
+ }
+ if *burst > *stock {
+ log.Fatalf("-burst %d exceeds -stock %d: the point of the pool is that a burst never waits on AWS", *burst, *stock)
+ }
+
+ // Ctrl-C must still terminate what we launched: a leaked MicroVM burns
+ // regional memory quota until it hits the 8h cap, and quota is the ceiling
+ // on pool depth.
+ ctx, stopSignals := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
+ defer stopSignals()
+
+ awsCfg, err := awsconfig.LoadDefaultConfig(ctx, awsconfig.WithRegion(*region))
+ if err != nil {
+ log.Fatalf("load AWS config: %v", err)
+ }
+
+ client := awsvm.NewClient(awsCfg, awsvm.Config{
+ Region: *region,
+ ImageIdentifier: *image,
+ ExecutionRoleArn: *role,
+ AgentPort: int32(*gPort),
+ // Idle-suspend must be off for pooled stock. A box that suspends itself
+ // while waiting turns the next claim into a throttled ResumeMicrovm,
+ // which is the exact cost the pool exists to avoid.
+ AutoResume: false,
+ })
+
+ pool := awsvm.NewPool(client, awsvm.PoolConfig{TargetStock: *stock})
+ mgr := awsvm.NewManager(client, os.TempDir())
+ defer mgr.Close()
+
+ poolCtx, stopPool := context.WithCancel(ctx)
+ defer stopPool()
+ go pool.Run(poolCtx)
+
+ if err := waitForStock(ctx, pool, *stock, *fillWait); err != nil {
+ log.Printf("pool never filled: %v (depth=%d)", err, pool.Depth())
+ if !*keep {
+ pool.Drain()
+ }
+ os.Exit(1)
+ }
+
+ // Stop launching before measuring. Otherwise the launch ticker keeps calling
+ // RunMicrovm during the burst and we would be measuring the pool topping
+ // itself up, not the claim path.
+ stopPool()
+
+ if *probe {
+ probeProxy(ctx, awsCfg, *region, *image, pool)
+ pool.Drain()
+ return
+ }
+
+ results := runBurst(ctx, pool, mgr, *burst, *command, *execsPer)
+ report(results)
+
+ if *keep {
+ log.Printf("-keep set: leaving %d pooled + %d claimed MicroVMs running", pool.Depth(), len(results))
+ return
+ }
+ log.Printf("cleaning up…")
+ for _, r := range results {
+ if r.sandboxID != "" {
+ if err := mgr.Kill(context.WithoutCancel(ctx), r.sandboxID); err != nil {
+ log.Printf(" terminate %s: %v", r.sandboxID, err)
+ }
+ }
+ }
+ pool.Drain()
+}
+
+func envOr(key, def string) string {
+ if v := os.Getenv(key); v != "" {
+ return v
+ }
+ return def
+}
+
+// waitForStock blocks until the pool reaches the target depth, reporting
+// progress so a slow fill is visibly a fill and not a hang.
+func waitForStock(ctx context.Context, pool *awsvm.Pool, target int, timeout time.Duration) error {
+ start := time.Now()
+ deadline := time.Now().Add(timeout)
+ tick := time.NewTicker(2 * time.Second)
+ defer tick.Stop()
+ last := -1
+ for {
+ if d := pool.Depth(); d >= target {
+ log.Printf("pool filled: %d boxes in %s (%.1f boxes/s)",
+ d, time.Since(start).Round(time.Millisecond), float64(d)/time.Since(start).Seconds())
+ return nil
+ } else if d != last {
+ log.Printf(" filling: %d/%d", d, target)
+ last = d
+ }
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-tick.C:
+ if time.Now().After(deadline) {
+ return fmt.Errorf("timed out after %s", timeout)
+ }
+ }
+ }
+}
+
+// result is one sandbox's timings. claim and exec are separated because they
+// answer different questions: claim should be ~0 by construction, while exec is
+// the number that actually reaches the customer.
+type result struct {
+ sandboxID string
+ claim time.Duration
+ // exec is the FIRST exec on a freshly claimed box, which pays the whole
+ // cold-channel cost: token mint, WebSocket handshake, HTTP/2 setup.
+ exec time.Duration
+ // warm are subsequent execs on the same established channel. This is the
+ // number that describes steady-state latency, and the two must never be
+ // conflated — quoting the cold figure as "exec latency" overstates it by
+ // roughly a second.
+ warm []time.Duration
+ stdout string
+ err error
+}
+
+// runBurst claims and execs n sandboxes simultaneously. Simultaneously is the
+// point: a staggered run hides exactly the contention a real create burst hits.
+func runBurst(ctx context.Context, pool *awsvm.Pool, mgr *awsvm.Manager, n int, command string, execs int) []result {
+ log.Printf("bursting %d claim+exec…", n)
+ results := make([]result, n)
+ var wg sync.WaitGroup
+ start := time.Now()
+
+ for i := 0; i < n; i++ {
+ wg.Add(1)
+ go func(i int) {
+ defer wg.Done()
+ sandboxID := fmt.Sprintf("sb-harness-%d-%d", start.UnixNano(), i)
+
+ claimStart := time.Now()
+ entry, ok := pool.Claim()
+ results[i].claim = time.Since(claimStart)
+ if !ok {
+ results[i].err = fmt.Errorf("pool empty")
+ return
+ }
+ results[i].sandboxID = sandboxID
+
+ // Track is what the edge-claim path does: bind a pre-launched box to
+ // a sandbox id without any AWS call.
+ mgr.TrackClaimed(sandboxID, entry, types.SandboxConfig{
+ SandboxID: sandboxID,
+ Template: "microvm",
+ })
+
+ for n := 0; n < execs; n++ {
+ execStart := time.Now()
+ res, err := mgr.Exec(ctx, sandboxID, types.ProcessConfig{
+ Command: command,
+ Timeout: 30,
+ })
+ took := time.Since(execStart)
+ if n == 0 {
+ results[i].exec = took
+ } else {
+ results[i].warm = append(results[i].warm, took)
+ }
+ if err != nil {
+ results[i].err = err
+ return
+ }
+ if res.ExitCode != 0 {
+ results[i].err = fmt.Errorf("exit %d: %s", res.ExitCode, res.Stderr)
+ return
+ }
+ results[i].stdout = res.Stdout
+ }
+ }(i)
+ }
+ wg.Wait()
+ log.Printf("burst wall-clock: %s", time.Since(start).Round(time.Millisecond))
+ return results
+}
+
+// probeProxy isolates "can the proxy reach the guest at all" from "does gRPC
+// work through the proxy".
+//
+// The hook server serves plain HTTP /healthz on port 8080 — the same port and
+// process Lambda already talks to successfully during the image build. If a
+// plain GET through the proxy succeeds while gRPC on 8081 returns 502, the
+// problem is gRPC or that specific port. If BOTH 502, the guest is not
+// admitting proxied traffic at all and the transport is not the issue.
+func probeProxy(ctx context.Context, awsCfg aws.Config, region, image string, pool *awsvm.Pool) {
+ entry, ok := pool.Claim()
+ if !ok {
+ log.Fatal("probe: pool empty")
+ }
+
+ for _, port := range []int32{hookPort, agentPort} {
+ // Tokens are port-scoped, so each probe needs one minted for its port.
+ c := awsvm.NewClient(awsCfg, awsvm.Config{
+ Region: region, ImageIdentifier: image, AgentPort: port,
+ })
+ token, err := c.AuthToken(ctx, entry.MicrovmID)
+ if err != nil {
+ log.Printf("probe port %d: mint token: %v", port, err)
+ continue
+ }
+
+ path := "/healthz"
+ if port == agentPort {
+ // Nothing serves plain HTTP here; we only care which error comes
+ // back — a proxy 502 versus anything originating in the guest.
+ path = "/"
+ }
+ url := awsvm.AgentURL(entry.Endpoint) + path
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
+ if err != nil {
+ log.Printf("probe port %d: %v", port, err)
+ continue
+ }
+ req.Header.Set("X-aws-proxy-auth", token)
+ req.Header.Set("X-aws-proxy-port", fmt.Sprintf("%d", port))
+
+ start := time.Now()
+ resp, err := http.DefaultClient.Do(req)
+ took := time.Since(start).Round(time.Millisecond)
+ if err != nil {
+ log.Printf("probe port %d %s → transport error after %s: %v", port, path, took, err)
+ continue
+ }
+ body, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
+ resp.Body.Close()
+ // Print the body verbatim rather than trimmed: on the hook port it is
+ // the guest's self-report, which is the whole point of the probe.
+ log.Printf("probe port %d %s → HTTP %d in %s (proto=%s) %s",
+ port, path, resp.StatusCode, took, resp.Proto, strings.TrimSpace(string(body)))
+ }
+ // Does an unannounced HTTP/2 trailer survive the proxy? gRPC carries its
+ // status that way, so a "no" here means gRPC cannot work through Lambda at
+ // all and the agent transport has to change; a "yes" means the trailer loss
+ // is ours to fix inside the guest.
+ c := awsvm.NewClient(awsCfg, awsvm.Config{Region: region, ImageIdentifier: image, AgentPort: hookPort})
+ if token, err := c.AuthToken(ctx, entry.MicrovmID); err == nil {
+ req, _ := http.NewRequestWithContext(ctx, http.MethodGet,
+ awsvm.AgentURL(entry.Endpoint)+"/trailer-test", nil)
+ req.Header.Set("X-aws-proxy-auth", token)
+ req.Header.Set("X-aws-proxy-port", fmt.Sprintf("%d", hookPort))
+ if resp, err := http.DefaultClient.Do(req); err != nil {
+ log.Printf("trailer probe: %v", err)
+ } else {
+ // Trailers are only populated after the body is drained.
+ _, _ = io.Copy(io.Discard, resp.Body)
+ resp.Body.Close()
+ got := resp.Trailer.Get("X-Osb-Trailer")
+ if got == "" {
+ log.Printf("trailer probe: TRAILER LOST through the proxy (trailers=%v) → gRPC cannot work as-is", resp.Trailer)
+ } else {
+ log.Printf("trailer probe: trailer survived (X-Osb-Trailer=%q) → proxy is fine, our bridge drops them", got)
+ }
+ }
+ }
+
+ // Does a WebSocket survive the proxy, and does it stream both ways? If so,
+ // gRPC can be tunnelled inside one and the agent's entire API keeps working
+ // unchanged despite trailers being stripped.
+ if token, err := c.AuthToken(ctx, entry.MicrovmID); err == nil {
+ wsURL := "wss://" + hostOnly(entry.Endpoint) + "/ws-test"
+ hdr := http.Header{}
+ hdr.Set("X-aws-proxy-auth", token)
+ hdr.Set("X-aws-proxy-port", fmt.Sprintf("%d", hookPort))
+
+ start := time.Now()
+ conn, resp, err := websocket.DefaultDialer.DialContext(ctx, wsURL, hdr)
+ if err != nil {
+ status := 0
+ if resp != nil {
+ status = resp.StatusCode
+ }
+ log.Printf("ws probe: upgrade FAILED (http=%d): %v → gRPC-over-WebSocket is not available either", status, err)
+ } else {
+ defer conn.Close()
+ payload := []byte("hello-microvm")
+ _ = conn.WriteMessage(websocket.TextMessage, payload)
+ _ = conn.SetReadDeadline(time.Now().Add(10 * time.Second))
+ _, got, rerr := conn.ReadMessage()
+ rtt := time.Since(start).Round(time.Millisecond)
+ if rerr != nil {
+ log.Printf("ws probe: upgraded but echo failed after %s: %v", rtt, rerr)
+ } else if string(got) == string(payload) {
+ log.Printf("ws probe: OK — upgrade + round-trip echo in %s → gRPC can be tunnelled over WebSocket", rtt)
+ } else {
+ log.Printf("ws probe: echo mismatch (%q)", string(got))
+ }
+ }
+ }
+
+ log.Printf("probe: microvm=%s endpoint=%s", entry.MicrovmID, entry.Endpoint)
+}
+
+func report(results []result) {
+ var claims, cold, warm []time.Duration
+ ok := 0
+ fmt.Println()
+ fmt.Println("── per-sandbox ─────────────────────────────────────────────")
+ for _, r := range results {
+ status := "ok"
+ if r.err != nil {
+ status = "FAIL: " + r.err.Error()
+ } else {
+ ok++
+ cold = append(cold, r.exec)
+ warm = append(warm, r.warm...)
+ }
+ claims = append(claims, r.claim)
+ fmt.Printf(" claim=%-9s exec=%-9s %s %s\n",
+ r.claim.Round(time.Microsecond), r.exec.Round(time.Millisecond), status, trim(r.stdout))
+ }
+
+ fmt.Println()
+ fmt.Println("── summary ─────────────────────────────────────────────────")
+ fmt.Printf(" success: %d/%d\n", ok, len(results))
+ printStats("claim", claims)
+ printStats("cold ", cold)
+ printStats("warm ", warm)
+ fmt.Println()
+ if ok == 0 {
+ // The single most important negative result this harness can produce.
+ fmt.Println(" NO EXEC SUCCEEDED — if the errors are transport-level, gRPC")
+ fmt.Println(" does not survive the Lambda proxy and the agent transport")
+ fmt.Println(" must change. Check whether the failures are gRPC status")
+ fmt.Println(" codes (reached the agent) or dial/TLS errors (did not).")
+ }
+}
+
+func printStats(label string, ds []time.Duration) {
+ if len(ds) == 0 {
+ fmt.Printf(" %s: (none)\n", label)
+ return
+ }
+ sorted := append([]time.Duration(nil), ds...)
+ sort.Slice(sorted, func(i, j int) bool { return sorted[i] < sorted[j] })
+ at := func(q float64) time.Duration {
+ idx := int(q * float64(len(sorted)-1))
+ return sorted[idx].Round(time.Millisecond)
+ }
+ fmt.Printf(" %s: min=%s med=%s p95=%s max=%s\n",
+ label, sorted[0].Round(time.Millisecond), at(0.5), at(0.95), sorted[len(sorted)-1].Round(time.Millisecond))
+}
+
+// hostOnly strips the scheme so the endpoint can be rebuilt as wss://.
+func hostOnly(endpoint string) string {
+ return strings.TrimPrefix(awsvm.AgentURL(endpoint), "https://")
+}
+
+// trim renders command output on a single line so the per-sandbox table stays
+// readable when a command is chatty.
+func trim(s string) string {
+ s = strings.TrimSpace(s)
+ if len(s) > 60 {
+ s = s[:60] + "…"
+ }
+ return strings.NewReplacer("\n", " ", "\r", " ").Replace(s)
+}
diff --git a/cmd/microvm-hooks/main.go b/cmd/microvm-hooks/main.go
new file mode 100644
index 00000000..f561463d
--- /dev/null
+++ b/cmd/microvm-hooks/main.go
@@ -0,0 +1,453 @@
+// Command microvm-hooks is the entrypoint for our AWS Lambda MicroVM image.
+//
+// Lambda MicroVMs drives an image through HTTP lifecycle hooks rather than
+// letting the guest come up on its own schedule, and it forwards NO customer
+// traffic until /run returns 200. That gate is worth having: on the QEMU
+// backend, "is the agent ready yet" is something we poll for and occasionally
+// get wrong (the wake-404 strandings, "agent not available"), whereas here the
+// platform simply holds traffic until we say so.
+//
+// This process is PID 1 in the MicroVM. It:
+// - starts osb-agent as a child, listening on TCP (Lambda's proxy can only
+// reach a guest TCP port; there is no virtio-serial or vsock here)
+// - serves the six lifecycle hooks Lambda calls
+// - reaps orphaned children, because being PID 1 means every process the
+// customer leaves behind reparents here, and unreaped zombies eat the
+// sandbox's pid budget until fork() starts failing
+package main
+
+import (
+ "context"
+ "crypto/tls"
+ "encoding/json"
+ "io"
+ "log"
+ "net"
+ "net/http"
+ "net/http/httputil"
+ "os"
+ "os/exec"
+ "os/signal"
+ "strings"
+ "sync"
+ "syscall"
+ "time"
+
+ "github.com/gorilla/websocket"
+ "github.com/opensandbox/opensandbox/internal/wsconn"
+ "golang.org/x/net/http2"
+ "golang.org/x/net/http2/h2c"
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/credentials/insecure"
+
+ pb "github.com/opensandbox/opensandbox/proto/agent"
+)
+
+const (
+ // hookPath is the prefix Lambda calls; the port is declared on the image.
+ hookPath = "/aws/lambda-microvms/runtime/v1/"
+
+ // agentAddr is where osb-agent listens for gRPC.
+ //
+ // Nothing outside the guest reaches this port. Lambda's proxy forwards only
+ // to the port declared in the image's hook configuration (hookAddr below);
+ // requests aimed at any other port return 502 even while that port is
+ // happily accepting connections inside the guest. Verified directly: with
+ // the agent listening here, a gRPC call to 8081 got a proxy 502 while the
+ // identical call to 8080 reached our own mux and was answered by it.
+ //
+ // So this stays loopback-only — it is reached exclusively through the
+ // in-guest bridge on the hook port.
+ agentAddr = "127.0.0.1:8081"
+
+ // agentDialAddr is how this process reaches the agent, for health checks and
+ // for the bridge. Same address; named separately because agentAddr is the
+ // bind string and this is the dial string, and they are only incidentally
+ // equal.
+ agentDialAddr = "127.0.0.1:8081"
+
+ // hookAddr is where Lambda reaches these hooks.
+ hookAddr = ":8080"
+
+ // agentTunnelPath is the WebSocket endpoint carrying gRPC to the agent.
+ // Must match internal/awsvm's dialer.
+ agentTunnelPath = "/osb/agent-grpc"
+)
+
+// runPayload is the body Lambda POSTs to /run. runHookPayload is per-MicroVM
+// (up to 16KB) and is how a pooled box learns which customer it now belongs to
+// — the native equivalent of our PrepareResume env/secret injection.
+type runPayload struct {
+ MicrovmID string `json:"microvmId"`
+ RunHookPayload string `json:"runHookPayload"`
+}
+
+type server struct {
+ mu sync.Mutex
+ agentCmd *exec.Cmd
+ // microvmID is learned at /run and only used for logging; the agent itself
+ // is told nothing about identity, exactly as on the QEMU backend.
+ microvmID string
+}
+
+// startedAt is stamped at process start, which happens during the image BUILD.
+// Every MicroVM resumes from that snapshot, so a large uptime on a freshly
+// launched box is expected and is itself a useful signal that we are looking at
+// a restored snapshot rather than a fresh boot.
+var startedAt = time.Now()
+
+func main() {
+ log.SetFlags(log.LstdFlags | log.Lmicroseconds)
+ log.Printf("microvm-hooks: starting (pid=%d)", os.Getpid())
+
+ startReaper()
+
+ s := &server{}
+ if err := s.startAgent(); err != nil {
+ log.Fatalf("microvm-hooks: start agent: %v", err)
+ }
+
+ mux := http.NewServeMux()
+ mux.HandleFunc(hookPath+"ready", s.handleReady)
+ mux.HandleFunc(hookPath+"validate", s.handleValidate)
+ mux.HandleFunc(hookPath+"run", s.handleRun)
+ mux.HandleFunc(hookPath+"suspend", s.handleSuspend)
+ mux.HandleFunc(hookPath+"resume", s.handleResume)
+ mux.HandleFunc(hookPath+"terminate", s.handleTerminate)
+ // /healthz reports the guest's own view of itself, and is reachable through
+ // Lambda's proxy on the hook port. That matters for diagnosis: runtime logs
+ // from a MicroVM do not reach the image's CloudWatch group (only build-time
+ // logs do), so without this there is no way to tell "the agent died after
+ // the snapshot" apart from "the proxy cannot speak to the agent's port".
+ mux.HandleFunc("/healthz", func(w http.ResponseWriter, _ *http.Request) {
+ s.mu.Lock()
+ cmd, id := s.agentCmd, s.microvmID
+ s.mu.Unlock()
+ pid := 0
+ if cmd != nil && cmd.Process != nil {
+ pid = cmd.Process.Pid
+ }
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "agentUp": agentUp(),
+ "agentPid": pid,
+ "agentAddr": agentAddr,
+ "microvmId": id,
+ "ranRunHook": id != "",
+ "uptimeSec": int(time.Since(startedAt).Seconds()),
+ })
+ })
+
+ // Diagnostic: emit an UNANNOUNCED HTTP/2 trailer, the way gRPC sends
+ // grpc-status. If this trailer does not survive the trip to a client, then
+ // gRPC cannot work through Lambda's proxy no matter how the guest is
+ // arranged — which is a very different problem from our own bridge dropping
+ // it, and the two are indistinguishable from the gRPC error alone.
+ mux.HandleFunc("/trailer-test", func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set(http.TrailerPrefix+"X-Osb-Trailer", "present")
+ w.WriteHeader(http.StatusOK)
+ _, _ = io.WriteString(w, "body\n")
+ })
+
+ // Diagnostic: echo over a WebSocket. Trailers do not survive the proxy, so
+ // gRPC cannot run over plain HTTP here; carrying it inside a WebSocket is
+ // the way to keep the agent's whole API intact. That only works if the
+ // proxy passes an upgrade through and does not buffer the stream, which is
+ // what this measures.
+ mux.HandleFunc("/ws-test", func(w http.ResponseWriter, r *http.Request) {
+ c, err := (&websocket.Upgrader{
+ CheckOrigin: func(*http.Request) bool { return true },
+ }).Upgrade(w, r, nil)
+ if err != nil {
+ log.Printf("microvm-hooks: /ws-test upgrade failed: %v", err)
+ return
+ }
+ defer c.Close()
+ for {
+ mt, msg, err := c.ReadMessage()
+ if err != nil {
+ return
+ }
+ if err := c.WriteMessage(mt, msg); err != nil {
+ return
+ }
+ }
+ })
+
+ // The agent tunnel: a WebSocket carrying osb-agent's gRPC verbatim.
+ //
+ // Lambda's proxy strips HTTP/2 trailers, and gRPC puts its status there, so
+ // forwarding gRPC as ordinary HTTP/2 loses every RPC result even though the
+ // command runs. Inside a WebSocket the proxy sees opaque frames and never
+ // touches the HTTP/2 stream within, so trailers arrive intact.
+ //
+ // This is a byte splice, not an HTTP proxy: whatever gRPC writes goes to the
+ // agent unchanged. That is exactly why it preserves semantics an HTTP-level
+ // proxy could not — and why osb-agent needs no change at all.
+ mux.HandleFunc(agentTunnelPath, s.handleAgentTunnel)
+
+ // Everything that is not a hook is forwarded to osb-agent.
+ //
+ // This exists because Lambda's proxy forwards guest traffic ONLY to the port
+ // declared in the image's hook configuration. A second listener is simply
+ // unreachable: the agent is demonstrably listening on 8081 and requests to
+ // it still come back 502, while the identical request to 8080 arrives. So
+ // the agent cannot have its own port, and rather than teach osb-agent to
+ // share this one — it is the same binary the QEMU backend runs, and forking
+ // its listener setup per backend is how drift starts — we bridge to it here.
+ //
+ // gRPC itself passes through the proxy unharmed; that was verified by
+ // sending a real gRPC call to this port and watching it arrive intact (the
+ // mux answered 404 rather than the proxy answering 502).
+ mux.Handle("/", agentReverseProxy())
+
+ // h2c: serve cleartext HTTP/2 as well as HTTP/1.1. gRPC requires HTTP/2, and
+ // the proxy's hop into the guest is cleartext, so without this the agent
+ // bridge would only ever see HTTP/1.1 and gRPC could not work.
+ handler := h2c.NewHandler(mux, &http2.Server{})
+
+ log.Printf("microvm-hooks: serving hooks + agent bridge on %s (agent at %s)", hookAddr, agentAddr)
+ if err := http.ListenAndServe(hookAddr, handler); err != nil {
+ log.Fatalf("microvm-hooks: serve: %v", err)
+ }
+}
+
+// agentReverseProxy bridges proxied traffic on the hook port to osb-agent's
+// gRPC listener, speaking h2c upstream because gRPC needs HTTP/2.
+func agentReverseProxy() *httputil.ReverseProxy {
+ return &httputil.ReverseProxy{
+ Rewrite: func(r *httputil.ProxyRequest) {
+ r.Out.URL.Scheme = "http"
+ r.Out.URL.Host = agentDialAddr
+ // Preserve the gRPC method path exactly; any rewriting here turns
+ // into an Unimplemented that looks like an agent bug.
+ r.Out.Host = agentDialAddr
+ },
+ Transport: &http2.Transport{
+ // Cleartext HTTP/2 to a loopback listener: no TLS to negotiate, and
+ // nothing to protect against on the guest's own loopback.
+ AllowHTTP: true,
+ DialTLSContext: func(ctx context.Context, network, addr string, _ *tls.Config) (net.Conn, error) {
+ return (&net.Dialer{}).DialContext(ctx, network, addr)
+ },
+ },
+ // Flush every write instead of buffering. gRPC streaming (and our exec
+ // output streaming) deadlocks if the proxy holds frames waiting for a
+ // buffer to fill.
+ FlushInterval: -1,
+ ErrorHandler: func(w http.ResponseWriter, _ *http.Request, err error) {
+ log.Printf("microvm-hooks: agent bridge error: %v", err)
+ http.Error(w, "agent unreachable", http.StatusBadGateway)
+ },
+ }
+}
+
+// startAgent launches osb-agent as a child process in TCP listen mode.
+func (s *server) startAgent() error {
+ cmd := exec.Command("/usr/local/bin/osb-agent")
+ cmd.Env = append(os.Environ(), "OSB_AGENT_LISTEN_TCP="+agentAddr)
+ cmd.Stdout = os.Stdout
+ cmd.Stderr = os.Stderr
+ if err := cmd.Start(); err != nil {
+ return err
+ }
+ s.mu.Lock()
+ s.agentCmd = cmd
+ s.mu.Unlock()
+
+ // A dead agent is a dead sandbox; log it loudly rather than leaving the box
+ // serving hooks while nothing can exec.
+ go func() {
+ err := cmd.Wait()
+ log.Printf("microvm-hooks: WARNING osb-agent exited: %v", err)
+ }()
+ log.Printf("microvm-hooks: osb-agent started (pid=%d)", cmd.Process.Pid)
+ return nil
+}
+
+// handleAgentTunnel upgrades to a WebSocket and splices it to osb-agent's gRPC
+// listener, so a gRPC client on the other side talks to the real agent with its
+// framing — and its trailers — preserved end to end.
+func (s *server) handleAgentTunnel(w http.ResponseWriter, r *http.Request) {
+ ws, err := (&websocket.Upgrader{
+ ReadBufferSize: 64 * 1024,
+ WriteBufferSize: 64 * 1024,
+ // The proxy is the only route in and it has already authenticated the
+ // caller's port-scoped token, so there is no origin to check against.
+ CheckOrigin: func(*http.Request) bool { return true },
+ }).Upgrade(w, r, nil)
+ if err != nil {
+ log.Printf("microvm-hooks: agent tunnel upgrade failed: %v", err)
+ return
+ }
+ defer ws.Close()
+
+ agent, err := net.DialTimeout("tcp", agentDialAddr, 5*time.Second)
+ if err != nil {
+ log.Printf("microvm-hooks: agent tunnel dial %s: %v", agentDialAddr, err)
+ return
+ }
+ defer agent.Close()
+
+ tunnel := wsconn.New(ws)
+ // Copy both directions and stop as soon as either side finishes; leaving the
+ // second copy running would pin a goroutine and a socket per dead tunnel.
+ done := make(chan struct{}, 2)
+ go func() { _, _ = io.Copy(agent, tunnel); done <- struct{}{} }()
+ go func() { _, _ = io.Copy(tunnel, agent); done <- struct{}{} }()
+ <-done
+}
+
+// agentUp reports whether the agent is accepting connections.
+func agentUp() bool {
+ conn, err := net.DialTimeout("tcp", agentDialAddr, 500*time.Millisecond)
+ if err != nil {
+ return false
+ }
+ _ = conn.Close()
+ return true
+}
+
+// handleReady is called during the image BUILD, after ENTRYPOINT starts. 200
+// tells Lambda to snapshot; 503 means retry. Return 503 immediately rather than
+// holding the request open — a held request that outlives the timeout kills the
+// whole build.
+func (s *server) handleReady(w http.ResponseWriter, _ *http.Request) {
+ if !agentUp() {
+ http.Error(w, "agent not listening yet", http.StatusServiceUnavailable)
+ return
+ }
+ log.Printf("microvm-hooks: /ready ok — agent listening, safe to snapshot")
+ w.WriteHeader(http.StatusOK)
+}
+
+// handleValidate runs on a fresh MicroVM started from the newly built image.
+//
+// It is also a performance lever, not just a correctness check: Lambda tracks
+// which regions of the snapshot get touched while serving this hook and
+// prefetches them at run time. So exercising the real exec path here is the
+// direct analogue of our golden-snapshot warm-up — the work we do in this
+// handler is what makes the customer's FIRST exec fast.
+func (s *server) handleValidate(w http.ResponseWriter, _ *http.Request) {
+ if !agentUp() {
+ http.Error(w, "agent not listening yet", http.StatusServiceUnavailable)
+ return
+ }
+ // Warm the AGENT's exec path, not just the binaries.
+ //
+ // Running these straight from this process (as an earlier version did) warms
+ // /bin/sh and node but leaves osb-agent's own exec machinery untouched, and
+ // that machinery is what a customer's first command actually goes through.
+ // Measured cost of skipping it: a flat ~800ms on the first exec of every VM,
+ // independent of the command — /bin/true was as slow as node -v — versus
+ // ~80ms once those pages are resident. Driving the real RPC here folds that
+ // into the image build, where Lambda records the touched snapshot regions and
+ // prefetches them at run time.
+ conn, err := grpc.NewClient(agentDialAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
+ if err != nil {
+ log.Printf("microvm-hooks: /validate agent dial: %v", err)
+ w.WriteHeader(http.StatusOK)
+ return
+ }
+ defer conn.Close()
+ client := pb.NewSandboxAgentClient(conn)
+
+ for _, cmd := range []string{
+ "true",
+ "command -v node >/dev/null && node -v || true",
+ "command -v python3 >/dev/null && python3 --version || true",
+ } {
+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
+ resp, err := client.Exec(ctx, &pb.ExecRequest{
+ Command: "/bin/sh",
+ Args: []string{"-c", cmd},
+ TimeoutSeconds: 15,
+ })
+ cancel()
+ if err != nil {
+ log.Printf("microvm-hooks: /validate agent exec %q: %v", cmd, err)
+ continue
+ }
+ log.Printf("microvm-hooks: /validate agent %q → %s", cmd, strings.TrimSpace(resp.Stdout))
+ }
+ w.WriteHeader(http.StatusOK)
+}
+
+// handleRun is called when a MicroVM starts from the image snapshot. Customer
+// traffic begins only after this returns 200, which makes it the natural place
+// to bind per-sandbox state.
+func (s *server) handleRun(w http.ResponseWriter, r *http.Request) {
+ var p runPayload
+ if body, err := io.ReadAll(io.LimitReader(r.Body, 64*1024)); err == nil && len(body) > 0 {
+ if err := json.Unmarshal(body, &p); err != nil {
+ log.Printf("microvm-hooks: /run payload not JSON (%v) — continuing", err)
+ }
+ }
+ s.mu.Lock()
+ s.microvmID = p.MicrovmID
+ s.mu.Unlock()
+
+ // The agent must be live before we let traffic in; this is the gate that
+ // replaces the QEMU backend's polling for agent readiness.
+ deadline := time.Now().Add(20 * time.Second)
+ for !agentUp() {
+ if time.Now().After(deadline) {
+ log.Printf("microvm-hooks: /run FAILED — agent never came up")
+ http.Error(w, "agent did not start", http.StatusServiceUnavailable)
+ return
+ }
+ time.Sleep(50 * time.Millisecond)
+ }
+
+ log.Printf("microvm-hooks: /run ok (microvm=%s payloadBytes=%d)", p.MicrovmID, len(p.RunHookPayload))
+ w.WriteHeader(http.StatusOK)
+}
+
+// handleSuspend runs before Lambda snapshots for a suspend. AWS captures memory
+// and disk itself, so unlike our QEMU path there is no fsfreeze to coordinate
+// and no torn-snapshot class of bug to defend against.
+func (s *server) handleSuspend(w http.ResponseWriter, _ *http.Request) {
+ log.Printf("microvm-hooks: /suspend")
+ w.WriteHeader(http.StatusOK)
+}
+
+// handleResume runs after a suspended MicroVM is restored, before it returns to
+// RUNNING. Anything that cannot survive a snapshot boundary is re-established
+// here — the counterpart of our PrepareResume.
+func (s *server) handleResume(w http.ResponseWriter, _ *http.Request) {
+ if !agentUp() {
+ // The agent survives inside the snapshot, so this should not happen;
+ // if it does, say so rather than admitting traffic to a dead box.
+ log.Printf("microvm-hooks: /resume WARNING agent not listening after restore")
+ http.Error(w, "agent not listening after resume", http.StatusServiceUnavailable)
+ return
+ }
+ log.Printf("microvm-hooks: /resume ok")
+ w.WriteHeader(http.StatusOK)
+}
+
+func (s *server) handleTerminate(w http.ResponseWriter, _ *http.Request) {
+ log.Printf("microvm-hooks: /terminate")
+ w.WriteHeader(http.StatusOK)
+}
+
+// startReaper drains SIGCHLD. As PID 1 we inherit every orphan the customer's
+// commands leave behind; without wait4 they linger as zombies holding pid-budget
+// slots until fork() fails with "resource temporarily unavailable" on a box that
+// looks idle. Same reasoning as the agent's own reaper on the QEMU backend.
+func startReaper() {
+ ch := make(chan os.Signal, 1)
+ signal.Notify(ch, syscall.SIGCHLD)
+ go func() {
+ for range ch {
+ for {
+ var ws syscall.WaitStatus
+ pid, err := syscall.Wait4(-1, &ws, syscall.WNOHANG, nil)
+ if pid <= 0 || err != nil {
+ break
+ }
+ }
+ }
+ }()
+}
diff --git a/cmd/server/main.go b/cmd/server/main.go
index 7e123bec..81a60d69 100644
--- a/cmd/server/main.go
+++ b/cmd/server/main.go
@@ -222,6 +222,26 @@ func main() {
log.Printf("opensandbox: sandbox domain configured (%s)", cfg.SandboxDomain)
}
+ // MaxWorkers == 0 means "this cell provisions no workers", and is decided
+ // here rather than inside the scaler. Both readings of 0 collapse at this
+ // layer — config.envOrDefaultInt has already substituted the default (10)
+ // for an unset OPENSANDBOX_MAX_WORKERS — so a 0 arriving here can only be
+ // an operator asking for zero. Inside ScalerConfig the two are
+ // indistinguishable (Go's zero value), which is why NewScaler coerces 0 up
+ // to 10 and why setting MAX_WORKERS=0 alone used to keep provisioning.
+ //
+ // This gates two separate things: the compute pool below, and the
+ // registry-backed capacity reporter. The reporter matters as much as the
+ // pool — it derives available_workers by counting registered workers, so on
+ // a cell that has none it publishes 0 forever, and the edge reads that as
+ // "cell full" and refuses to route. A workerless cell needs its capacity to
+ // come from whatever actually serves creates there.
+ workersDisabled := cfg.Mode == "server" && cfg.MaxWorkersPerRegion == 0
+ if workersDisabled {
+ log.Println("opensandbox: OPENSANDBOX_MAX_WORKERS=0 — worker autoscaling disabled, this cell provisions no workers")
+ }
+ opts.WorkersDisabled = workersDisabled
+
// Initialize Redis worker registry in server mode. The scaler reference
// is hoisted to outer scope so the API server can be wired with it later
// for the migrate endpoint (see server.SetMigrator below).
@@ -282,36 +302,16 @@ func main() {
log.Println("opensandbox: sandbox API proxy enabled (data-plane requests proxied to workers)")
}
- // CF-parallel event forwarder. Drains events:{cell_id} from Redis and
- // POSTs HMAC-signed batches to the events-ingest Worker. Inert when
- // CFEventEndpoint is empty — old NATS path keeps running independently.
- if cfg.CFEventEndpoint != "" && cfg.CFEventSecret != "" && cfg.CellID != "" {
- cfClient := controlplane.NewCFEventClient(cfg.CFEventEndpoint, cfg.CFEventSecret, cfg.CellID)
- fwd, err := controlplane.NewEventForwarder(controlplane.EventForwarderConfig{
- Redis: redisRegistry.RedisClient(),
- CellID: cfg.CellID,
- Client: cfClient,
- })
- if err != nil {
- log.Fatalf("event_forwarder: %v", err)
- }
- if err := fwd.Start(context.Background()); err != nil {
- log.Fatalf("event_forwarder start: %v", err)
- }
- defer func() {
- stopCtx, stopCancel := context.WithTimeout(context.Background(), 10*time.Second)
- defer stopCancel()
- _ = fwd.Stop(stopCtx)
- }()
- log.Printf("opensandbox: CF event forwarder started (endpoint=%s cell=%s)", cfg.CFEventEndpoint, cfg.CellID)
- } else if cfg.Mode == "server" {
- log.Printf("opensandbox: CF event forwarder NOT started (CFEventEndpoint/Secret/CellID unset)")
- }
-
// Capacity reporter — periodically pushes a cell_capacity event onto the
// same events:{cell_id} stream the forwarder drains. Feeds the edge's
// pickCell() cascade via D1. Inert when CellID is empty.
- if cfg.CellID != "" {
+ //
+ // Skipped when this cell provisions no workers: counting an empty
+ // registry would publish available_workers=0 on a cell that is serving
+ // creates fine, and two reporters on one stream would alternate and
+ // flap it in and out of the edge's routing set. The backend that owns
+ // the sandboxes reports instead (see microvmBackend.Capacity).
+ if cfg.CellID != "" && !workersDisabled {
cr, err := controlplane.NewCapacityReporter(controlplane.CapacityReporterConfig{
Redis: redisRegistry.RedisClient(),
Registry: redisRegistry,
@@ -337,6 +337,47 @@ func main() {
}
}
+ // Billing does not depend on there being QEMU workers, so the Redis client
+ // and the event forwarder must not either. Both used to live inside the
+ // mode=="server" block above, next to the worker registry that supplies the
+ // client. A MicroVM cell has no workers to register and so never entered
+ // that block: its usage ticks reached local SQLite and stopped there, with
+ // every log line still reporting billing was running.
+ if opts.RedisClient == nil && cfg.RedisURL != "" {
+ redisOpts, err := redis.ParseURL(cfg.RedisURL)
+ if err != nil {
+ log.Fatalf("opensandbox: invalid OPENSANDBOX_REDIS_URL: %v", err)
+ }
+ opts.RedisClient = redis.NewClient(redisOpts)
+ log.Println("opensandbox: Redis client connected (no worker registry — event stream only)")
+ }
+
+ // CF-parallel event forwarder. Drains events:{cell_id} from Redis and POSTs
+ // HMAC-signed batches to the events-ingest Worker. Inert when the CF
+ // endpoint is unset.
+ if cfg.CFEventEndpoint != "" && cfg.CFEventSecret != "" && cfg.CellID != "" && opts.RedisClient != nil {
+ cfClient := controlplane.NewCFEventClient(cfg.CFEventEndpoint, cfg.CFEventSecret, cfg.CellID)
+ fwd, err := controlplane.NewEventForwarder(controlplane.EventForwarderConfig{
+ Redis: opts.RedisClient,
+ CellID: cfg.CellID,
+ Client: cfClient,
+ })
+ if err != nil {
+ log.Fatalf("event_forwarder: %v", err)
+ }
+ if err := fwd.Start(context.Background()); err != nil {
+ log.Fatalf("event_forwarder start: %v", err)
+ }
+ defer func() {
+ stopCtx, stopCancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer stopCancel()
+ _ = fwd.Stop(stopCtx)
+ }()
+ log.Printf("opensandbox: CF event forwarder started (endpoint=%s cell=%s)", cfg.CFEventEndpoint, cfg.CellID)
+ } else if cfg.Mode == "server" {
+ log.Printf("opensandbox: CF event forwarder NOT started (CFEventEndpoint/Secret/CellID unset)")
+ }
+
// Hoisted at function scope so the per-sandbox autoscaler (created
// later, after the API server) can consult IsLeader() each tick — keeps
// a single elector authoritative across both the cluster scaler and the
@@ -344,8 +385,14 @@ func main() {
// (combined / dev mode) — autoscaler then runs unconditionally.
var leaderElector *controlplane.LeaderElector
- // Initialize compute pool + autoscaler (server mode)
- if cfg.Mode == "server" && redisRegistry != nil {
+ // Initialize compute pool + autoscaler (server mode).
+ //
+ // Skipping the pool entirely, rather than capping the scaler at zero, is
+ // what a MicroVM cell needs: AWS holds the VMs, so there is no worker to
+ // launch, drain, roll, or migrate to, and a scaler with nothing to manage
+ // would still contend for the leader lock and log decisions about an empty
+ // fleet forever.
+ if cfg.Mode == "server" && redisRegistry != nil && !workersDisabled {
// Build the WorkerSpec: cloud-neutral config that the CP supplies to
// whichever pool is selected. The pool combines this with cloud-specific
// cloud-init to launch new workers.
@@ -658,7 +705,7 @@ func main() {
for _, w := range redisRegistry.GetAllWorkers() {
liveWorkers[w.ID] = true
}
- orphans, err := opts.Store.MarkOrphanedSandboxes(ctx, liveWorkers)
+ orphans, err := opts.Store.MarkOrphanedSandboxes(ctx, liveWorkers, api.ManagedWorkerIDPrefixes())
if err != nil {
log.Printf("maintenance: orphan reconciliation error: %v", err)
observability.CaptureError(err, "area", "maintenance", "op", "mark_orphaned_sandboxes")
diff --git a/deploy/microvm/Dockerfile b/deploy/microvm/Dockerfile
new file mode 100644
index 00000000..94208071
--- /dev/null
+++ b/deploy/microvm/Dockerfile
@@ -0,0 +1,57 @@
+# MicroVM image for the AWS Lambda MicroVMs backend (internal/awsvm).
+#
+# Lambda runs this Dockerfile on top of its managed MicroVM base environment
+# (al2023-1), starts the ENTRYPOINT, waits for our /ready hook, then snapshots
+# the disk AND memory. Every MicroVM launched from the resulting image resumes
+# from that snapshot — which is why startup is fast, and also why anything
+# baked in here is already warm when a customer arrives.
+#
+# The FROM below is Lambda's own snapshot-compatible container base. We could
+# use our own base instead (private ECR is supported), and eventually should,
+# so that sandboxes on this backend match the runtime customers get on the QEMU
+# backend. For now this stays deliberately minimal: the open question is whether
+# our agent works through Lambda's proxy at all, and a fat image only slows the
+# loop that answers it.
+# Resolves to arm64: Lambda MicroVMs runs ARM_64 only, and the build host is
+# ARM, so the multi-arch base and the binaries build.sh cross-compiles must both
+# be arm64 or the build fails before this file is ever executed.
+FROM public.ecr.aws/lambda/microvms:al2023-minimal
+
+# Runtimes the TTI benchmark and most first commands reach for. Kept small on
+# purpose — see the note above about runtime parity being a later, separate job.
+#
+# shadow-utils is not optional: it provides useradd. The minimal base does not
+# ship it, and without it the sandbox user below is never created — which shows
+# up much later as every exec failing with "fork/exec /bin/sh: no such file or
+# directory", because the agent runs commands in /home/sandbox and Go reports a
+# missing working directory as if the binary were missing.
+RUN dnf install -y nodejs python3 tar gzip ca-certificates shadow-utils \
+ && dnf clean all \
+ && rm -rf /var/cache/dnf
+
+# osb-agent is the same binary the QEMU backend runs in-guest; only its
+# listener differs (TCP here, virtio-serial there), selected by the env var the
+# hook server sets when it spawns the agent.
+COPY osb-agent /usr/local/bin/osb-agent
+COPY microvm-hooks /usr/local/bin/microvm-hooks
+RUN chmod +x /usr/local/bin/osb-agent /usr/local/bin/microvm-hooks
+
+# A sandbox user so customer commands do not run as root — matching the QEMU
+# backend, where exec deliberately runs unprivileged. internal/agent runs every
+# exec as this user with cwd /home/sandbox, so both must exist.
+#
+# Deliberately NOT tolerant of failure: an earlier `|| true` here hid a missing
+# useradd and turned a build-time problem into an every-exec runtime failure.
+RUN useradd --create-home --shell /bin/bash sandbox \
+ && test -d /home/sandbox
+
+# Documentation only. Lambda's proxy forwards guest traffic solely to the port
+# declared in the image's hook configuration (8080) — EXPOSE does not influence
+# that, which was confirmed by adding 8081 here and watching it stay 502.
+# osb-agent's 8081 is reachable only via the in-guest bridge in cmd/microvm-hooks.
+EXPOSE 8080
+
+# microvm-hooks is PID 1: it supervises osb-agent, serves the lifecycle hooks
+# Lambda calls, and reaps orphaned children (unreaped zombies otherwise exhaust
+# the pid budget on a box that looks idle).
+ENTRYPOINT ["/usr/local/bin/microvm-hooks"]
diff --git a/deploy/microvm/build.sh b/deploy/microvm/build.sh
new file mode 100755
index 00000000..89cb7da4
--- /dev/null
+++ b/deploy/microvm/build.sh
@@ -0,0 +1,53 @@
+#!/usr/bin/env bash
+# Package the MicroVM image artifact and upload it to S3.
+#
+# Lambda MicroVMs takes a ZIP containing a Dockerfile plus its build context,
+# NOT a prebuilt container image — Lambda runs the Dockerfile itself on its own
+# build infrastructure. So this script only cross-compiles the two binaries,
+# zips them next to the Dockerfile, and uploads.
+#
+# Creating or updating the image resource is a separate step (CreateMicrovmImage
+# / UpdateMicrovmImage) so that packaging stays safe to re-run and cannot touch
+# any image resource by accident.
+#
+# ./deploy/microvm/build.sh s3://my-bucket/microvm/agent-image.zip
+set -euo pipefail
+
+DEST="${1:-}"
+if [[ -z "$DEST" ]]; then
+ echo "usage: $0 s3://bucket/key.zip" >&2
+ exit 2
+fi
+
+REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
+STAGE="$(mktemp -d)"
+trap 'rm -rf "$STAGE"' EXIT
+
+# Lambda MicroVMs is ARM-only: CreateMicrovmImage's cpu-configurations accepts
+# exactly one architecture, ARM_64. An amd64 artifact fails the build before the
+# Dockerfile ever runs, which surfaces as a bare CREATE_FAILED with no
+# stateReason and no CloudWatch log group — so pin the arch here rather than
+# inheriting the developer's laptop and rediscovering that the hard way.
+export CGO_ENABLED=0 GOOS=linux GOARCH=arm64
+
+echo "building osb-agent + microvm-hooks (${GOOS}/${GOARCH})…"
+go build -o "$STAGE/osb-agent" "$REPO_ROOT/cmd/agent"
+go build -o "$STAGE/microvm-hooks" "$REPO_ROOT/cmd/microvm-hooks"
+cp "$REPO_ROOT/deploy/microvm/Dockerfile" "$STAGE/Dockerfile"
+
+ZIP="$STAGE/artifact.zip"
+( cd "$STAGE" && zip -q -r "$ZIP" Dockerfile osb-agent microvm-hooks )
+echo "artifact: $(du -h "$ZIP" | cut -f1)"
+
+echo "uploading → $DEST"
+aws s3 cp "$ZIP" "$DEST"
+
+cat <<EOF
+
+uploaded. Now publish the image resource:
+
+ ./deploy/microvm/publish.sh $DEST
+
+publish.sh carries the hook declaration and ARM_64 config that this artifact
+assumes; publishing by hand without them fails the build.
+EOF
diff --git a/deploy/microvm/publish.sh b/deploy/microvm/publish.sh
new file mode 100755
index 00000000..3ff4d7d7
--- /dev/null
+++ b/deploy/microvm/publish.sh
@@ -0,0 +1,117 @@
+#!/usr/bin/env bash
+# Publish (create or update) the MicroVM image resource from an uploaded artifact.
+#
+# Split out from build.sh because the image resource carries configuration the
+# artifact alone cannot express — the hook port, which hooks are enabled, and the
+# CPU architecture. Getting any of those wrong fails the build with a bare
+# CREATE_FAILED: no stateReason, and no CloudWatch log group, because the build
+# never reaches the point of running the Dockerfile. Keeping the invocation in a
+# script rather than in copy-paste instructions is what stops that recurring.
+#
+# ./deploy/microvm/publish.sh s3://bucket/agent-image.zip
+set -euo pipefail
+
+DEST="${1:-}"
+if [[ -z "$DEST" ]]; then
+ echo "usage: $0 s3://bucket/key.zip" >&2
+ exit 2
+fi
+
+REGION="${AWS_REGION:-us-east-1}"
+NAME="${MICROVM_IMAGE_NAME:-opensandbox-agent-dev}"
+ACCOUNT="$(aws sts get-caller-identity --query Account --output text)"
+IMAGE_ARN="arn:aws:lambda:${REGION}:${ACCOUNT}:microvm-image:${NAME}"
+BASE_IMAGE_ARN="${MICROVM_BASE_IMAGE_ARN:-arn:aws:lambda:${REGION}:aws:microvm-image:al2023-1}"
+BUILD_ROLE_ARN="${MICROVM_BUILD_ROLE_ARN:-arn:aws:iam::${ACCOUNT}:role/opensandbox-microvm-build}"
+
+# The hook contract, mirroring cmd/microvm-hooks. Lambda will not call a hook we
+# do not declare here, so an undeclared /ready means nothing ever signals that
+# the image is safe to snapshot.
+#
+# Timeouts: run/resume are on the customer's critical path and capped at 60s by
+# the API, so they are kept tight — a box that cannot produce a live agent in
+# 20s is broken, and failing fast is better than admitting traffic to it. The
+# build-time hooks get far longer because /validate deliberately exercises the
+# exec path to drive snapshot-region prefetch.
+HOOKS=$(cat <<'JSON'
+{
+ "port": 8080,
+ "microvmHooks": {
+ "run": "ENABLED",
+ "runTimeoutInSeconds": 30,
+ "resume": "ENABLED",
+ "resumeTimeoutInSeconds": 30,
+ "suspend": "ENABLED",
+ "suspendTimeoutInSeconds": 30,
+ "terminate": "ENABLED",
+ "terminateTimeoutInSeconds": 30
+ },
+ "microvmImageHooks": {
+ "ready": "ENABLED",
+ "readyTimeoutInSeconds": 300,
+ "validate": "ENABLED",
+ "validateTimeoutInSeconds": 300
+ }
+}
+JSON
+)
+
+# ARM_64 is the only architecture Lambda MicroVMs accepts. build.sh cross-compiles
+# to match; stating it explicitly here keeps the two from drifting apart silently.
+CPU='[{"architecture":"ARM_64"}]'
+
+# 2048 MiB is the smallest baseline that still gets a full vCPU under Lambda's
+# baseline-peak model, and peak scales to 4x it.
+RESOURCES='[{"minimumMemoryInMiB":2048}]'
+
+# Name the log group explicitly so build failures are greppable at a known path
+# instead of wherever the service would otherwise default.
+LOGGING="{\"cloudWatch\":{\"logGroup\":\"/aws/lambda/microvms/${NAME}\"}}"
+
+common=(
+ --code-artifact "uri=${DEST}"
+ --base-image-arn "$BASE_IMAGE_ARN"
+ --build-role-arn "$BUILD_ROLE_ARN"
+ --hooks "$HOOKS"
+ --cpu-configurations "$CPU"
+ --resources "$RESOURCES"
+ --logging "$LOGGING"
+ --region "$REGION"
+)
+
+# Only ever create or update the image we own, identified by our own name. This
+# account is shared with a customer-serving workload; nothing here enumerates or
+# touches an image it did not create.
+if aws lambda-microvms get-microvm-image --image-identifier "$IMAGE_ARN" --region "$REGION" >/dev/null 2>&1; then
+ echo "updating existing image ${NAME}…"
+ # base-image-arn and build-role-arn are required on every update, even when
+ # only the artifact changed — omitting them is a ValidationException.
+ aws lambda-microvms update-microvm-image --image-identifier "$IMAGE_ARN" "${common[@]}"
+else
+ echo "creating image ${NAME}…"
+ aws lambda-microvms create-microvm-image --name "$NAME" "${common[@]}"
+fi
+
+echo
+echo "build is asynchronous; polling until it leaves CREATING…"
+while true; do
+ state="$(aws lambda-microvms get-microvm-image --image-identifier "$IMAGE_ARN" --region "$REGION" \
+ --query 'state' --output text 2>/dev/null || echo UNKNOWN)"
+ echo " state=${state}"
+ case "$state" in
+ # CREATED is a first build; UPDATED is every subsequent one. Both mean the
+ # build finished — check latestActiveImageVersion for what to actually run.
+ CREATED|UPDATED|ACTIVE)
+ echo "image ready: ${IMAGE_ARN}"
+ aws lambda-microvms get-microvm-image --image-identifier "$IMAGE_ARN" --region "$REGION" \
+ --query '{active:latestActiveImageVersion,failed:latestFailedImageVersion}'
+ exit 0 ;;
+ *FAILED*)
+ echo "build FAILED — reason (if any) and logs:" >&2
+ aws lambda-microvms get-microvm-image --image-identifier "$IMAGE_ARN" --region "$REGION" >&2 || true
+ aws logs tail "/aws/lambda/microvms/${NAME}" --since 30m --region "$REGION" >&2 || \
+ echo " (no log group — the build failed before running the Dockerfile)" >&2
+ exit 1 ;;
+ esac
+ sleep 15
+done
diff --git a/go.mod b/go.mod
index 79cd35cc..849be631 100644
--- a/go.mod
+++ b/go.mod
@@ -11,11 +11,12 @@ require (
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.6.4
github.com/BurntSushi/toml v1.6.0
github.com/Masterminds/semver/v3 v3.5.0
- github.com/aws/aws-sdk-go-v2 v1.43.0
+ github.com/aws/aws-sdk-go-v2 v1.43.5
github.com/aws/aws-sdk-go-v2/config v1.32.31
github.com/aws/aws-sdk-go-v2/credentials v1.19.30
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.35
github.com/aws/aws-sdk-go-v2/service/ec2 v1.290.1
+ github.com/aws/aws-sdk-go-v2/service/lambdamicrovms v1.2.5
github.com/aws/aws-sdk-go-v2/service/s3 v1.106.0
github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.41.2
github.com/aws/aws-sdk-go-v2/service/ssm v1.68.4
@@ -35,6 +36,7 @@ require (
github.com/spf13/cobra v1.10.2
github.com/stripe/stripe-go/v82 v82.5.1
github.com/workos/workos-go/v4 v4.46.1
+ golang.org/x/net v0.49.0
golang.org/x/sync v0.20.0
golang.org/x/sys v0.42.0
golang.org/x/term v0.40.0
@@ -49,8 +51,8 @@ require (
github.com/AzureAD/microsoft-authentication-library-for-go v1.6.0 // indirect
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.14 // indirect
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.31 // indirect
- github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.31 // indirect
- github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.31 // indirect
+ github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.36 // indirect
+ github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.36 // indirect
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.32 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.13 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.24 // indirect
@@ -60,7 +62,7 @@ require (
github.com/aws/aws-sdk-go-v2/service/sso v1.33.0 // indirect
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.38.0 // indirect
github.com/aws/aws-sdk-go-v2/service/sts v1.45.0 // indirect
- github.com/aws/smithy-go v1.27.3 // indirect
+ github.com/aws/smithy-go v1.27.7 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
@@ -91,7 +93,6 @@ require (
github.com/valyala/fasttemplate v1.2.2 // indirect
go.uber.org/atomic v1.11.0 // indirect
golang.org/x/crypto v0.47.0 // indirect
- golang.org/x/net v0.49.0 // indirect
golang.org/x/text v0.33.0 // indirect
golang.org/x/time v0.8.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20241015192408-796eee8c2d53 // indirect
diff --git a/go.sum b/go.sum
index 9f1b235b..875b8adf 100644
--- a/go.sum
+++ b/go.sum
@@ -32,8 +32,8 @@ github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk
github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/Masterminds/semver/v3 v3.5.0 h1:kQceYJfbupGfZOKZQg0kou0DgAKhzDg2NZPAwZ/2OOE=
github.com/Masterminds/semver/v3 v3.5.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM=
-github.com/aws/aws-sdk-go-v2 v1.43.0 h1:fharf/WhbRAVZ1du0QL7roNFxZ6T/sWr+4Ni617bwSI=
-github.com/aws/aws-sdk-go-v2 v1.43.0/go.mod h1:5pKeft2eJj+gElQ38Jqg4ibCqh+/AK33/0X3hip7IjM=
+github.com/aws/aws-sdk-go-v2 v1.43.5 h1:yKT5GYnFWhuDo+DqKvE5ZPwVn3RjC4MAeBtZGlh6AVM=
+github.com/aws/aws-sdk-go-v2 v1.43.5/go.mod h1:wZjAJppCntyOGgVSmgVTfDyRJK5PHOasO6Wsy8U7Axk=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.14 h1:3IZY0XAJquT3aHzbkHfPzy4ACPcEjVG0x87KOwtpqGY=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.14/go.mod h1:zwM6veDkhGgQFqkBy+uT28AAYpLu+uFMlPl+rCg/73E=
github.com/aws/aws-sdk-go-v2/config v1.32.31 h1:n4nY9O3QKoHIkL85EX+V8RcMFtOhlpTFhGArg915PXk=
@@ -44,10 +44,10 @@ github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.31 h1:kfVL5wAunCJycL6MOQ6aNh
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.31/go.mod h1:nWfRNDAppujCQgOUd43lKT4yeLv9z3nJ3bw1G3BgQKo=
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.35 h1:TwCjUC1rnFKTtfqEpQY9ClYPFpGpUaouODrdGPB5b3Y=
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.35/go.mod h1:V0zqtP3iJk9zu86GxuQGN09RYyQB+3mjcPiyfLC6wlg=
-github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.31 h1:Z8F3hfCY33IGpJjFAnv0wvtv1FIKj1GHmRDEYqy64tw=
-github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.31/go.mod h1:aVyUoytEyOViR6jhq6jula0xkc5NfBE2hgeF6BvOrao=
-github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.31 h1:hyOxUyXdh3AyjE93gBgsfziJag9ACwcs+ZpDBLzi8mw=
-github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.31/go.mod h1:OERqI9k0draSLB8O8woxY3q25ZWTELRK4RRoLMuMZFo=
+github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.36 h1:5CrzwxDqf4w3x1Vs3/NiZ0nsC34Hbm3pIDMWbsLebOE=
+github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.36/go.mod h1:A3gHdKZIvG/QXERzZwcxNS3RNDFcRCuhhTFBYp+V/nw=
+github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.36 h1:A4N2f4YPcST0v+dWtX+xrpPPCL9VTBhoIFFUWYqbacE=
+github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.36/go.mod h1:B/Qr859uxWUEfZeGotK5KAEoof4Q9YWgNtPSwV6jcyk=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.32 h1:0MrUL35H/Y4kdFfItoR5jCgtDQ4Z/8LudAoIHRfA4hE=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.32/go.mod h1:2tNZkuWz54arj8mHVf+8Y7cKkcD8Wr/fBpENgEXpjLc=
github.com/aws/aws-sdk-go-v2/service/ec2 v1.290.1 h1:iNxv8JSlaMFSo/DDDGsAPgvPuONsfNp6kyJnzjHgIQ4=
@@ -60,6 +60,8 @@ github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.31 h1:w2SIhW92
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.31/go.mod h1:wAhpCQbkov+IcvjozJbd2xRCoZybUEHNkcFunssNACg=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.32 h1:jWXtZdCnhXa9sGFixRaU2AxT4DIVse9HS4E2f+/KwV0=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.32/go.mod h1:9JS1UpfVvyD/ZPX8GsKb/Pq8scEM+7GP5fqh9SwH7po=
+github.com/aws/aws-sdk-go-v2/service/lambdamicrovms v1.2.5 h1:p9nw/hXe7Q/89Q6q96gzhV9V02wO/w02VtS54/y9uGA=
+github.com/aws/aws-sdk-go-v2/service/lambdamicrovms v1.2.5/go.mod h1:vAuBcAkrPH1XicBB5cpsijcRma9waOnrrKh93Bhknio=
github.com/aws/aws-sdk-go-v2/service/s3 v1.106.0 h1:7QZWVJZWzHivHWIa+5TELLaBBkbuoj0GPwQtMlJ0sqk=
github.com/aws/aws-sdk-go-v2/service/s3 v1.106.0/go.mod h1:fcvq5L7dK+5cQFicEJwpI6e6Wn8NY2i6yT5wRLYVc7s=
github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.41.2 h1:hezAo5AQM0moD4qitsn8bZuc2WE/MmP+cySGfJWEi1A=
@@ -74,8 +76,8 @@ github.com/aws/aws-sdk-go-v2/service/ssooidc v1.38.0 h1:tC323YV77QdafeBr6LUhLDTs
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.38.0/go.mod h1:SfLK1sgviHmbI+MozR9iDwDjL4cdCVZtahsjoR+z7wg=
github.com/aws/aws-sdk-go-v2/service/sts v1.45.0 h1:Pd6PNlp4t8PTXxqzstICl52Wsy78vpjFZ7PRUj44mJc=
github.com/aws/aws-sdk-go-v2/service/sts v1.45.0/go.mod h1:rmQ0TnHzuLPmabgjPcsywhsSOmaBDgzR4zvDxSPsGdg=
-github.com/aws/smithy-go v1.27.3 h1:F3Zb497UhhskkfpJmfkXswyo+t0sh9OTBnIHjogWbVY=
-github.com/aws/smithy-go v1.27.3/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
+github.com/aws/smithy-go v1.27.7 h1:Zgj5z4LfcDYoQIVk+n/yGdTkP/2y6ZT5vYxe0fp7bqE=
+github.com/aws/smithy-go v1.27.7/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 h1:DDGfHa7BWjL4YnC6+E63dPcxHo2sUxDIu8g3QgEJdRY=
diff --git a/internal/api/admin_events.go b/internal/api/admin_events.go
index 507dc206..c94ee855 100644
--- a/internal/api/admin_events.go
+++ b/internal/api/admin_events.go
@@ -22,9 +22,9 @@ type AdminEvent struct {
// AdminEventBus broadcasts events to connected SSE clients.
type AdminEventBus struct {
- mu sync.RWMutex
- clients map[chan AdminEvent]struct{}
- history []AdminEvent // last 200 events
+ mu sync.RWMutex
+ clients map[chan AdminEvent]struct{}
+ history []AdminEvent // last 200 events
}
// NewAdminEventBus creates a new event bus.
diff --git a/internal/api/backend.go b/internal/api/backend.go
new file mode 100644
index 00000000..011bb259
--- /dev/null
+++ b/internal/api/backend.go
@@ -0,0 +1,294 @@
+package api
+
+import (
+ "context"
+
+ "github.com/labstack/echo/v4"
+
+ "github.com/opensandbox/opensandbox/internal/db"
+ "github.com/opensandbox/opensandbox/internal/sandbox"
+ "github.com/opensandbox/opensandbox/pkg/types"
+)
+
+// backend.go — the seam between sandbox runtimes.
+//
+// sandbox.Manager already abstracts what you do *to* a sandbox: exec, files,
+// stats, kill. What it never abstracted is everything around it — which runtime
+// serves a create, how to reach a sandbox once it exists, whether a cell has
+// capacity, and who owns a given worker_id. Those decisions were open-coded as
+// `if s.microvm != nil` at each site, which is how a MicroVM-only cell shipped
+// with its claim in a handler the edge never calls, its exec routed to a worker
+// proxy that marked healthy boxes dead, and its sandboxes reaped seconds after
+// creation by a sweep that equates "no registered worker" with "gone".
+//
+// Every one of those failed silently. That is the signature of a missing seam
+// rather than missing code: a new call site has no way to know it owed the
+// question an answer.
+//
+// Deliberately NOT covered here: the worker registry itself. Fifty-one call
+// sites across admin, dashboard, pool manufacture, and the scaler read it
+// directly, and almost all are genuine QEMU-fleet operations rather than
+// sandbox placement. Pulling them behind this interface would multiply the
+// work without making any runtime decision clearer.
+
+// Backend is one sandbox runtime: how to place a sandbox on it, how to reach
+// one it holds, what capacity it has, and how to recognize what it owns.
+type Backend interface {
+ // Name identifies the backend in logs and telemetry. Never returned to a
+ // customer — nothing here should describe our infrastructure to them.
+ Name() string
+
+ // OwnsWorkerID reports whether a persisted worker_id belongs to this
+ // backend. This is the durable identity question: the reconciler, the
+ // orphan sweep, and the event publisher all need to know who holds a
+ // sandbox using only what is in the database.
+ OwnsWorkerID(workerID string) bool
+
+ // WorkerIDPrefixes lists every worker_id prefix this backend writes or
+ // still reads. Queries that must reason about ownership in SQL — the
+ // restore scan, the orphan sweep — take these instead of hardcoding
+ // literals, so adding a backend cannot leave a predicate behind. Empty
+ // means the backend uses real registered worker ids.
+ WorkerIDPrefixes() []string
+
+ // Route returns the manager serving a sandbox this backend holds, or false
+ // if it does not hold it. False must mean "not mine", never "mine but
+ // unavailable" — the caller reads false as permission to try elsewhere.
+ Route(ctx context.Context, sandboxID string) (sandbox.Manager, bool)
+
+ // Capacity reports placement numbers for the cell, in the shape the edge
+ // consumes: it gates routing on available > 0.
+ Capacity() (healthy, available, running int)
+
+ // Reconcile settles persisted state against the runtime's own view —
+ // adopting what is still alive, closing out what is gone. Nothing else
+ // notices a backend-side death, so skipping it leaks both database rows
+ // and running compute.
+ Reconcile(ctx context.Context, store *db.Store)
+
+ // Close releases whatever the backend holds that would outlive the process.
+ // Warm stock is the case that matters: a redeploy that abandons it leaks a
+ // full pool on every rollout, and those hosts bill and hold capacity until
+ // their lifetime cap. Must be safe on a disabled backend.
+ Close()
+}
+
+// knownBackends is every backend this build can run, enabled or not. Their
+// prefix methods must be safe on a nil receiver — they are called on the zero
+// value here.
+//
+// Separate from the Server's registry because the orphan sweep runs from
+// cmd/server before any Server exists, and because its predicate should cover
+// backends that are currently disabled: rows written while one was enabled
+// outlive the flag, and forgetting them would reap live sandboxes.
+var knownBackends = []Backend{(*microvmBackend)(nil)}
+
+// ManagedWorkerIDPrefixes is the union of every known backend's worker_id
+// prefixes, for callers that must recognize managed sandboxes in SQL before the
+// Server is constructed.
+func ManagedWorkerIDPrefixes() []string {
+ var out []string
+ for _, b := range knownBackends {
+ out = append(out, b.WorkerIDPrefixes()...)
+ }
+ return out
+}
+
+// Placer is a Backend that can accept new sandboxes.
+//
+// Split from Backend because the two capabilities are genuinely independent: a
+// runtime can own and serve existing sandboxes without being somewhere new ones
+// should land — a backend being drained, or one whose creates are still handled
+// by another path. Folding Claim into Backend made registration imply placement,
+// so registering a runtime for routing alone would silently divert every create
+// to it and fail them.
+type Placer interface {
+ Backend
+
+ // Claim places a new sandbox and returns the worker_id to persist. An
+ // error is terminal for the create — the caller must not fall through to
+ // another path, because a backend that could not place a sandbox has
+ // already decided the answer.
+ Claim(ctx context.Context, p placement) (workerID string, err error)
+
+ // Activate starts the host chosen by Claim. It runs AFTER the pending row
+ // is written, because a backend may need that row to exist while booting —
+ // see runCreate for the ordering and why it is not negotiable.
+ //
+ // A backend whose hosts are already running has nothing to start and
+ // returns immediately; the create is complete once the row is written.
+ Activate(ctx context.Context, a activation) (activated, error)
+
+ // RequiresPersistedRow reports whether losing the session row strands the
+ // host, which decides whether a failed database write fails the create.
+ //
+ // False for a backend that can enumerate what it is running on its own —
+ // its reconciler rediscovers the sandbox and the missing row is a temporary
+ // gap, so failing the create would destroy a working sandbox over a
+ // database blip. True for a backend that rebuilds its view *from* these
+ // rows, where an unwritten row is a host nothing will ever reclaim.
+ RequiresPersistedRow() bool
+
+ // Release gives back a claim that will not be activated, after a create
+ // fails between the two calls.
+ //
+ // Without it every failed create leaks whatever Claim reserved. What that
+ // costs depends on the backend — a held connection, or a running host that
+ // bills and occupies capacity with nothing tracking it — so the backend
+ // decides what giving it back means. Must be safe to call for a sandbox
+ // that was never claimed.
+ Release(ctx context.Context, sandboxID, workerID string)
+}
+
+// placement is the request-scoped input to Claim.
+//
+// Region is here rather than on the backend because it is a property of the
+// request, not the runtime: the caller may override the cell's own region per
+// create. Passing it through the config would not work — SandboxConfig is the
+// customer's document and carries no placement fields.
+type placement struct {
+ sandboxID string
+ region string
+ cfg types.SandboxConfig
+}
+
+// activation is everything needed to start a host Claim already chose.
+//
+// Wider than SandboxConfig because activation depends on work done between the
+// two calls: the template resolved to concrete drive keys, and the sandbox got
+// an identity a host can present when dialing back to us. Squeezing those into
+// the customer's config would put control-plane internals in a document the
+// customer writes.
+type activation struct {
+ sandboxID string
+ workerID string
+ cfg types.SandboxConfig
+
+ // templateRootfsKey and templateWorkspaceKey are the resolved snapshot
+ // drives, empty for a base-golden create.
+ templateRootfsKey string
+ templateWorkspaceKey string
+
+ // connectToken authorizes the host's outbound data-plane dial back to us.
+ connectToken string
+}
+
+// activated is what the host reported once it was up.
+//
+// goldenVersion is the image the host actually built the sandbox from, which is
+// not always the one the placement record implies — a worker mid-roll can serve
+// a create from either. A later live-migrate rebases against this value, so a
+// wrong or empty one makes the sandbox unmigratable.
+type activated struct {
+ sandboxID string
+ status string
+ goldenVersion string
+}
+
+// registerBackend adds a runtime to the dispatch set.
+//
+// Order is significant: claimBackend serves new sandboxes from the first
+// registered backend, so registration order is placement policy.
+func (s *Server) registerBackend(b Backend) {
+ if b == nil {
+ return
+ }
+ s.backends = append(s.backends, b)
+}
+
+// backendFor finds the backend holding an existing sandbox.
+//
+// Asks each backend rather than consulting worker_id, because routing happens
+// on the request path where the in-memory binding is authoritative and a
+// database read is not free. OwnsWorkerID covers the cases that start from
+// persisted state instead.
+func (s *Server) backendFor(ctx context.Context, sandboxID string) (Backend, sandbox.Manager, bool) {
+ for _, b := range s.backends {
+ if mgr, ok := b.Route(ctx, sandboxID); ok {
+ return b, mgr, true
+ }
+ }
+ return nil, nil, false
+}
+
+// managedWorkerIDPrefixes collects the prefixes of every registered backend,
+// for the SQL that has to recognize managed sandboxes without a live lookup.
+func (s *Server) managedWorkerIDPrefixes() []string {
+ var out []string
+ for _, b := range s.backends {
+ out = append(out, b.WorkerIDPrefixes()...)
+ }
+ return out
+}
+
+// backendForWorkerID finds the backend that owns a persisted worker_id, for
+// callers working from database rows rather than live requests.
+func (s *Server) backendForWorkerID(workerID string) (Backend, bool) {
+ for _, b := range s.backends {
+ if b.OwnsWorkerID(workerID) {
+ return b, true
+ }
+ }
+ return nil, false
+}
+
+// claimBackend returns the backend that should serve a new create, or false to
+// leave the create to the worker path.
+//
+// Only Placers are considered, so a backend registered for routing or identity
+// alone never becomes the create path by accident.
+//
+// The QEMU fleet is deliberately not registered: it is reached by falling
+// through, exactly as before. Making it a Placer means splitting
+// createSandboxRemote, which today mixes worker selection, a 30s capacity
+// poll, persistence, token minting, and response shaping in one function on
+// the path that serves all current traffic. That split is worth doing
+// deliberately, not as a side effect of introducing the seam.
+func (s *Server) claimBackend() (Placer, bool) {
+ for _, b := range s.backends {
+ if p, ok := b.(Placer); ok {
+ return p, true
+ }
+ }
+ return nil, false
+}
+
+// dispatchDataPlane picks between serving a request in-process and proxying it
+// to the worker that holds the sandbox.
+//
+// The default must be the proxy: a sandbox with no registered backend is a
+// worker's, and that is every sandbox on the QEMU fleet. Getting this backwards
+// is not a graceful degradation — the local handlers assume a manager that is
+// nil there, and the proxy assumes a registry entry that does not exist for a
+// backend-held sandbox.
+func (s *Server) dispatchDataPlane(local, proxied echo.HandlerFunc) echo.HandlerFunc {
+ return func(c echo.Context) error {
+ if _, mgr, ok := s.backendFor(c.Request().Context(), c.Param("id")); ok && mgr != nil {
+ return local(c)
+ }
+ return proxied(c)
+ }
+}
+
+// managerFor returns the manager that should serve this request: the holding
+// backend's when one holds the sandbox, otherwise the local manager.
+//
+// Handlers that reach for s.manager directly are correct only on a cell that
+// has one. On a control plane serving a managed backend s.manager is nil, so
+// those handlers answer "sandbox execution not available in server-only mode"
+// for a sandbox that is running fine — which is exactly what the filesystem
+// routes did once they were dispatched in-process.
+func (s *Server) managerFor(c echo.Context) sandbox.Manager {
+ if _, mgr, ok := s.backendFor(c.Request().Context(), c.Param("id")); ok && mgr != nil {
+ return mgr
+ }
+ return s.manager
+}
+
+// execManagerFor reports the manager serving a sandbox in-process, if any.
+// Retained as the name the data-plane routes call; the decision now comes from
+// the backend registry rather than a hardcoded runtime check.
+func (s *Server) execManagerFor(sandboxID string) (sandbox.Manager, bool) {
+ _, mgr, ok := s.backendFor(context.Background(), sandboxID)
+ return mgr, ok
+}
diff --git a/internal/api/backend_conformance_test.go b/internal/api/backend_conformance_test.go
new file mode 100644
index 00000000..1b4d39c2
--- /dev/null
+++ b/internal/api/backend_conformance_test.go
@@ -0,0 +1,295 @@
+package api
+
+import (
+ "context"
+ "strings"
+ "testing"
+
+ "github.com/opensandbox/opensandbox/internal/db"
+ "github.com/opensandbox/opensandbox/internal/sandbox"
+)
+
+// backend_conformance_test.go — one contract, run against every Backend.
+//
+// Adding a backend means adding a row to conformanceBackends. Every invariant
+// below then applies to it automatically, which is the point: the bugs this
+// suite exists to catch were all cases where a new runtime silently failed to
+// answer a question the system assumed someone had answered.
+//
+// The cautionary example is in this repo: internal/firecracker declares
+// `var _ sandbox.Manager = (*Manager)(nil)` and does not compile, because
+// nothing ever built it. An interface assertion is not coverage.
+//
+// Provider-dependent behavior (real launches, quota errors) is deliberately out
+// of scope — those need credentials and cost money. What is in scope is every
+// decision the dispatch layer makes from local state: identity, ownership,
+// routing, capacity shape, and nil-safety.
+
+// conformanceBackend pairs a Backend with the facts a test needs to drive it.
+type conformanceBackend struct {
+ name string
+ // build returns a backend in its disabled/zero state — the state a cell not
+ // running this runtime sees, which must be inert rather than panicking.
+ buildDisabled func() Backend
+ // ownedWorkerID is a worker_id this backend must claim as its own.
+ ownedWorkerID string
+ // foreignWorkerIDs must never be claimed. A false positive here is worse
+ // than a false negative: it routes another runtime's sandbox into this one.
+ foreignWorkerIDs []string
+}
+
+var conformanceBackends = []conformanceBackend{
+ {
+ name: "vmhost",
+ buildDisabled: func() Backend { return (*microvmBackend)(nil) },
+ ownedWorkerID: microvmWorkerID("abc123"),
+ foreignWorkerIDs: []string{
+ "w-azure-osb-worker-2512f614", // a real QEMU worker
+ "worker-eastus2-7",
+ "",
+ "vmhost:", // prefix with no id
+ "vmhost", // prefix without separator
+ "microvm:", // legacy prefix, no id
+ // A RAW provider host id. This is the shape the provider SDK
+ // returns, and it is deliberately NOT owned — which is why Claim
+ // must encode before returning a worker_id. Returning the raw id
+ // made every row invisible to the orphan sweep, the restore scan,
+ // and the event publisher, all of which match on the prefixes.
+ hostIDPrefix + "abc123",
+ },
+ },
+}
+
+// A backend must recognize what it owns. This is the durable identity question
+// the reconciler and the orphan sweep both ask using only database rows; a
+// backend that fails it leaves its sandboxes unroutable and its hosts running.
+func TestConformanceOwnsItsOwnWorkerID(t *testing.T) {
+ for _, tc := range conformanceBackends {
+ t.Run(tc.name, func(t *testing.T) {
+ b := tc.buildDisabled()
+ if !b.OwnsWorkerID(tc.ownedWorkerID) {
+ t.Fatalf("%s does not recognize its own worker_id %q", tc.name, tc.ownedWorkerID)
+ }
+ })
+ }
+}
+
+// Claiming another runtime's worker_id is the dangerous direction: the orphan
+// sweep would stop reaping real workers' sandboxes, and routing would send
+// traffic to a backend that does not hold the sandbox.
+func TestConformanceDisownsForeignWorkerIDs(t *testing.T) {
+ for _, tc := range conformanceBackends {
+ t.Run(tc.name, func(t *testing.T) {
+ b := tc.buildDisabled()
+ for _, id := range tc.foreignWorkerIDs {
+ if b.OwnsWorkerID(id) {
+ t.Errorf("%s claimed foreign worker_id %q", tc.name, id)
+ }
+ }
+ })
+ }
+}
+
+// A backend's identifier must not name the infrastructure behind it. Name()
+// reaches logs and telemetry, and those get pasted into tickets and dashboards.
+func TestConformanceNameIsRuntimeNeutral(t *testing.T) {
+ banned := []string{"aws", "amazon", "lambda", "microvm", "azure", "gcp"}
+ for _, tc := range conformanceBackends {
+ t.Run(tc.name, func(t *testing.T) {
+ name := strings.ToLower(tc.buildDisabled().Name())
+ if name == "" {
+ t.Fatal("backend has no name")
+ }
+ for _, bad := range banned {
+ if strings.Contains(name, bad) {
+ t.Errorf("backend name %q names the provider", name)
+ }
+ }
+ })
+ }
+}
+
+// A disabled backend is the state every cell not running it sees — on the QEMU
+// fleet that is the only state. Every entry point must be inert rather than
+// panicking, because a nil dereference here takes down the create path for a
+// cell that has nothing to do with this runtime.
+func TestConformanceDisabledBackendIsInert(t *testing.T) {
+ for _, tc := range conformanceBackends {
+ t.Run(tc.name, func(t *testing.T) {
+ b := tc.buildDisabled()
+ ctx := context.Background()
+
+ if mgr, ok := b.Route(ctx, "sb-anything"); ok || mgr != nil {
+ t.Errorf("disabled %s routed a sandbox: mgr=%v ok=%v", tc.name, mgr, ok)
+ }
+ if p, isPlacer := b.(Placer); isPlacer {
+ if _, err := p.Claim(ctx, placement{sandboxID: "sb-anything"}); err == nil {
+ t.Errorf("disabled %s claimed a sandbox without error", tc.name)
+ }
+ }
+ healthy, available, running := b.Capacity()
+ if healthy != 0 || available != 0 || running != 0 {
+ t.Errorf("disabled %s advertised capacity (%d,%d,%d) — the edge would route creates to it",
+ tc.name, healthy, available, running)
+ }
+ if p, isPlacer := b.(Placer); isPlacer {
+ // Releasing a sandbox a disabled backend never claimed must be
+ // a no-op. Cleanup runs on every failed create, including ones
+ // that failed before this backend was involved.
+ p.Release(ctx, "sb-never-claimed", "")
+ }
+ // Must not panic.
+ b.Reconcile(ctx, nil)
+ b.Close()
+ })
+ }
+}
+
+// A backend that cannot rediscover its own sandboxes must say so, because that
+// is what decides whether a failed row write fails the create. Getting this
+// backwards in either direction is expensive: false when it should be true
+// leaks a host forever, true when it should be false destroys a working sandbox
+// over a transient database error.
+func TestConformanceDeclaresWhetherItNeedsTheRow(t *testing.T) {
+ for _, tc := range conformanceBackends {
+ t.Run(tc.name, func(t *testing.T) {
+ p, isPlacer := tc.buildDisabled().(Placer)
+ if !isPlacer {
+ t.Skip("not a Placer")
+ }
+ // A backend that writes a synthetic worker_id has no registry to ask
+ // what it is running, so it can only rebuild from the rows.
+ needsRow := p.RequiresPersistedRow()
+ if synthetic := len(p.WorkerIDPrefixes()) > 0; synthetic != needsRow {
+ t.Errorf("%s: RequiresPersistedRow=%v but synthetic worker ids=%v — one of these is wrong",
+ tc.name, needsRow, synthetic)
+ }
+ })
+ }
+}
+
+// A backend that fakes a worker_id must declare every prefix it can produce,
+// or the SQL built from these will not recognize its own rows — the orphan
+// sweep reaps them, and the restore scan cannot find them after a restart.
+func TestConformancePrefixesCoverOwnedWorkerID(t *testing.T) {
+ for _, tc := range conformanceBackends {
+ t.Run(tc.name, func(t *testing.T) {
+ b := tc.buildDisabled()
+ prefixes := b.WorkerIDPrefixes()
+ if len(prefixes) == 0 {
+ t.Fatalf("%s declares no worker_id prefixes but synthesizes worker ids", tc.name)
+ }
+ matched := false
+ for _, p := range prefixes {
+ if strings.HasPrefix(tc.ownedWorkerID, p) {
+ matched = true
+ }
+ }
+ if !matched {
+ t.Fatalf("%s owns %q but declares prefixes %v — SQL built from these misses its own rows",
+ tc.name, tc.ownedWorkerID, prefixes)
+ }
+ // A prefix that matches a real worker id would exclude the whole
+ // QEMU fleet from the orphan sweep.
+ for _, p := range prefixes {
+ if strings.HasPrefix("w-azure-osb-worker-2512f614", p) {
+ t.Errorf("%s prefix %q matches a real worker id", tc.name, p)
+ }
+ }
+ })
+ }
+}
+
+// Route must answer "not mine" for a sandbox the backend does not hold, never
+// "mine but unavailable" — the caller reads false as permission to try another
+// backend, so a wrong answer here strands the sandbox.
+func TestConformanceRouteDeclinesUnknownSandbox(t *testing.T) {
+ for _, tc := range conformanceBackends {
+ t.Run(tc.name, func(t *testing.T) {
+ if _, ok := tc.buildDisabled().Route(context.Background(), "sb-never-created"); ok {
+ t.Fatalf("%s claimed a sandbox it never held", tc.name)
+ }
+ })
+ }
+}
+
+// ── dispatch-layer invariants ───────────────────────────────────────────────
+
+// fakeBackend is a Backend that holds exactly one sandbox, for exercising the
+// registry itself rather than any real runtime.
+type fakeBackend struct {
+ name string
+ holds string
+ mgr sandbox.Manager
+ places bool // implements Placer via fakePlacer
+}
+
+// fakePlacer is a fakeBackend that can also accept new sandboxes.
+type fakePlacer struct{ *fakeBackend }
+
+func (f *fakePlacer) RequiresPersistedRow() bool { return false }
+
+func (f *fakePlacer) Release(context.Context, string, string) {}
+
+func (f *fakePlacer) Claim(context.Context, placement) (string, error) {
+ return f.name + ":host", nil
+}
+func (f *fakePlacer) Activate(_ context.Context, a activation) (activated, error) {
+ return activated{sandboxID: a.sandboxID, status: "running"}, nil
+}
+
+func (f *fakeBackend) Name() string { return f.name }
+func (f *fakeBackend) WorkerIDPrefixes() []string { return []string{f.name + ":"} }
+func (f *fakeBackend) OwnsWorkerID(w string) bool {
+ return strings.HasPrefix(w, f.name+":")
+}
+func (f *fakeBackend) Route(_ context.Context, id string) (sandbox.Manager, bool) {
+ if id == f.holds {
+ return f.mgr, true
+ }
+ return nil, false
+}
+func (f *fakeBackend) Capacity() (int, int, int) { return 1, 1, 0 }
+func (f *fakeBackend) Reconcile(context.Context, *db.Store) {}
+
+func (f *fakeBackend) Close() {}
+
+// Registration order is placement policy: claimBackend serves new sandboxes
+// from the first registered backend, and backendFor must find the one that
+// actually holds a given sandbox rather than the first that answers.
+func TestRegistryDispatchesToTheHoldingBackend(t *testing.T) {
+ first := &fakeBackend{name: "first", holds: "sb-first"}
+ second := &fakePlacer{&fakeBackend{name: "second", holds: "sb-second"}}
+ s := &Server{}
+ s.registerBackend(first)
+ s.registerBackend(second)
+
+ got, _, ok := s.backendFor(context.Background(), "sb-second")
+ if !ok || got.Name() != "second" {
+ t.Fatalf("backendFor picked %v (ok=%v), want the backend holding the sandbox", got, ok)
+ }
+ // "first" is registered ahead of "second" but cannot place, so creates must
+ // skip it rather than being diverted to a backend that would fail them.
+ claim, ok := s.claimBackend()
+ if !ok || claim.Name() != "second" {
+ t.Fatalf("claimBackend picked %v, want the first backend that can place", claim)
+ }
+ if _, _, ok := s.backendFor(context.Background(), "sb-unheld"); ok {
+ t.Fatal("registry claimed a sandbox no backend holds")
+ }
+}
+
+// A Server with no backends must route nothing. That nil case IS the QEMU
+// fleet, and a stray true here would divert its traffic in-process.
+func TestNoBackendsRoutesNothing(t *testing.T) {
+ s := &Server{}
+ if _, _, ok := s.backendFor(context.Background(), "sb-1"); ok {
+ t.Fatal("empty registry claimed a sandbox")
+ }
+ if _, ok := s.claimBackend(); ok {
+ t.Fatal("empty registry offered to serve a create")
+ }
+ if mgr, ok := s.execManagerFor("sb-1"); ok || mgr != nil {
+ t.Fatal("empty registry returned an exec manager")
+ }
+}
diff --git a/internal/api/checkpoint_events.go b/internal/api/checkpoint_events.go
index c2a20e99..295984aa 100644
--- a/internal/api/checkpoint_events.go
+++ b/internal/api/checkpoint_events.go
@@ -19,9 +19,10 @@ import (
// the cell_capacity events emitted by controlplane.CapacityReporter.
//
// Event types:
-// checkpoint_ready — checkpoint upload finished; UPSERT row in D1
-// checkpoint_failed — async checkpoint failed; UPSERT failed row in D1
-// checkpoint_deleted — checkpoint dropped from cell PG; DELETE row in D1
+//
+// checkpoint_ready — checkpoint upload finished; UPSERT row in D1
+// checkpoint_failed — async checkpoint failed; UPSERT failed row in D1
+// checkpoint_deleted — checkpoint dropped from cell PG; DELETE row in D1
//
// Best-effort: failure to XADD is logged but doesn't fail the caller. The
// dashboard cross-cell view runs ~seconds behind cell PG truth as a result;
@@ -149,8 +150,9 @@ func (s *Server) publishImageCacheReadyFrom(ctx context.Context, ic *db.ImageCac
// Images view in sync without proxying per-cell at request time.
//
// Event types:
-// image_cache_ready — image is in ready state; UPSERT into D1 images_index
-// image_cache_deleted — image dropped from cell PG; DELETE from D1
+//
+// image_cache_ready — image is in ready state; UPSERT into D1 images_index
+// image_cache_deleted — image dropped from cell PG; DELETE from D1
func (s *Server) publishImageCacheEvent(
ctx context.Context,
eventType string,
diff --git a/internal/api/create_flow.go b/internal/api/create_flow.go
new file mode 100644
index 00000000..2a8a7187
--- /dev/null
+++ b/internal/api/create_flow.go
@@ -0,0 +1,160 @@
+package api
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "log"
+ "net/http"
+
+ "github.com/labstack/echo/v4"
+
+ "github.com/opensandbox/opensandbox/internal/awsvm"
+)
+
+// create_flow.go — the order a sandbox comes into existence, independent of the
+// runtime that hosts it.
+//
+// Every backend runs the same five steps, and the order is not stylistic:
+//
+// claim choose a host — no side effects, so a failure here costs nothing
+// persist write the pending row BEFORE the host boots; the QEMU worker reads
+// org_id out of it while starting the VM, so a later write races the
+// thing that depends on it
+// activate start the host (no-op for a backend whose hosts already run)
+// promote pending → running, the point at which the sandbox is real
+// cleanup on activate failure, close the row out rather than leaving it
+// pending forever — a stuck pending row holds an open scale event and
+// bills until something else notices
+//
+// Sequencing lives here, apart from the HTTP handler, because the handler needs
+// a database and a worker registry to run at all and the ordering invariants
+// need neither. Before this the whole sequence was inline in createSandboxRemote
+// and had no test: the persist-before-activate constraint was a comment.
+
+// createSteps is the runtime-specific half of a create. Each step is a closure
+// so the sequencer needs no knowledge of PG, gRPC, or any provider SDK.
+type createSteps struct {
+ // claim chooses a host and returns the worker_id to persist.
+ claim func(ctx context.Context) (workerID string, err error)
+ // persist writes the pending session row.
+ persist func(ctx context.Context, workerID string) error
+ // persistRequired makes a persist failure fatal, running cleanup and
+ // failing the create.
+ //
+ // Set it when the row is the only record that this sandbox exists. A
+ // backend that can enumerate what it is running reconciles a missing row
+ // later, so losing one is a temporary gap; a backend that rebuilds its view
+ // *from* these rows cannot, so an unwritten row is a host nothing will ever
+ // reclaim — it bills and holds capacity until its hard lifetime cap.
+ persistRequired bool
+ // activate starts the host. Nil means nothing to start.
+ activate func(ctx context.Context, workerID string) error
+ // promote marks the sandbox running.
+ promote func(ctx context.Context, workerID string) error
+ // cleanup runs when activate fails, with the cause. Nil skips it.
+ cleanup func(ctx context.Context, workerID string, cause error)
+}
+
+// runCreate executes the steps in the one order that is correct.
+//
+// Returns the first error and stops: a create that could not claim must not
+// persist, and one that could not activate must not promote. Both mistakes
+// produce a row the system believes in and no host behind it.
+func runCreate(ctx context.Context, sandboxID string, steps createSteps) (workerID string, err error) {
+ workerID, err = steps.claim(ctx)
+ if err != nil {
+ return "", err
+ }
+
+ if steps.persist != nil {
+ if err := steps.persist(ctx, workerID); err != nil {
+ if steps.persistRequired {
+ // Nothing else knows this host exists, so continuing would hand
+ // out a sandbox no sweep can ever reclaim.
+ if steps.cleanup != nil {
+ steps.cleanup(ctx, workerID, err)
+ }
+ return "", fmt.Errorf("create: persist %s on %s: %w", sandboxID, workerID, err)
+ }
+ // Otherwise survivable: the host exists and the customer can use it,
+ // and the row is reconciled later from the runtime's own view.
+ // Failing here instead would strand a running host over a database
+ // blip, which is strictly worse than a missing row.
+ log.Printf("create: persist failed for %s on %s: %v — continuing, reconciler will settle it",
+ sandboxID, workerID, err)
+ }
+ }
+
+ if steps.activate != nil {
+ if err := steps.activate(ctx, workerID); err != nil {
+ if steps.cleanup != nil {
+ steps.cleanup(ctx, workerID, err)
+ }
+ return "", fmt.Errorf("create: activate %s on %s: %w", sandboxID, workerID, err)
+ }
+ }
+
+ if steps.promote != nil {
+ if err := steps.promote(ctx, workerID); err != nil {
+ // The sandbox is up; only the row lags. Same reasoning as persist.
+ log.Printf("create: promote failed for %s on %s: %v", sandboxID, workerID, err)
+ }
+ }
+ return workerID, nil
+}
+
+// respondCreateErr answers a failed create, separating "we are full" from "we
+// are being asked too fast" from "that host is restarting" from everything else.
+//
+// The distinction is the whole point: these are different problems with
+// different answers — one needs capacity added, one clears in under a second,
+// one clears as soon as another host is picked. Collapsing them into a generic
+// 503 leaves a client unable to choose between retrying and giving up.
+//
+// Every message here is what the customer reads, so none of them names the
+// runtime that failed. Which backend was serving the create is our problem, and
+// it changes; the log line beside each one carries that detail instead.
+func respondCreateErr(c echo.Context, err error) error {
+ switch {
+ case errors.Is(err, awsvm.ErrQuotaExceeded), errors.Is(err, ErrNoCapacity):
+ // No Retry-After: retrying does not help until a sandbox is released or
+ // capacity is added, and inviting a retry storm at a full region only
+ // adds rate limiting on top of exhaustion.
+ log.Printf("create: OUT OF CAPACITY: %v", err)
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{
+ "error": "out of capacity: no sandbox capacity is currently available in this region",
+ "hint": "retry once a sandbox is released, or contact support to raise your capacity",
+ })
+
+ case errors.Is(err, awsvm.ErrThrottled):
+ // Transient by construction — say so, and give a concrete delay so
+ // clients space retries instead of hammering.
+ log.Printf("create: rate limited: %v", err)
+ c.Response().Header().Set("Retry-After", "1")
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{
+ "error": "sandbox creation is temporarily rate limited, retry shortly",
+ })
+
+ case isTransientWorkerErr(err):
+ // The chosen host is restarting or unreachable. Retrying reselects, so
+ // this must be retryable rather than a 500 that reads as our bug.
+ log.Printf("create: host unavailable: %v", err)
+ c.Response().Header().Set("Retry-After", "2")
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{
+ "error": "sandbox capacity is temporarily unavailable, please retry",
+ "code": "host_unavailable",
+ })
+
+ case errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded):
+ log.Printf("create: timed out: %v", err)
+ return c.JSON(http.StatusGatewayTimeout, map[string]string{
+ "error": "timed out starting the sandbox",
+ })
+ }
+
+ log.Printf("create: failed: %v", err)
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": "failed to start the sandbox",
+ })
+}
diff --git a/internal/api/create_flow_test.go b/internal/api/create_flow_test.go
new file mode 100644
index 00000000..a0e02a9a
--- /dev/null
+++ b/internal/api/create_flow_test.go
@@ -0,0 +1,153 @@
+package api
+
+import (
+ "context"
+ "errors"
+ "strings"
+ "testing"
+)
+
+// create_flow_test.go — the create sequence, which until now was a comment.
+//
+// The ordering constraint ("persist before activate, because the worker reads
+// org_id from the row while booting") lived only in prose inside a 292-line
+// handler that no test could reach. These pin it.
+
+// recorder captures the order steps ran in.
+type recorder struct{ calls []string }
+
+func (r *recorder) mark(s string) { r.calls = append(r.calls, s) }
+func (r *recorder) seq() string { return strings.Join(r.calls, ",") }
+
+func okSteps(r *recorder) createSteps {
+ return createSteps{
+ claim: func(context.Context) (string, error) {
+ r.mark("claim")
+ return "w-1", nil
+ },
+ persist: func(context.Context, string) error { r.mark("persist"); return nil },
+ activate: func(context.Context, string) error { r.mark("activate"); return nil },
+ promote: func(context.Context, string) error { r.mark("promote"); return nil },
+ cleanup: func(context.Context, string, error) { r.mark("cleanup") },
+ }
+}
+
+// The row must exist before the host boots. Reversing these is not a cosmetic
+// reordering: the QEMU worker looks up org_id in that row while starting the
+// VM, so a later write races the thing that reads it.
+func TestRunCreatePersistsBeforeActivating(t *testing.T) {
+ r := &recorder{}
+ workerID, err := runCreate(context.Background(), "sb-1", okSteps(r))
+ if err != nil {
+ t.Fatalf("runCreate: %v", err)
+ }
+ if workerID != "w-1" {
+ t.Fatalf("got worker %q, want w-1", workerID)
+ }
+ if got := r.seq(); got != "claim,persist,activate,promote" {
+ t.Fatalf("sequence was %q, want claim,persist,activate,promote", got)
+ }
+}
+
+// A create that could not choose a host must not write a row. Otherwise the
+// database gains a sandbox with no host behind it, which the reconciler has to
+// clean up and which bills in the meantime.
+func TestRunCreateStopsWhenClaimFails(t *testing.T) {
+ r := &recorder{}
+ steps := okSteps(r)
+ steps.claim = func(context.Context) (string, error) {
+ r.mark("claim")
+ return "", errors.New("no capacity")
+ }
+
+ if _, err := runCreate(context.Background(), "sb-1", steps); err == nil {
+ t.Fatal("runCreate succeeded despite a failed claim")
+ }
+ if got := r.seq(); got != "claim" {
+ t.Fatalf("sequence was %q — steps ran after the claim failed", got)
+ }
+}
+
+// A host that failed to start must not be promoted to running, and its row must
+// be cleaned up. Promoting here is how a sandbox ends up 'running' with nothing
+// behind it — the customer's next request 502s and billing has already started.
+func TestRunCreateCleansUpAndSkipsPromoteWhenActivateFails(t *testing.T) {
+ r := &recorder{}
+ steps := okSteps(r)
+ boom := errors.New("worker refused")
+ steps.activate = func(context.Context, string) error {
+ r.mark("activate")
+ return boom
+ }
+
+ _, err := runCreate(context.Background(), "sb-1", steps)
+ if err == nil {
+ t.Fatal("runCreate succeeded despite a failed activate")
+ }
+ if !errors.Is(err, boom) {
+ t.Fatalf("error %v lost the underlying cause", err)
+ }
+ if got := r.seq(); got != "claim,persist,activate,cleanup" {
+ t.Fatalf("sequence was %q, want cleanup and no promote", got)
+ }
+}
+
+// A persist failure must not abort a create whose host is already running.
+// Failing here would strand a live host with nothing tracking it — strictly
+// worse than a missing row, which the reconciler settles.
+func TestRunCreateContinuesWhenPersistFails(t *testing.T) {
+ r := &recorder{}
+ steps := okSteps(r)
+ steps.persist = func(context.Context, string) error {
+ r.mark("persist")
+ return errors.New("pg down")
+ }
+
+ if _, err := runCreate(context.Background(), "sb-1", steps); err != nil {
+ t.Fatalf("runCreate aborted on a non-fatal persist failure: %v", err)
+ }
+ if got := r.seq(); got != "claim,persist,activate,promote" {
+ t.Fatalf("sequence was %q — a persist failure changed the flow", got)
+ }
+}
+
+// For a backend that rebuilds its view of what it is running *from* these rows,
+// an unwritten row is not a gap the reconciler closes — it is a host nothing
+// will ever reclaim, billing and holding capacity until its hard lifetime cap.
+// Those backends must fail the create and give the host back.
+func TestRunCreateFailsWhenRequiredPersistFails(t *testing.T) {
+ r := &recorder{}
+ steps := okSteps(r)
+ steps.persistRequired = true
+ boom := errors.New("pg down")
+ steps.persist = func(context.Context, string) error {
+ r.mark("persist")
+ return boom
+ }
+
+ _, err := runCreate(context.Background(), "sb-1", steps)
+ if err == nil {
+ t.Fatal("runCreate handed out a sandbox it could not record")
+ }
+ if !errors.Is(err, boom) {
+ t.Fatalf("error %v lost the underlying cause", err)
+ }
+ if got := r.seq(); got != "claim,persist,cleanup" {
+ t.Fatalf("sequence was %q, want the host released and nothing started", got)
+ }
+}
+
+// A backend whose hosts are already running supplies no activate. The sequence
+// must still complete rather than treating the nil as a failure.
+func TestRunCreateSkipsNilActivate(t *testing.T) {
+ r := &recorder{}
+ steps := okSteps(r)
+ steps.activate = nil
+
+ if _, err := runCreate(context.Background(), "sb-1", steps); err != nil {
+ t.Fatalf("runCreate: %v", err)
+ }
+ if got := r.seq(); got != "claim,persist,promote" {
+ t.Fatalf("sequence was %q, want the activate step skipped", got)
+ }
+}
diff --git a/internal/api/dashboard_agent_subscriptions.go b/internal/api/dashboard_agent_subscriptions.go
index 8a02865b..90ee8368 100644
--- a/internal/api/dashboard_agent_subscriptions.go
+++ b/internal/api/dashboard_agent_subscriptions.go
@@ -212,10 +212,10 @@ func (s *Server) dashboardSubscribeAgentFeature(c echo.Context) error {
return c.JSON(http.StatusInternalServerError, map[string]string{"error": "checkout create failed"})
}
return c.JSON(http.StatusOK, map[string]any{
- "status": "checkout_required",
+ "status": "checkout_required",
"checkout_url": url,
- "feature": feature,
- "agent_id": agentID,
+ "feature": feature,
+ "agent_id": agentID,
})
}
@@ -224,8 +224,8 @@ func (s *Server) dashboardSubscribeAgentFeature(c echo.Context) error {
if err != nil {
log.Printf("billing: direct subscribe failed: %v", err)
return c.JSON(http.StatusInternalServerError, map[string]string{
- "error": "subscribe failed",
- "detail": err.Error(),
+ "error": "subscribe failed",
+ "detail": err.Error(),
})
}
@@ -450,10 +450,10 @@ func (s *Server) apiAgentEntitlement(c echo.Context) error {
if priceID == "" {
// Feature ungated on this deployment.
return c.JSON(http.StatusOK, map[string]any{
- "entitled": true,
- "reason": "ungated",
- "feature": feature,
- "agent_id": agentID,
+ "entitled": true,
+ "reason": "ungated",
+ "feature": feature,
+ "agent_id": agentID,
})
}
@@ -480,12 +480,12 @@ func (s *Server) apiAgentEntitlement(c echo.Context) error {
})
}
return c.JSON(http.StatusOK, map[string]any{
- "entitled": true,
- "feature": feature,
- "agent_id": agentID,
- "status": sub.Status,
- "current_period_end": sub.CurrentPeriodEnd,
- "cancel_at_period_end": sub.CancelAtPeriodEnd,
+ "entitled": true,
+ "feature": feature,
+ "agent_id": agentID,
+ "status": sub.Status,
+ "current_period_end": sub.CurrentPeriodEnd,
+ "cancel_at_period_end": sub.CancelAtPeriodEnd,
})
}
@@ -516,4 +516,3 @@ func priceMonthlyCentsForFeature(feature string) int64 {
}
return 0
}
-
diff --git a/internal/api/dashboard_agents.go b/internal/api/dashboard_agents.go
index a6209fc0..97938a63 100644
--- a/internal/api/dashboard_agents.go
+++ b/internal/api/dashboard_agents.go
@@ -191,4 +191,3 @@ func (s *Server) dashboardAgentsProxy(c echo.Context) error {
}
}
}
-
diff --git a/internal/api/dashboard_billing.go b/internal/api/dashboard_billing.go
index a2a03fe2..185fa02f 100644
--- a/internal/api/dashboard_billing.go
+++ b/internal/api/dashboard_billing.go
@@ -83,11 +83,11 @@ func (s *Server) billingGet(c echo.Context) error {
// the Stripe Billing Portal instead of re-computing cost locally against a
// hardcoded rate table that would diverge for grandfathered orgs.
return c.JSON(http.StatusOK, map[string]interface{}{
- "plan": org.Plan,
- "stripeCreditCents": stripeCreditCents,
- "maxConcurrentSandboxes": org.MaxConcurrentSandboxes,
- "hasPaymentMethod": org.StripeCustomerID != nil,
- "freeCreditsRemainingCents": org.FreeCreditsRemainingCents,
+ "plan": org.Plan,
+ "stripeCreditCents": stripeCreditCents,
+ "maxConcurrentSandboxes": org.MaxConcurrentSandboxes,
+ "hasPaymentMethod": org.StripeCustomerID != nil,
+ "freeCreditsRemainingCents": org.FreeCreditsRemainingCents,
})
}
@@ -185,15 +185,15 @@ func (s *Server) billingInvoices(c echo.Context) error {
}
type inv struct {
- ID string `json:"id"`
- Number string `json:"number"`
- Status string `json:"status"`
- AmountDue int64 `json:"amountDue"`
- AmountPaid int64 `json:"amountPaid"`
- Currency string `json:"currency"`
- Created int64 `json:"created"`
- HostedURL string `json:"hostedUrl"`
- PDFURL string `json:"pdfUrl"`
+ ID string `json:"id"`
+ Number string `json:"number"`
+ Status string `json:"status"`
+ AmountDue int64 `json:"amountDue"`
+ AmountPaid int64 `json:"amountPaid"`
+ Currency string `json:"currency"`
+ Created int64 `json:"created"`
+ HostedURL string `json:"hostedUrl"`
+ PDFURL string `json:"pdfUrl"`
}
var result []inv
for _, i := range invoices {
diff --git a/internal/api/exec_session.go b/internal/api/exec_session.go
index 932a7e19..012835e5 100644
--- a/internal/api/exec_session.go
+++ b/internal/api/exec_session.go
@@ -4,6 +4,7 @@ import (
"context"
"encoding/binary"
"fmt"
+ "log"
"net/http"
"os"
"strconv"
@@ -230,6 +231,14 @@ func (s *Server) execRun(c echo.Context) error {
})
}
+ // MicroVM-backed sandboxes are served in-process, checked before the worker
+ // dispatch below for the same reason as in execRunAsyncRoute: their
+ // worker_id names no registered worker, so execRunRemote can only fail with
+ // "no gRPC connection to worker microvm:<id>".
+ if mgr, ok := s.execManagerFor(id); ok {
+ return s.execRunMicrovm(c, mgr, id, req)
+ }
+
// Server mode: route exec to the worker that owns this sandbox via gRPC
if s.workerRegistry != nil {
return s.execRunRemote(c, id, req)
@@ -238,7 +247,11 @@ func (s *Server) execRun(c echo.Context) error {
// POST /exec/run is the synchronous one-shot endpoint, kept for SDK versions
// that predate the async flow. Newer SDKs POST /exec/run-async, which returns
// a handle immediately and is polled via /result (see execRunAsyncRoute).
- if s.manager == nil {
+ // managerFor, not s.manager: on a control plane serving a registered backend
+ // s.manager is nil, and reading it directly answers "not available in
+ // server-only mode" for a sandbox that is running fine.
+ mgr := s.managerFor(c)
+ if mgr == nil {
return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)
}
@@ -246,7 +259,7 @@ func (s *Server) execRun(c echo.Context) error {
routeOp := func(ctx context.Context) error {
var err error
- result, err = s.manager.Exec(ctx, id, req)
+ result, err = mgr.Exec(ctx, id, req)
return err
}
@@ -329,12 +342,43 @@ func (s *Server) execRunAsyncRoute(c echo.Context) error {
if req.Command == "" {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "cmd is required"})
}
+ // MicroVM-backed sandboxes are served in-process by the awsvm manager
+ // instead of being dispatched to a worker. Checked before the
+ // execSessionManager guard because that manager is part of the worker path
+ // and is legitimately nil on a MicroVM-only cell.
+ if mgr, ok := s.execManagerFor(id); ok {
+ return s.execRunMicrovm(c, mgr, id, req)
+ }
if s.execSessionManager == nil {
return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)
}
return s.execRunAsync(c, id, req)
}
+// execRunMicrovm runs a command on a MicroVM-backed sandbox and answers inline.
+//
+// The async/poll ladder exists because the worker path could not answer within
+// one request. Here it can: the agent tunnel is already open, so a command is a
+// single ~83ms round trip. Returning the completed ExecRunResult directly lets
+// the SDK short-circuit its poll loop — the same contract as the worker path's
+// inline-hold fast path, reached without the hold.
+func (s *Server) execRunMicrovm(c echo.Context, mgr sandbox.Manager, sandboxID string, req types.ProcessConfig) error {
+ res, err := mgr.Exec(c.Request().Context(), sandboxID, req)
+ if err != nil {
+ log.Printf("microvm: exec %s failed: %v", sandboxID, err)
+ return respondManagerErr(c, err)
+ }
+ if s.router != nil {
+ s.router.Touch(sandboxID) // keep the idle timer honest, as the worker path does
+ }
+ return c.JSON(http.StatusOK, types.ExecRunResult{
+ Running: false,
+ ExitCode: &res.ExitCode,
+ Stdout: res.Stdout,
+ Stderr: res.Stderr,
+ })
+}
+
// execRunRemote routes an exec/run request to the worker via gRPC.
func (s *Server) execRunRemote(c echo.Context, sandboxID string, req types.ProcessConfig) error {
orgID, _ := auth.GetOrgID(c)
diff --git a/internal/api/filesystem.go b/internal/api/filesystem.go
index 7f786414..6818796c 100644
--- a/internal/api/filesystem.go
+++ b/internal/api/filesystem.go
@@ -11,7 +11,8 @@ import (
)
func (s *Server) readFile(c echo.Context) error {
- if s.manager == nil {
+ mgr := s.managerFor(c)
+ if mgr == nil {
return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)
}
@@ -28,7 +29,7 @@ func (s *Server) readFile(c echo.Context) error {
routeOp := func(ctx context.Context) error {
var err error
- reader, totalSize, err = s.manager.ReadFileStream(ctx, id, path)
+ reader, totalSize, err = mgr.ReadFileStream(ctx, id, path)
return err
}
@@ -58,7 +59,8 @@ func (s *Server) readFile(c echo.Context) error {
}
func (s *Server) writeFile(c echo.Context) error {
- if s.manager == nil {
+ mgr := s.managerFor(c)
+ if mgr == nil {
return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)
}
@@ -71,7 +73,7 @@ func (s *Server) writeFile(c echo.Context) error {
}
routeOp := func(ctx context.Context) error {
- _, err := s.manager.WriteFileStream(ctx, id, path, 0644, c.Request().Body)
+ _, err := mgr.WriteFileStream(ctx, id, path, 0644, c.Request().Body)
return err
}
@@ -93,7 +95,8 @@ func (s *Server) writeFile(c echo.Context) error {
}
func (s *Server) listDir(c echo.Context) error {
- if s.manager == nil {
+ mgr := s.managerFor(c)
+ if mgr == nil {
return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)
}
@@ -107,7 +110,7 @@ func (s *Server) listDir(c echo.Context) error {
routeOp := func(ctx context.Context) error {
var err error
- entries, err = s.manager.ListDir(ctx, id, path)
+ entries, err = mgr.ListDir(ctx, id, path)
return err
}
@@ -129,7 +132,8 @@ func (s *Server) listDir(c echo.Context) error {
}
func (s *Server) makeDir(c echo.Context) error {
- if s.manager == nil {
+ mgr := s.managerFor(c)
+ if mgr == nil {
return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)
}
@@ -142,7 +146,7 @@ func (s *Server) makeDir(c echo.Context) error {
}
routeOp := func(ctx context.Context) error {
- return s.manager.MakeDir(ctx, id, path)
+ return mgr.MakeDir(ctx, id, path)
}
if s.router != nil {
@@ -163,7 +167,8 @@ func (s *Server) makeDir(c echo.Context) error {
}
func (s *Server) removeFile(c echo.Context) error {
- if s.manager == nil {
+ mgr := s.managerFor(c)
+ if mgr == nil {
return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)
}
@@ -176,7 +181,7 @@ func (s *Server) removeFile(c echo.Context) error {
}
routeOp := func(ctx context.Context) error {
- return s.manager.Remove(ctx, id, path)
+ return mgr.Remove(ctx, id, path)
}
if s.router != nil {
diff --git a/internal/api/internal_sandbox.go b/internal/api/internal_sandbox.go
index d72fbf8b..8bd7b591 100644
--- a/internal/api/internal_sandbox.go
+++ b/internal/api/internal_sandbox.go
@@ -206,8 +206,13 @@ func (s *Server) internalCreateSandbox(c echo.Context) error {
return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})
}
- // Reuse the normal remote-create path — picks a worker, dispatches via
- // gRPC, persists the session, writes the {sandboxID, token, status, ...}
+ // Reuse the normal remote-create path — chooses a backend and a host,
+ // persists the session, boots it, writes the {sandboxID, token, status, ...}
// response body.
+ //
+ // This handler is where the edge actually lands, which is why placement must
+ // not be duplicated here: a claim that lived only on the public path was
+ // dead code in production, and every customer create 503'd for 30s while a
+ // full pool sat idle. Both handlers now share one create.
return s.createSandboxRemote(c, c.Request().Context(), cfg, orgID, true, secretStoreID)
}
diff --git a/internal/api/microvm_backend.go b/internal/api/microvm_backend.go
new file mode 100644
index 00000000..4929d758
--- /dev/null
+++ b/internal/api/microvm_backend.go
@@ -0,0 +1,714 @@
+package api
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log"
+ "net/http"
+ "os"
+ "strconv"
+ "strings"
+ "time"
+
+ awsconfig "github.com/aws/aws-sdk-go-v2/config"
+ "github.com/google/uuid"
+ "github.com/labstack/echo/v4"
+ "github.com/opensandbox/opensandbox/internal/awsvm"
+ "github.com/opensandbox/opensandbox/internal/controlplane"
+ "github.com/opensandbox/opensandbox/internal/db"
+ "github.com/opensandbox/opensandbox/internal/sandbox"
+ "github.com/opensandbox/opensandbox/internal/worker"
+ "github.com/opensandbox/opensandbox/pkg/types"
+ "github.com/redis/go-redis/v9"
+)
+
+// microvm_backend.go — the AWS Lambda MicroVM backend, owned by the control
+// plane.
+//
+// It lives here rather than in cmd/worker on purpose. The point of this backend
+// is that AWS holds the VM, so there is nothing for a QEMU worker host to own;
+// running it from the worker would keep the very hop it exists to remove and
+// add an Azure→AWS leg to every exec. The control plane already decides which
+// cell serves a create, so backend selection belongs at the same level.
+//
+// The QEMU path is untouched. When this backend is disabled — the default —
+// nothing here runs and no AWS call is ever made.
+//
+// Measured on us-east-1 (3-box runs, laptop client):
+//
+// claim 0s (zero AWS calls, by construction)
+// first exec ~224ms (pre-dialled tunnel + agent-path warm-up in the image)
+// warm exec ~83ms
+//
+// Two platform constraints shape everything and are documented where they bite
+// (internal/awsvm/agent.go): the proxy strips HTTP/2 trailers, so gRPC rides
+// inside a WebSocket; and it forwards only to the image's declared hook port.
+
+// microvmBackend holds the CP's MicroVM client and warm pool. nil when the
+// backend is disabled, which is the only state the QEMU fleet ever sees.
+type microvmBackend struct {
+ client *awsvm.Client
+ pool *awsvm.Pool
+ manager *awsvm.Manager
+
+ // usageTicker emits the billing ticks these sandboxes would otherwise never
+ // produce. On the QEMU fleet the worker runs one; there is no worker here,
+ // so the control plane runs it directly over the same sandbox.Manager
+ // interface. Without it MicroVM sandboxes run entirely unmetered.
+ usageTicker *worker.UsageTicker
+
+ // eventPub drains those ticks off local disk to the cell's Redis stream.
+ // The ticker without the publisher meters into a file nobody reads.
+ eventPub *worker.RedisEventPublisher
+
+ // capacity tells the edge this cell exists and can take creates. A cell that
+ // never reports is not routed to at all.
+ capacity *controlplane.CapacityReporter
+
+ // coldSlots caps concurrent cold launches (see maxColdCreates).
+ coldSlots chan struct{}
+
+ // stopPool ends the maintenance loop on shutdown so a redeploying CP does
+ // not leave stock running: abandoned boxes bill compute and hold regional
+ // memory quota until the 8h service cap.
+ stopPool context.CancelFunc
+}
+
+// microvmEnabled reports whether this cell serves MicroVM-backed sandboxes.
+// Off unless explicitly turned on: this backend is regional (us-east-1 today)
+// and cannot serve a cell whose customers expect QEMU semantics like
+// checkpoints or fork, which it does not implement.
+func microvmEnabled() bool {
+ return os.Getenv("OPENSANDBOX_MICROVM_ENABLED") == "1"
+}
+
+// newMicrovmBackend builds the backend from environment config, or returns nil
+// if disabled. An error here is fatal to startup by design — a cell configured
+// for MicroVMs that silently fell back to QEMU would be far more confusing than
+// a refusal to boot.
+func newMicrovmBackend(ctx context.Context) (*microvmBackend, error) {
+ if !microvmEnabled() {
+ return nil, nil
+ }
+
+ image := os.Getenv("OPENSANDBOX_MICROVM_IMAGE_ARN")
+ if image == "" {
+ return nil, fmt.Errorf("OPENSANDBOX_MICROVM_ENABLED=1 but OPENSANDBOX_MICROVM_IMAGE_ARN is unset")
+ }
+ region := os.Getenv("OPENSANDBOX_MICROVM_REGION")
+ if region == "" {
+ region = "us-east-1"
+ }
+
+ awsCfg, err := awsconfig.LoadDefaultConfig(ctx, awsconfig.WithRegion(region))
+ if err != nil {
+ return nil, fmt.Errorf("microvm: load AWS config: %w", err)
+ }
+
+ client := awsvm.NewClient(awsCfg, awsvm.Config{
+ Region: region,
+ ImageIdentifier: image,
+ ExecutionRoleArn: os.Getenv("OPENSANDBOX_MICROVM_EXECUTION_ROLE_ARN"),
+ // Idle-suspend stays off for pooled stock: a box that suspends itself
+ // while waiting turns the next claim into a ResumeMicrovm, which is
+ // rate-limited at 5/s — exactly the cost the pool exists to avoid.
+ AutoResume: false,
+ })
+
+ pool := awsvm.NewPool(client, awsvm.PoolConfig{
+ TargetStock: envInt("OPENSANDBOX_MICROVM_POOL_TARGET", 20),
+ })
+
+ poolCtx, stop := context.WithCancel(context.Background())
+ go pool.Run(poolCtx)
+
+ log.Printf("microvm: backend enabled (region=%s image=%s poolTarget=%d)",
+ region, image, envInt("OPENSANDBOX_MICROVM_POOL_TARGET", 20))
+
+ return &microvmBackend{
+ client: client,
+ pool: pool,
+ manager: awsvm.NewManager(client, os.TempDir()),
+ coldSlots: make(chan struct{}, maxColdCreates),
+ stopPool: stop,
+ }, nil
+}
+
+// claimPooled binds a warm host to a sandbox id and returns whether one was
+// available. It makes NO provider calls — that is the property the whole pool
+// design exists to preserve, because launch and resume are both rate-limited
+// and a burst cannot afford either.
+//
+// A miss is not an error here; Claim decides what to do about it.
+func (b *microvmBackend) claimPooled(sandboxID string, cfg types.SandboxConfig) (string, bool) {
+ if b == nil {
+ return "", false
+ }
+ entry, ok := b.pool.Claim()
+ if !ok {
+ log.Printf("microvm: pool empty on claim for %s — cold create", sandboxID)
+ return "", false
+ }
+ // TrackClaimed adopts the tunnel the pool already established. Losing that
+ // here would cost ~700ms on the customer's first command, which is most of
+ // what this backend's latency story is about.
+ b.manager.TrackClaimed(sandboxID, entry, cfg)
+ // Encoded, not raw: Claim's contract is "the worker_id to persist", and the
+ // raw host id is not a worker_id this backend recognizes as its own.
+ return microvmWorkerID(entry.MicrovmID), true
+}
+
+// maxColdCreates bounds concurrent cold launches. RunMicrovm is rate-limited at
+// 5/s, so letting an unbounded burst through would convert one empty pool into
+// a wall of throttling errors — turning a slow create into a failed one for
+// requests that had nothing to do with the burst.
+const maxColdCreates = 5
+
+// coldCreateTimeout bounds a single cold launch. Generous relative to the ~1.5s
+// a healthy launch takes, because the alternative for the customer is a failed
+// create, not a fast one.
+const coldCreateTimeout = 45 * time.Second
+
+// Claim serves a sandbox from warm stock, falling back to launching one.
+//
+// The pool is a latency optimization, not the capacity limit: the real ceiling
+// is an AWS regional quota far above normal use. Before this existed a pool miss
+// fell through to the worker path and sat in its 30s poll waiting for a worker
+// that a MicroVM cell never has — so every create past pool depth failed after
+// 30 seconds against a backend that would have launched a box in ~1.5s.
+//
+// Returns ErrQuotaExceeded only when AWS says the region is genuinely full, so
+// the caller can report "out of capacity" and mean it.
+func (b *microvmBackend) Claim(ctx context.Context, p placement) (string, error) {
+ if b == nil {
+ return "", errors.New("microvm: backend disabled")
+ }
+ sandboxID, cfg := p.sandboxID, p.cfg
+ if id, ok := b.claimPooled(sandboxID, cfg); ok {
+ return id, nil
+ }
+
+ // Bound concurrency rather than queueing indefinitely: a caller blocked here
+ // is a customer waiting on a create, so failing fast beats a long hold.
+ select {
+ case b.coldSlots <- struct{}{}:
+ defer func() { <-b.coldSlots }()
+ case <-ctx.Done():
+ return "", ctx.Err()
+ }
+
+ launchCtx, cancel := context.WithTimeout(ctx, coldCreateTimeout)
+ defer cancel()
+
+ start := time.Now()
+ box, err := b.client.Run(launchCtx, "")
+ if err != nil {
+ return "", err // already classified (quota vs throttle) by awsvm
+ }
+ ready, err := b.client.WaitRunning(launchCtx, box.ID, coldCreateTimeout)
+ if err != nil {
+ // The box may be mid-boot rather than dead, but we cannot hand out one
+ // we could not confirm — terminate it instead of leaking a box that
+ // bills and holds quota with nothing tracking it.
+ go func() { _ = b.client.Terminate(context.Background(), box.ID) }()
+ return "", fmt.Errorf("microvm: cold create %s never became ready: %w", box.ID, err)
+ }
+ // WaitRunning returns the settled box — it carries the endpoint the agent
+ // tunnel dials, which the pre-ready Run response does not.
+ box = ready
+
+ // Track, not TrackClaimed: there is no pre-dialled tunnel on this path, so
+ // the first exec pays the dial. That is the cost of missing the pool.
+ b.manager.Track(sandboxID, box, cfg)
+ log.Printf("microvm: COLD CREATE %s -> %s in %s", sandboxID, box.ID, time.Since(start).Round(time.Millisecond))
+ return microvmWorkerID(box.ID), nil
+}
+
+// Restore rebuilds the in-memory sandbox→MicroVM map from the database after a
+// control-plane restart, and closes out rows whose box AWS no longer has.
+//
+// Skipping this does not merely lose routing: an untracked box is one nothing
+// will ever terminate, so it keeps billing compute and holding regional memory
+// quota — which is the real ceiling on pool depth — until the 8h cap.
+func (b *microvmBackend) Restore(ctx context.Context, store *db.Store) {
+ b.reconcileOnce(ctx, store)
+}
+
+// microvmReconcileInterval paces the background sweep. Boxes die on their own
+// schedule — the 8h service cap, or AWS terminating one underneath us — so this
+// is the only thing that ever notices. Five minutes is far tighter than the
+// window in which a stale row could matter, and each pass is one cheap
+// GetMicrovm per live sandbox.
+const microvmReconcileInterval = 5 * time.Minute
+
+// StartReconciler sweeps for boxes that died without anyone telling us.
+//
+// Unlike the QEMU fleet, nothing here reports in, so a dead box keeps a running
+// row forever unless this sweep notices — inflating concurrency and quota counts
+// with sandboxes that no longer exist.
+//
+// The inverse hazard is real too, and cost a dev cell every sandbox it created:
+// MarkOrphanedSandboxes reaps any session whose worker_id is missing from the
+// live worker registry, and "microvm:<id>" is missing from it by construction.
+// It now skips these rows explicitly (internal/db/store.go). Anything else that
+// infers liveness from the worker registry has to do the same — AWS is the only
+// authority on whether one of these boxes is alive.
+func (b *microvmBackend) StartReconciler(ctx context.Context, store *db.Store) {
+ if b == nil || store == nil {
+ return
+ }
+ go func() {
+ t := time.NewTicker(microvmReconcileInterval)
+ defer t.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-t.C:
+ b.reconcileOnce(ctx, store)
+ }
+ }
+ }()
+}
+
+// reconcileOnce reconciles persisted MicroVM sandboxes against AWS: adopt the
+// ones still alive, close out the ones that are gone. Used both at boot (where
+// the adopt half matters, after a restart drops the in-memory map) and on the
+// ticker (where the close half matters).
+func (b *microvmBackend) reconcileOnce(ctx context.Context, store *db.Store) {
+ if b == nil || store == nil {
+ return
+ }
+ rows, err := store.ListMicrovmSessions(ctx, b.WorkerIDPrefixes())
+ if err != nil {
+ log.Printf("microvm: restore query failed: %v", err)
+ return
+ }
+
+ var restored, closed int
+ for _, r := range rows {
+ microvmID, ok := parseMicrovmWorkerID(r.WorkerID)
+ if !ok {
+ continue
+ }
+ // Already tracked and healthy — nothing to do. Skipping avoids a
+ // GetMicrovm per sandbox per tick once the map is warm.
+ if _, err := b.manager.Get(ctx, r.SandboxID); err == nil {
+ continue
+ }
+ box, err := b.client.Get(ctx, microvmID)
+ if err != nil || !box.Alive() {
+ // The box is gone (terminated, or aged past the 8h cap) but the row
+ // still says running. Close it, or wake/exec will 404 forever
+ // against a sandbox that cannot exist.
+ msg := "microvm no longer exists"
+ _ = store.UpdateSandboxSessionStatus(ctx, r.SandboxID, "stopped", &msg)
+ closed++
+ continue
+ }
+ // Re-derive the config from the persisted row rather than tracking a
+ // bare id. Track fills zero sizing with the backend default, so a
+ // restore that skipped this would re-meter a 4096MB sandbox at 2048
+ // for the rest of its life — under-billing that nothing surfaces,
+ // since every log line still reports ticks flowing.
+ cfg := types.SandboxConfig{SandboxID: r.SandboxID}
+ if len(r.Config) > 0 {
+ if err := json.Unmarshal(r.Config, &cfg); err != nil {
+ log.Printf("microvm: restore %s: config unmarshal failed (%v) — tracking with defaults", r.SandboxID, err)
+ }
+ cfg.SandboxID = r.SandboxID
+ }
+ b.manager.Track(r.SandboxID, box, cfg)
+ restored++
+ }
+ if restored > 0 || closed > 0 {
+ log.Printf("microvm: reconciled — adopted %d sandbox(es), closed %d dead row(s)", restored, closed)
+ }
+}
+
+// Kill terminates a MicroVM-backed sandbox. Reports whether this backend owned
+// it, so the caller can fall through to the worker path when it did not.
+func (b *microvmBackend) Kill(ctx context.Context, sandboxID string) (bool, error) {
+ if b == nil {
+ return false, nil
+ }
+ if _, err := b.manager.Get(ctx, sandboxID); err != nil {
+ return false, nil
+ }
+ return true, b.manager.Kill(ctx, sandboxID)
+}
+
+// Depth reports current stock, for telemetry and for the sizing invariant: if
+// the edge shards claims, the shards' aggregate target must not exceed this
+// pool or they starve while hoarding — the failure that cost 1045ms vs 174ms on
+// the QEMU fleet.
+func (b *microvmBackend) Depth() int {
+ if b == nil {
+ return 0
+ }
+ return b.pool.Depth()
+}
+
+// StartUsageTicker begins emitting billing ticks for MicroVM sandboxes.
+//
+// UsageTicker takes a sandbox.Manager, which awsvm.Manager already satisfies,
+// so this is wiring rather than a second implementation. It also relies on
+// IsSandboxAlive to drop dead sandboxes — and this backend deliberately asks
+// AWS there instead of trusting its local map, which is exactly what stops a
+// stale entry billing for a VM that no longer exists.
+func (b *microvmBackend) StartUsageTicker(ctx context.Context, sandboxDBs *sandbox.SandboxDBManager) {
+ if b == nil {
+ return
+ }
+ t := worker.NewUsageTicker(b.manager, sandboxDBs, 20*time.Second, 10)
+ if t == nil {
+ // nil sandboxDBs disables it. Say so loudly: silent non-billing is the
+ // failure mode that does not page anyone.
+ log.Printf("microvm: WARNING usage ticker disabled — sandboxes will not be metered")
+ return
+ }
+ b.usageTicker = t
+ t.Start(ctx)
+ log.Printf("microvm: usage ticker started")
+}
+
+// StartEventPublisher drains the ticks the usage ticker writes into per-sandbox
+// SQLite out to the cell's Redis stream, where event_forwarder picks them up for
+// events-ingest → D1 `usage_samples`.
+//
+// This is the second half of billing and is easy to miss, because omitting it
+// looks fine from inside the control plane: LogEvent succeeds, the ticks are on
+// disk, and nothing errors — they simply never leave the box. On the QEMU fleet
+// cmd/worker runs this publisher; with no worker in the MicroVM path, the
+// control plane has to.
+//
+// Off unless both Redis and a cell id are configured, matching the worker: with
+// no consumer, the stream is a slow leak rather than a billing path.
+func (b *microvmBackend) StartEventPublisher(ctx context.Context, sandboxDBs *sandbox.SandboxDBManager, rdb *redis.Client, cellID string, store *db.Store) {
+ if b == nil {
+ return
+ }
+ if sandboxDBs == nil || rdb == nil || cellID == "" {
+ log.Printf("microvm: WARNING event publisher disabled (sandboxDBs=%v redis=%v cellID=%q) — usage ticks stay on local disk and are never billed",
+ sandboxDBs != nil, rdb != nil, cellID)
+ return
+ }
+
+ // Each MicroVM sandbox carries its own owner id, so the envelope's worker_id
+ // has to be resolved per sandbox rather than stamped from the publisher.
+ // events-ingest drops a tick whose worker_id disagrees with
+ // sandboxes_index.worker_id, and every one of these disagrees with any
+ // single fleet-wide id.
+ workerIDs := func(sandboxID string) (string, bool) {
+ hostID, ok := b.manager.MicrovmIDFor(sandboxID)
+ if !ok {
+ return "", false
+ }
+ return microvmWorkerID(hostID), true
+ }
+
+ // org_id + plan are denormalized onto the envelope so events-ingest can
+ // route without a D1 lookup per event. Blank plan means "unknown" there,
+ // which skips the debit — so a missing org row costs metering, not a
+ // mis-bill.
+ var meta worker.MetadataResolver
+ if store != nil {
+ meta = func(sandboxID string) (string, string, bool) {
+ lookupCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ orgIDStr, err := store.GetSandboxOrgID(lookupCtx, sandboxID)
+ if err != nil || orgIDStr == "" {
+ return "", "", false
+ }
+ orgID, err := uuid.Parse(orgIDStr)
+ if err != nil {
+ return "", "", false
+ }
+ org, err := store.GetOrg(lookupCtx, orgID)
+ if err != nil {
+ return orgIDStr, "", true
+ }
+ return orgIDStr, org.Plan, true
+ }
+ }
+
+ pub, err := worker.NewRedisEventPublisher(worker.RedisEventPublisherConfig{
+ Client: rdb,
+ SandboxDBs: sandboxDBs,
+ CellID: cellID,
+ WorkerID: microvmPublisherWorkerID,
+ Resolver: meta,
+ WorkerIDResolver: workerIDs,
+ })
+ if err != nil {
+ log.Printf("microvm: WARNING event publisher init failed: %v — usage ticks will not be billed", err)
+ return
+ }
+
+ // Flush before the SQLite file is deleted. Without this the terminal events
+ // of a destroyed sandbox — including its final usage slice — race the 2s
+ // poll and are lost.
+ sandboxDBs.SetOnRemove(func(sandboxID string) {
+ pub.FlushSandbox(context.Background(), sandboxID)
+ })
+
+ pub.Start(ctx)
+ b.eventPub = pub
+ log.Printf("microvm: event publisher started (stream=events:%s)", cellID)
+}
+
+// Capacity reports this cell's placement numbers to the edge, in the shape a
+// QEMU cell reports worker counts. Implements controlplane.CapacitySource.
+//
+// `available` is a constant 1: this backend has no cell-level capacity worth
+// publishing. Its real ceiling is an AWS regional memory quota that is raised
+// on request and sits orders of magnitude above current use, so any number we
+// computed would say "yes" until the day it didn't.
+//
+// It reported pool depth first, which was wrong in the direction that costs
+// customers: the pool is warmth, not capacity. Advertising depth 503'd creates
+// the backend could serve — every burst past the pool, plus a 30s window after
+// each refill where a fully-stocked cell still advertised zero.
+//
+// What this keeps is the freshness half. The edge also requires
+// capacity_updated_at inside 120s, so this doubles as a liveness heartbeat: a
+// CP that dies, loses Redis, or stops forwarding drops its cell out of routing
+// on its own. That is how a stopped dev CP announced itself rather than
+// silently black-holing creates.
+//
+// Not covered: a live CP whose AWS credentials have expired keeps publishing 1
+// while failing every launch. Closing that means gating on a recent-success
+// signal rather than a constant — worth doing when this backend carries real
+// traffic, and deliberately not built now.
+func (b *microvmBackend) Capacity() (healthy, available, running int) {
+ if b == nil {
+ return 0, 0, 0
+ }
+ n, err := b.manager.Count(context.Background())
+ if err != nil {
+ n = 0
+ }
+ return 1, 1, n
+}
+
+// StartCapacityReporter publishes this cell's capacity so the edge will route
+// to it at all.
+//
+// Without this a MicroVM cell is invisible rather than unhealthy: the edge's
+// isHealthy() gate requires available_workers > 0 and a capacity_updated_at
+// inside 120s, both of which only ever came from the QEMU worker registry. A
+// cell with no workers never wrote either, so every create — including one
+// pinned to it by cellId — fell through to "no cells available with capacity".
+func (b *microvmBackend) StartCapacityReporter(ctx context.Context, rdb *redis.Client, cellID string) {
+ if b == nil {
+ return
+ }
+ if rdb == nil || cellID == "" {
+ log.Printf("microvm: WARNING capacity reporter disabled (redis=%v cellID=%q) — the edge will not route creates to this cell",
+ rdb != nil, cellID)
+ return
+ }
+ cr, err := controlplane.NewCapacityReporter(controlplane.CapacityReporterConfig{
+ Redis: rdb,
+ Source: b,
+ CellID: cellID,
+ })
+ if err != nil {
+ log.Printf("microvm: WARNING capacity reporter init failed: %v — the edge will not route creates to this cell", err)
+ return
+ }
+ cr.Start(ctx)
+ b.capacity = cr
+ log.Printf("microvm: capacity reporter started (cell=%s)", cellID)
+}
+
+// Close stops the maintenance loop and terminates remaining stock.
+func (b *microvmBackend) Close() {
+ if b == nil {
+ return
+ }
+ if b.usageTicker != nil {
+ stopCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ _ = b.usageTicker.Stop(stopCtx)
+ cancel()
+ }
+ // After the ticker, so its final slices are in SQLite before the publisher
+ // drains. Stop() does a last flush; skipping it drops the ticks accrued
+ // since the previous 2s poll on every redeploy.
+ if b.eventPub != nil {
+ stopCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ _ = b.eventPub.Stop(stopCtx)
+ cancel()
+ }
+ if b.capacity != nil {
+ b.capacity.Stop()
+ }
+ b.stopPool()
+ b.pool.Drain()
+ b.manager.Close()
+}
+
+// microvmWorkerPrefix marks sandbox_sessions.worker_id as backed by this
+// runtime and carries the underlying host id after the colon.
+//
+// There is no worker: the host is managed for us, which is the point of this
+// backend. But worker_id is NOT NULL and every existing lookup keys on it, so
+// this keeps those queries working. Encoding the host id here rather than
+// adding a column is deliberate — it is the only durable link between our
+// sandbox id and the host, and without it a control-plane restart loses the
+// mapping: the sandboxes become unroutable AND unreapable, billing compute
+// until the hard duration cap.
+//
+// worker_id travels well beyond the database — it is returned in the create
+// response, written to D1 sandboxes_index, and rendered in the dashboard — so
+// both halves of it are ours to choose, and neither describes the runtime.
+const microvmWorkerPrefix = "vmhost:"
+
+// legacyWorkerPrefix is still read so rows predating the current encoding stay
+// routable and reapable; dropping it would strand those hosts billing until
+// their duration cap with nothing able to parse, reconcile, or terminate them.
+// Never written.
+const legacyWorkerPrefix = "microvm:"
+
+// hostIDPrefix is the fixed prefix the platform puts on every host id. Trimmed
+// on the way into worker_id and restored on the way out, so the id we publish
+// is ours end to end while the value we hand back to the platform is unchanged.
+// A host id that does not carry it is stored verbatim.
+const hostIDPrefix = "microvm-"
+
+// microvmPublisherWorkerID is the event publisher's fallback stamp, used only
+// for a sandbox whose host binding is already gone from memory — which in
+// practice means its final flush during shutdown or after a reconcile drop.
+// The per-sandbox resolver supplies the real owner in every other case.
+const microvmPublisherWorkerID = "vmhost-cp"
+
+// microvmWorkerID encodes a host id for storage in worker_id.
+func microvmWorkerID(microvmID string) string {
+ return microvmWorkerPrefix + strings.TrimPrefix(microvmID, hostIDPrefix)
+}
+
+// parseMicrovmWorkerID recovers the host id, reporting whether the row is
+// backed by this runtime at all.
+func parseMicrovmWorkerID(workerID string) (string, bool) {
+ for _, prefix := range []string{microvmWorkerPrefix, legacyWorkerPrefix} {
+ if !strings.HasPrefix(workerID, prefix) {
+ continue
+ }
+ id := strings.TrimPrefix(workerID, prefix)
+ if id == "" {
+ return "", false
+ }
+ // Rows stored before the id was trimmed already carry it.
+ if !strings.HasPrefix(id, hostIDPrefix) {
+ id = hostIDPrefix + id
+ }
+ return id, true
+ }
+ return "", false
+}
+
+// execManagerFor returns the sandbox.Manager that owns a sandbox.
+//
+// This is the routing seam for step 3: MicroVM-backed sandboxes are served by
+// the awsvm manager in this process, everything else by the existing
+// worker/cell path. Membership is decided by the awsvm manager's own tracking
+// rather than a DB read, so the exec hot path stays in memory.
+// ── Backend implementation ──────────────────────────────────────────────────
+
+// Compile-time proof this backend satisfies the dispatch seam. Without it a
+// method-signature drift would not surface until a call site failed at runtime,
+// which for this backend has repeatedly meant a silent failure rather than a
+// loud one.
+var _ Placer = (*microvmBackend)(nil)
+
+func (b *microvmBackend) Name() string { return "vmhost" }
+
+func (b *microvmBackend) WorkerIDPrefixes() []string {
+ return []string{microvmWorkerPrefix, legacyWorkerPrefix}
+}
+
+func (b *microvmBackend) OwnsWorkerID(workerID string) bool {
+ _, ok := parseMicrovmWorkerID(workerID)
+ return ok
+}
+
+// Route reports whether this backend holds the sandbox, from its in-memory
+// binding only. Deliberately not an availability check: a false here sends the
+// caller to another backend, so "mine but sick" must never look like "not
+// mine".
+func (b *microvmBackend) Route(_ context.Context, sandboxID string) (sandbox.Manager, bool) {
+ if b == nil {
+ return nil, false
+ }
+ if _, ok := b.manager.MicrovmIDFor(sandboxID); !ok {
+ return nil, false
+ }
+ return b.manager, true
+}
+
+// Activate has nothing to do: Claim returns a host that is already running,
+// either popped from warm stock or launched and waited for. There is no second
+// step, which is the whole reason this backend answers a create in ~350ms.
+//
+// It reports running rather than an empty status so the caller does not have to
+// know which backends boot lazily.
+func (b *microvmBackend) Activate(_ context.Context, a activation) (activated, error) {
+ return activated{sandboxID: a.sandboxID, status: "running"}, nil
+}
+
+// RequiresPersistedRow is true: this backend rebuilds its map of what it is
+// running *from* these rows, so a host with no row is one nothing will ever
+// terminate — it bills compute and holds regional capacity until the service's
+// hard lifetime cap.
+func (b *microvmBackend) RequiresPersistedRow() bool { return true }
+
+// Release terminates the host, because here Claim already produced a running
+// one — from warm stock or a cold launch. Merely forgetting it would leave a
+// box that bills compute and holds regional capacity with nothing tracking it,
+// until its hard lifetime cap hours later.
+func (b *microvmBackend) Release(ctx context.Context, sandboxID, _ string) {
+ if b == nil {
+ return
+ }
+ if err := b.manager.Kill(ctx, sandboxID); err != nil {
+ log.Printf("microvm: release %s: %v", sandboxID, err)
+ }
+}
+
+func (b *microvmBackend) Reconcile(ctx context.Context, store *db.Store) {
+ b.reconcileOnce(ctx, store)
+}
+
+// respondManagerErr maps a sandbox.Manager error to a response, turning
+// "this backend cannot do that" into 501 Not Implemented rather than 500.
+//
+// The distinction matters to callers: a 500 invites a retry and reads as our
+// bug, while 501 says the operation will never succeed on this runtime. The
+// MicroVM backend returns ErrUnsupported for checkpoint/fork/reboot/power-cycle
+// — operations with no counterpart in a service where images are built through
+// an API rather than captured from a running VM.
+func respondManagerErr(c echo.Context, err error) error {
+ if errors.Is(err, awsvm.ErrUnsupported) {
+ return c.JSON(http.StatusNotImplemented, map[string]string{
+ "error": "this operation is not supported for this sandbox",
+ })
+ }
+ // Logged, not returned: internal errors carry upstream service names,
+ // resource ids, and wording.
+ log.Printf("microvm: operation failed: %v", err)
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": "the sandbox could not complete this operation",
+ })
+}
+
+func envInt(key string, def int) int {
+ if v := os.Getenv(key); v != "" {
+ if n, err := strconv.Atoi(v); err == nil && n >= 0 {
+ return n
+ }
+ log.Printf("microvm: ignoring malformed %s=%q, using %d", key, v, def)
+ }
+ return def
+}
diff --git a/internal/api/microvm_backend_test.go b/internal/api/microvm_backend_test.go
new file mode 100644
index 00000000..879c8d59
--- /dev/null
+++ b/internal/api/microvm_backend_test.go
@@ -0,0 +1,188 @@
+package api
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/labstack/echo/v4"
+ "github.com/opensandbox/opensandbox/internal/awsvm"
+ "github.com/opensandbox/opensandbox/pkg/types"
+)
+
+// The MicroVM backend is off by default and its hooks sit in three handlers the
+// QEMU fleet uses on every request (createSandbox, killSandboxByID,
+// execRunAsyncRoute). These tests pin the property that makes that safe: with
+// the backend disabled, every hook is inert.
+//
+// This is the regression guard for a real bug found the hard way — the claim
+// was originally placed behind the worker-registry check, which made it
+// unreachable on a MicroVM-only cell. Placement in these handlers is load
+// bearing in both directions.
+
+// The Backend contract itself is covered generically in
+// backend_conformance_test.go. What remains here is this backend's own
+// lifecycle wiring — the calls the router makes at startup and shutdown, which
+// no other backend has and which must not panic when the runtime is disabled.
+// That nil case IS the QEMU fleet.
+func TestNilMicrovmBackendIsInert(t *testing.T) {
+ var b *microvmBackend // explicitly nil, as on a QEMU cell
+
+ if id, ok := b.claimPooled("sb-test", types.SandboxConfig{}); ok || id != "" {
+ t.Fatalf("nil backend claimed a box: id=%q ok=%v", id, ok)
+ }
+ if d := b.Depth(); d != 0 {
+ t.Fatalf("nil backend reported depth %d", d)
+ }
+ owned, err := b.Kill(context.Background(), "sb-test")
+ if owned || err != nil {
+ t.Fatalf("nil backend claimed ownership on Kill: owned=%v err=%v", owned, err)
+ }
+ // Must not panic.
+ b.Close()
+ b.Restore(context.Background(), nil)
+ b.StartReconciler(context.Background(), nil)
+ b.StartUsageTicker(context.Background(), nil)
+ b.StartCapacityReporter(context.Background(), nil, "")
+ b.StartEventPublisher(context.Background(), nil, nil, "", nil)
+}
+
+// execManagerFor decides whether a sandbox is served in-process or dispatched
+// to a worker. On a QEMU cell it must never claim a sandbox, or exec would be
+// routed to a backend that does not hold it.
+func TestExecManagerForDeclinesWhenBackendDisabled(t *testing.T) {
+ s := &Server{} // microvm nil
+ if mgr, ok := s.execManagerFor("sb-anything"); ok || mgr != nil {
+ t.Fatalf("disabled backend claimed sandbox routing: mgr=%v ok=%v", mgr, ok)
+ }
+}
+
+// ErrUnsupported must surface as 501, not 500: a 500 reads as our bug and
+// invites a retry, while the operation can never succeed on this runtime.
+func TestRespondManagerErrMapsUnsupportedTo501(t *testing.T) {
+ e := echo.New()
+ rec := httptest.NewRecorder()
+ c := e.NewContext(httptest.NewRequest(http.MethodPost, "/", nil), rec)
+
+ if err := respondManagerErr(c, awsvm.ErrUnsupported); err != nil {
+ t.Fatalf("respondManagerErr: %v", err)
+ }
+ if rec.Code != http.StatusNotImplemented {
+ t.Fatalf("unsupported op returned %d, want 501", rec.Code)
+ }
+}
+
+// Anything that is not ErrUnsupported stays a 500 — a transport failure or a
+// dead box is a real error and must not be reported as "not implemented".
+func TestRespondManagerErrKeeps500ForRealErrors(t *testing.T) {
+ e := echo.New()
+ rec := httptest.NewRecorder()
+ c := e.NewContext(httptest.NewRequest(http.MethodPost, "/", nil), rec)
+
+ if err := respondManagerErr(c, errors.New("connection reset")); err != nil {
+ t.Fatalf("respondManagerErr: %v", err)
+ }
+ if rec.Code != http.StatusInternalServerError {
+ t.Fatalf("ordinary error returned %d, want 500", rec.Code)
+ }
+}
+
+// A full region and a rate limit are different problems with opposite fixes:
+// raise the quota vs. wait a second. The response has to say which, or an
+// operator tunes the wrong knob and a client cannot decide whether to retry.
+func TestRespondCreateErrDistinguishesQuotaFromThrottle(t *testing.T) {
+ newCtx := func() (echo.Context, *httptest.ResponseRecorder) {
+ e := echo.New()
+ rec := httptest.NewRecorder()
+ return e.NewContext(httptest.NewRequest(http.MethodPost, "/", nil), rec), rec
+ }
+
+ c, rec := newCtx()
+ if err := respondCreateErr(c, fmt.Errorf("run: %w", awsvm.ErrQuotaExceeded)); err != nil {
+ t.Fatalf("respondCreateErr: %v", err)
+ }
+ if rec.Code != http.StatusServiceUnavailable {
+ t.Fatalf("quota returned %d, want 503", rec.Code)
+ }
+ if !strings.Contains(rec.Body.String(), "out of capacity") {
+ t.Fatalf("quota body does not say out of capacity: %s", rec.Body.String())
+ }
+ // Retrying cannot help until a box is released, so we must not invite it.
+ if got := rec.Header().Get("Retry-After"); got != "" {
+ t.Fatalf("quota set Retry-After=%q, inviting a retry storm at a full region", got)
+ }
+
+ c, rec = newCtx()
+ if err := respondCreateErr(c, fmt.Errorf("run: %w", awsvm.ErrThrottled)); err != nil {
+ t.Fatalf("respondCreateErr: %v", err)
+ }
+ if rec.Code != http.StatusServiceUnavailable {
+ t.Fatalf("throttle returned %d, want 503", rec.Code)
+ }
+ if rec.Header().Get("Retry-After") == "" {
+ t.Fatal("throttle is transient but gave the client no Retry-After")
+ }
+ if strings.Contains(rec.Body.String(), "out of capacity") {
+ t.Fatal("throttle reported as out of capacity — sends operators to raise a quota that is fine")
+ }
+}
+
+// Anything unclassified stays a 500: reporting an unknown failure as capacity
+// exhaustion would hide a real bug behind a plausible-looking operational
+// message.
+func TestRespondCreateErrKeeps500ForUnknown(t *testing.T) {
+ e := echo.New()
+ rec := httptest.NewRecorder()
+ c := e.NewContext(httptest.NewRequest(http.MethodPost, "/", nil), rec)
+
+ if err := respondCreateErr(c, errors.New("connection reset")); err != nil {
+ t.Fatalf("respondCreateErr: %v", err)
+ }
+ if rec.Code != http.StatusInternalServerError {
+ t.Fatalf("unknown error returned %d, want 500", rec.Code)
+ }
+}
+
+// microvmWorkerID round-trips through worker_id. That encoding is the only
+// durable link between a sandbox and its AWS box; if it breaks, a restarted
+// control plane cannot rebuild its map and the boxes are both unroutable and
+// unreapable.
+func TestMicrovmWorkerIDRoundTrips(t *testing.T) {
+ const id = "microvm-abc123"
+ got, ok := parseMicrovmWorkerID(microvmWorkerID(id))
+ if !ok || got != id {
+ t.Fatalf("round-trip failed: got %q ok=%v", got, ok)
+ }
+
+ // A real worker id must never be mistaken for a MicroVM row, or the
+ // reconciler would start closing live QEMU sandboxes.
+ for _, notOurs := range []string{"worker-eastus2-7", "", "microvm:", "microvm", "vmhost:", "vmhost"} {
+ if _, ok := parseMicrovmWorkerID(notOurs); ok {
+ t.Fatalf("parsed %q as a MicroVM worker id", notOurs)
+ }
+ }
+}
+
+// Rows written before the vendor-neutral rename still carry the old prefix.
+// They must stay parseable: the restore path uses this to rebuild the sandbox→
+// box map, so a parse failure leaves those sandboxes unroutable and their boxes
+// running until the provider's duration cap with nothing able to reap them.
+func TestParseMicrovmWorkerIDAcceptsLegacyPrefix(t *testing.T) {
+ got, ok := parseMicrovmWorkerID("microvm:microvm-abc123")
+ if !ok || got != "microvm-abc123" {
+ t.Fatalf("legacy prefix not parsed: got %q ok=%v", got, ok)
+ }
+}
+
+// The written form must be the neutral one. worker_id is returned in the create
+// response and written to D1, so writing the old prefix would keep advertising
+// the provider to every customer.
+func TestMicrovmWorkerIDWritesNeutralPrefix(t *testing.T) {
+ if got := microvmWorkerID("abc123"); strings.Contains(got, "microvm") {
+ t.Fatalf("microvmWorkerID produced %q, which names the runtime", got)
+ }
+}
diff --git a/internal/api/projects.go b/internal/api/projects.go
index 791c216b..d936e785 100644
--- a/internal/api/projects.go
+++ b/internal/api/projects.go
@@ -386,4 +386,3 @@ func (s *Server) fanoutSecretRefresh(parentCtx context.Context, storeID uuid.UUI
}
return refreshed, failures
}
-
diff --git a/internal/api/router.go b/internal/api/router.go
index 6d6d5537..fc5ad096 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -62,6 +62,7 @@ type Server struct {
workos *auth.WorkOSMiddleware // nil if WorkOS not configured
dashboardAuthMode string // "workos" or "single-tenant"; empty disables dashboard APIs
workerRegistry *controlplane.RedisWorkerRegistry // nil in combined/worker mode
+ workersDisabled bool // OPENSANDBOX_MAX_WORKERS=0: this cell provisions no workers
checkpointStore *storage.CheckpointStore // nil if hibernation not configured
sandboxDomain string // base domain for sandbox subdomains
cfClient *cloudflare.Client // nil if Cloudflare not configured
@@ -72,7 +73,11 @@ type Server struct {
stripeClient *billing.StripeClient // nil if Stripe not configured
redisClient *redis.Client // nil if Redis not configured (for health checks)
adminEvents *AdminEventBus // real-time event bus for admin dashboard
- ready int32 // atomic: 1 = ready, 0 = not ready
+ microvm *microvmBackend // managed-host backend; nil unless enabled (see microvm_backend.go)
+ // backends is the dispatch set for placement and routing (see backend.go).
+ // The worker path is deliberately absent — it is reached by falling through.
+ backends []Backend
+ ready int32 // atomic: 1 = ready, 0 = not ready
// Axiom log query (sandbox session logs read API).
// Empty token = endpoint returns 503.
@@ -161,11 +166,15 @@ type ServerOpts struct {
DashboardAuthMode string // "workos" or "single-tenant"
SingleTenantPrincipal *auth.SingleTenantPrincipal // required for single-tenant dashboard auth
WorkerRegistry *controlplane.RedisWorkerRegistry // nil in combined/worker mode
- CheckpointStore *storage.CheckpointStore // nil if hibernation not configured
- CFClient *cloudflare.Client // nil if Cloudflare not configured
- SandboxAPIProxy *proxy.SandboxAPIProxy // nil except in server mode (proxies data-plane to workers)
- StripeClient *billing.StripeClient // nil if Stripe not configured
- RedisClient *redis.Client // nil if Redis not configured (for health checks)
+ // WorkersDisabled marks a cell that provisions no workers
+ // (OPENSANDBOX_MAX_WORKERS=0). The registry can still be non-nil there, so
+ // this — not the registry — is what decides who reports cell capacity.
+ WorkersDisabled bool
+ CheckpointStore *storage.CheckpointStore // nil if hibernation not configured
+ CFClient *cloudflare.Client // nil if Cloudflare not configured
+ SandboxAPIProxy *proxy.SandboxAPIProxy // nil except in server mode (proxies data-plane to workers)
+ StripeClient *billing.StripeClient // nil if Stripe not configured
+ RedisClient *redis.Client // nil if Redis not configured (for health checks)
}
// NewServer creates a new API server with all routes configured.
@@ -213,6 +222,7 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
s.router = opts.Router
s.dashboardAuthMode = opts.DashboardAuthMode
s.workerRegistry = opts.WorkerRegistry
+ s.workersDisabled = opts.WorkersDisabled
s.checkpointStore = opts.CheckpointStore
s.sandboxDomain = opts.SandboxDomain
s.cfClient = opts.CFClient
@@ -528,14 +538,41 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
return pxy(c)
}
- // Exec
- api.POST("/sandboxes/:id/exec", pxy)
- api.GET("/sandboxes/:id/exec", pxy)
+ // Data-plane dispatch: a sandbox held by a registered backend is served
+ // in-process; everything else is proxied to the worker that holds it.
+ //
+ // One table, one wrapper. Previously each route was wrapped by hand, which
+ // meant a new data-plane route defaulted to the proxy — and the proxy does
+ // not merely fail for a backend-held sandbox, it resolves the route through
+ // the worker registry, concludes the worker was lost, and writes the
+ // session to `error`. A forgotten route killed healthy sandboxes on their
+ // first request.
+ dataPlane := []struct {
+ method, path string
+ local echo.HandlerFunc
+ }{
+ {http.MethodPost, "/sandboxes/:id/exec", s.createExecSession},
+ {http.MethodGet, "/sandboxes/:id/exec", s.listExecSessions},
+ {http.MethodGet, "/sandboxes/:id/exec/:sessionID/result", s.execResult},
+ {http.MethodPost, "/sandboxes/:id/exec/:sessionID/kill", s.killExecSession},
+ {http.MethodPost, "/sandboxes/:id/exec/run", s.execRun},
+ {http.MethodPost, "/sandboxes/:id/exec/run-async", s.execRunAsyncRoute},
+
+ {http.MethodGet, "/sandboxes/:id/files", s.readFile},
+ {http.MethodPut, "/sandboxes/:id/files", s.writeFile},
+ {http.MethodGet, "/sandboxes/:id/files/list", s.listDir},
+ {http.MethodPost, "/sandboxes/:id/files/mkdir", s.makeDir},
+ {http.MethodDelete, "/sandboxes/:id/files", s.removeFile},
+ }
+ for _, r := range dataPlane {
+ api.Add(r.method, r.path, s.dispatchDataPlane(r.local, pxy))
+ }
+
+ // Streaming and agent routes stay on the proxy: the backends that serve
+ // in-process do not implement PTY, agent sessions, or bidi streaming, so
+ // routing them here would answer a request no manager can serve. They
+ // reach the worker path exactly as before.
api.GET("/sandboxes/:id/exec/:sessionID", wsHandler)
- api.GET("/sandboxes/:id/exec/:sessionID/result", pxy)
- api.POST("/sandboxes/:id/exec/:sessionID/kill", pxy)
- api.POST("/sandboxes/:id/exec/run", pxy)
- api.POST("/sandboxes/:id/exec/run-async", pxy)
// Agent
api.POST("/sandboxes/:id/agent", pxy)
@@ -545,13 +582,6 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
api.POST("/sandboxes/:id/agent/:sid/interrupt", pxy)
api.POST("/sandboxes/:id/agent/:sid/kill", pxy)
- // Filesystem
- api.GET("/sandboxes/:id/files", pxy)
- api.PUT("/sandboxes/:id/files", pxy)
- api.GET("/sandboxes/:id/files/list", pxy)
- api.POST("/sandboxes/:id/files/mkdir", pxy)
- api.DELETE("/sandboxes/:id/files", pxy)
-
// Mounts (FUSE)
api.POST("/sandboxes/:id/mounts", pxy)
api.GET("/sandboxes/:id/mounts", pxy)
@@ -770,6 +800,54 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
// Serve web dashboard SPA at root (catch-all after API/auth routes)
s.serveDashboardUI(e, frontendURL)
+ // AWS Lambda MicroVM backend. Disabled by default: this returns nil and no
+ // AWS call is ever made, so the QEMU fleet is unaffected. When it IS enabled
+ // but misconfigured, fail loudly rather than silently serving QEMU from a
+ // cell the operator believes is running MicroVMs.
+ if mvm, err := newMicrovmBackend(context.Background()); err != nil {
+ log.Fatalf("opensandbox: microvm backend: %v", err)
+ } else if mvm != nil {
+ s.microvm = mvm
+ // Registering it is what makes every claim/route site find it. Before
+ // this the sites each hardcoded their own check, and any new one
+ // silently defaulted to the worker path.
+ s.registerBackend(mvm)
+ // Rebuild the sandbox→MicroVM map before serving. A restart otherwise
+ // leaves live sandboxes unroutable and their boxes unreapable.
+ mvm.Restore(context.Background(), s.store)
+ // Nothing else will ever notice a MicroVM dying — no worker reports in
+ // for these — so sweep on a ticker for the lifetime of the process.
+ mvm.StartReconciler(context.Background(), s.store)
+ // Billing: no worker exists to emit usage ticks for these sandboxes, so
+ // the control plane emits them itself over the same interface.
+ mvm.StartUsageTicker(context.Background(), s.sandboxDBs)
+ // ...and drains them to the cell stream. The ticker alone writes to
+ // local SQLite; without this half nothing ever reads it, and the
+ // sandboxes run free while every log line says billing is working.
+ mvm.StartEventPublisher(context.Background(), s.sandboxDBs, s.redisClient, s.cellID, s.store)
+ // Capacity, but only when no registry-backed reporter is publishing it
+ // already — two writers on one stream would alternate between MicroVM
+ // depth and worker counts, flapping the cell in and out of the edge's
+ // routing set. Keyed on workersDisabled rather than a nil registry: a
+ // MicroVM cell in server mode still HAS a registry (worker_id lookups,
+ // lifecycle publishing), it just never has workers in it, and gating on
+ // the registry left the worker-counting reporter running to publish
+ // available_workers=0 forever.
+ if s.workerRegistry == nil || s.workersDisabled {
+ mvm.StartCapacityReporter(context.Background(), s.redisClient, s.cellID)
+ }
+ }
+
+ // The QEMU fleet, registered last so it is the fall-through rather than the
+ // preference: a cell running both serves creates from the backend that holds
+ // its own warm stock, and reaches the fleet only when that one declines.
+ //
+ // Registration order is placement policy — claimBackend takes the first
+ // Placer — so moving this line changes which runtime serves every create.
+ if wb := newWorkerBackend(s.workerRegistry); wb != nil && !s.workersDisabled {
+ s.registerBackend(wb)
+ }
+
return s
}
@@ -887,14 +965,28 @@ func (s *Server) Start(addr string) error {
// Shutdown gracefully drains in-flight requests and stops the server.
func (s *Server) Shutdown(ctx context.Context) error {
+ // Drain every backend before the HTTP server goes away. Warm stock we
+ // abandon keeps billing compute and holding capacity until its lifetime
+ // cap, so a redeploying control plane would leak a full pool per rollout.
+ s.closeBackends()
return s.echo.Shutdown(ctx)
}
// Close immediately shuts down the server (no drain).
func (s *Server) Close() error {
+ s.closeBackends()
return s.echo.Close()
}
+// closeBackends releases every registered runtime. Iterating the registry
+// rather than naming one is the point: a backend added later is drained without
+// anyone remembering to add a line here.
+func (s *Server) closeBackends() {
+ for _, b := range s.backends {
+ b.Close()
+ }
+}
+
// Echo returns the underlying echo instance for reuse (e.g., worker HTTP server).
func (s *Server) Echo() *echo.Echo {
return s.echo
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index 32f42198..6bf4e599 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -4,10 +4,10 @@ import (
"context"
"encoding/json"
"errors"
- "os"
"fmt"
"log"
"net/http"
+ "os"
"strings"
"time"
@@ -185,8 +185,11 @@ func (s *Server) createSandbox(c echo.Context) error {
}
}
- // Server mode with worker registry: dispatch to remote worker via gRPC
- if s.workerRegistry != nil {
+ // Any registered backend serves the create through the shared flow. The
+ // condition is backend registration, not the worker registry: a cell served
+ // by a backend has no registry and no local manager, so gating on the
+ // registry made every create there fail with "server-only mode".
+ if _, ok := s.claimBackend(); ok {
return s.createSandboxRemote(c, ctx, cfg, orgID, hasOrg, secretStoreID)
}
@@ -796,30 +799,6 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty
region = "iad"
}
- worker, grpcClient, err := s.workerRegistry.GetLeastLoadedWorker(region)
- if err != nil {
- // No worker immediately available — poll for up to 30s
- // (scaler may be launching a new worker)
- deadline := time.After(30 * time.Second)
- ticker := time.NewTicker(2 * time.Second)
- defer ticker.Stop()
- for err != nil {
- select {
- case <-deadline:
- return c.JSON(http.StatusServiceUnavailable, map[string]string{
- "error": "no workers available in region " + region + " (waited 30s)",
- })
- case <-ctx.Done():
- return c.JSON(http.StatusServiceUnavailable, map[string]string{
- "error": "request cancelled while waiting for capacity",
- })
- case <-ticker.C:
- worker, grpcClient, err = s.workerRegistry.GetLeastLoadedWorker(region)
- }
- }
- log.Printf("sandbox: worker became available after queuing (region=%s)", region)
- }
-
// Resolve template (org-scoped lookup with public fallback).
// Edge-first when s.edge is configured (post-migration 041), local PG
// otherwise. Same return shape so the rest of the create flow doesn't
@@ -864,182 +843,143 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty
if poolTemplate == "" {
poolTemplate = poolTemplateName()
}
+ // This is the fleet's own warm pool, which lives in PG and is claimed by
+ // resume+rebind on a worker. A backend that keeps its own warm stock
+ // serves it from inside Claim instead, so there is nothing to branch on
+ // here — the create below is the same call either way.
if done, resp := s.tryClaimPooled(c, ctx, cfg, uuid.UUID(orgID), secretStoreID, region, poolTemplate); done {
return resp
}
}
- // Dispatch via persistent gRPC connection.
- // Worker uses local cache for checkpoint forks (300ms) and downloads from S3
- // only on cold starts. The pre-fix 60s budget was tight for cold forks of
- // multi-GB checkpoints — under any blob-side contention or rebase work,
- // the call could time out before the worker finished. Bumped to a generous
- // flat 5min so cold forks of large checkpoints land cleanly. The happy
- // path is unchanged: this RPC returns as soon as the VM is up, so warm
- // forks still complete in well under a second.
- grpcTimeout := 5 * time.Minute
- grpcCtx, cancel := context.WithTimeout(ctx, grpcTimeout)
- defer cancel()
-
- // Save requested resource limits — create with defaults (golden snapshot),
- // then scale up after creation. This avoids needing a golden per CPU config.
- requestedMemoryMB := cfg.MemoryMB
- requestedCpuCount := cfg.CpuCount
+ // Everything below is runtime-independent: choose a host, write the row,
+ // start the host, promote. runCreate owns that order; the closures below own
+ // what each step means here. Before this the sequence was inline and the
+ // persist-before-activate constraint was a comment.
+ backend, ok := s.claimBackend()
+ if !ok {
+ // No registered backend can accept a sandbox. A cell in this state can
+ // still serve the ones it already has, so this is a capacity answer.
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{
+ "error": "out of capacity: no sandbox capacity is currently available in this region",
+ })
+ }
- // Pre-generate sandbox ID so we can create the session in PG before the
- // gRPC call. The worker's RecordScaleEvent needs the org_id from the
- // session row, which must exist before the worker looks it up.
+ // Pre-generate the sandbox id: the row must carry it before the host boots,
+ // because the host looks its org up by this id while starting.
sandboxID := "sb-" + uuid.New().String()[:8]
- // Register inline webhooks at the edge (Svix) BEFORE the session row and the
- // worker boot, so the endpoint exists well before `created` is relayed. On
- // this remote path `created` is emitted only at the pending→running promotion
- // (i.e. on successful create), so a failed create relays no `created` at all.
+ // Register inline webhooks at the edge (Svix) BEFORE the row and the boot, so
+ // the endpoint exists well before `created` is relayed. On this path `created`
+ // is emitted only at the pending→running promotion, so a failed create relays
+ // no `created` at all.
var inlineWebhooks []types.SandboxWebhookResult
if hasOrg && len(cfg.Webhooks) > 0 {
inlineWebhooks = s.registerInlineWebhooksEdge(ctx, orgID, sandboxID, cfg.Webhooks)
}
- // Create session with "pending" status before dispatching to worker.
- if s.store != nil && hasOrg {
- template := cfg.Template
- if template == "" {
- template = "default"
- }
- cfgJSON, _ := json.Marshal(cfgForPersistence(cfg))
- metadataJSON, _ := json.Marshal(cfg.Metadata)
- // Log + report (Sentry) any session-insert failure loudly. The old
- // `_, _ =` swallow produced D1-only sandboxes: the edge wrote the
- // sandboxes_index row, the cell PG row never materialized, and every
- // subsequent kill/hibernate/exec returned "sandbox not found" via
- // GetSandboxSession. Continuing past the error keeps the user-visible
- // create path 200 (the gRPC call below still creates the VM), but the
- // failure now surfaces in logs and Sentry so we can chase root causes
- // instead of silently producing orphans.
- if _, insErr := s.store.CreateSandboxSessionWithStatus(ctx, sandboxID, orgID, auth.GetUserID(c), template, region, worker.ID, cfgJSON, metadataJSON, "pending", secretStoreID); insErr != nil {
- log.Printf("sandbox: PG session insert failed for %s: %v — sandbox will be D1-only until reconciled", sandboxID, insErr)
- observability.CaptureError(insErr, "area", "sandbox_create", "op", "pg_session_insert", "sandbox_id", sandboxID, "org_id", uuid.UUID(orgID).String())
- }
- if worker.GoldenVersion != "" {
- _ = s.store.SetSandboxGoldenVersion(ctx, sandboxID, worker.GoldenVersion)
- }
- if templateID != nil {
- _ = s.store.UpdateSandboxSessionTemplate(ctx, sandboxID, *templateID)
- }
- }
-
- grpcResp, err := grpcClient.CreateSandbox(grpcCtx, &pb.CreateSandboxRequest{
- SandboxId: sandboxID,
- Template: cfg.Template,
- Timeout: int32(cfg.Timeout),
- Envs: cfg.Envs,
- NetworkEnabled: cfg.IsNetworkEnabled(),
- Port: int32(cfg.Port),
- TemplateRootfsKey: templateRootfsKey,
- TemplateWorkspaceKey: templateWorkspaceKey,
- EgressAllowlist: cfg.EgressAllowlist,
- SecretAllowedHosts: flattenSecretAllowedHosts(cfg.SecretAllowedHosts),
- SecretEnvs: cfg.SecretEnvs,
- DiskMb: int32(cfg.DiskMB),
- VmdoConnectToken: auth.MintVMDOConnectToken(s.sessionJWTSecret, sandboxID),
- })
- if err != nil {
- // Mark session as failed so it doesn't count as active.
- if s.store != nil {
- errMsg := err.Error()
- _ = s.store.UpdateSandboxSessionStatus(ctx, sandboxID, "failed", &errMsg)
- }
- // Inline webhooks were registered at the edge (Svix); a sandbox that never
- // started simply emits no events, so the endpoints sit idle. Edge-side
- // orphan cleanup is a future nicety, not worth a synchronous edge call on
- // the create-failure path.
- // A worker that is restarting/unreachable is transient — return a
- // retryable 503 (with Retry-After) instead of a raw 500 so callers retry
- // and the edge can reselect a worker.
- if isTransientWorkerErr(err) {
- c.Response().Header().Set("Retry-After", "2")
- return c.JSON(http.StatusServiceUnavailable, map[string]string{
- "error": "worker temporarily unavailable, please retry: " + err.Error(),
- "code": "worker_unavailable",
+ var host activated
+ workerID, err := runCreate(ctx, sandboxID, createSteps{
+ claim: func(ctx context.Context) (string, error) {
+ return backend.Claim(ctx, placement{sandboxID: sandboxID, region: region, cfg: cfg})
+ },
+
+ persistRequired: backend.RequiresPersistedRow(),
+
+ persist: func(ctx context.Context, workerID string) error {
+ if s.store == nil || !hasOrg {
+ return nil
+ }
+ template := cfg.Template
+ if template == "" {
+ template = "default"
+ }
+ cfgJSON, _ := json.Marshal(cfgForPersistence(cfg))
+ metadataJSON, _ := json.Marshal(cfg.Metadata)
+ // A failure here used to be swallowed, which produced D1-only
+ // sandboxes: the edge wrote its index row, the cell row never
+ // materialized, and every later kill/hibernate/exec answered
+ // "sandbox not found". It is reported now even where it is survivable.
+ if _, err := s.store.CreateSandboxSessionWithStatus(ctx, sandboxID, orgID, auth.GetUserID(c),
+ template, region, workerID, cfgJSON, metadataJSON, "pending", secretStoreID); err != nil {
+ observability.CaptureError(err, "area", "sandbox_create", "op", "pg_session_insert",
+ "sandbox_id", sandboxID, "org_id", uuid.UUID(orgID).String())
+ return err
+ }
+ if templateID != nil {
+ _ = s.store.UpdateSandboxSessionTemplate(ctx, sandboxID, *templateID)
+ }
+ return nil
+ },
+
+ activate: func(ctx context.Context, workerID string) error {
+ var err error
+ host, err = backend.Activate(ctx, activation{
+ sandboxID: sandboxID,
+ workerID: workerID,
+ cfg: cfg,
+ templateRootfsKey: templateRootfsKey,
+ templateWorkspaceKey: templateWorkspaceKey,
+ connectToken: auth.MintVMDOConnectToken(s.sessionJWTSecret, sandboxID),
})
- }
- return c.JSON(http.StatusInternalServerError, map[string]string{
- "error": "worker create failed: " + err.Error(),
- })
- }
+ return err
+ },
- // Creation succeeded — promote session to running.
- if s.store != nil {
- _ = s.store.UpdateSandboxSessionStatus(ctx, sandboxID, "running", nil)
- // Stamp the authoritative golden the worker actually created this box on,
- // so a later live-migrate can pick the right rebase base. Falls back to
- // the registry heartbeat's golden for pre-golden workers. EVERY box must
- // end up with a golden_version — a blank one is unmigratable.
- golden := grpcResp.GetGoldenVersion()
- if golden == "" {
- golden = worker.GoldenVersion
- }
- if golden != "" {
- _ = s.store.SetSandboxGoldenVersion(ctx, sandboxID, golden)
- }
+ promote: func(ctx context.Context, workerID string) error {
+ if s.store == nil {
+ return nil
+ }
+ // Stamp the image the host actually built on BEFORE the status
+ // flip, so the golden does not ride on that write succeeding.
+ // Nothing backfills a blank golden — there is no sweep for it — so
+ // a row that misses this stamp is unmigratable for the life of the
+ // sandbox, and a live-migrate has no base to rebase against.
+ if host.goldenVersion != "" {
+ _ = s.store.SetSandboxGoldenVersion(ctx, sandboxID, host.goldenVersion)
+ }
+ return s.store.UpdateSandboxSessionStatus(ctx, sandboxID, "running", nil)
+ },
+
+ cleanup: func(ctx context.Context, workerID string, cause error) {
+ // Give the host back first. The row can be corrected later; a host
+ // nothing is tracking cannot be, and it bills the whole time.
+ backend.Release(ctx, sandboxID, workerID)
+ if s.store != nil {
+ msg := cause.Error()
+ _ = s.store.UpdateSandboxSessionStatus(ctx, sandboxID, "failed", &msg)
+ }
+ // Inline webhooks were registered at the edge; a sandbox that never
+ // started emits no events, so those endpoints simply sit idle.
+ },
+ })
+ if err != nil {
+ return respondCreateErr(c, err)
}
- // Preview-URL auth: validate the payload, hash the token, persist it on
- // the freshly-promoted session row. Done after the running-promotion so
- // SetSandboxPreviewAuth's row-state check finds the right row. The
- // plaintext is returned exactly once in the response below.
+ // Preview-URL auth: validate, hash, and persist on the promoted row — after
+ // promotion so the row-state check finds the right row. The plaintext is
+ // returned exactly once, below.
var previewAuthPlaintext string
if cfg.PreviewAuth != nil {
pt, hash, scheme, vStatus, vErr := previewauth.ProcessRequest(cfg.PreviewAuth.Scheme, cfg.PreviewAuth.Token)
if vErr != nil {
- log.Printf("sandbox: %s preview auth setup failed: %v", grpcResp.SandboxId, vErr)
+ log.Printf("sandbox: %s preview auth setup failed: %v", sandboxID, vErr)
if vStatus >= 400 && vStatus < 500 {
return c.JSON(vStatus, map[string]string{"error": vErr.Error()})
}
} else if hash != "" && s.store != nil {
- if pErr := s.store.SetSandboxPreviewAuth(ctx, grpcResp.SandboxId, hash, scheme); pErr != nil {
- log.Printf("sandbox: %s SetSandboxPreviewAuth failed: %v", grpcResp.SandboxId, pErr)
+ if pErr := s.store.SetSandboxPreviewAuth(ctx, sandboxID, hash, scheme); pErr != nil {
+ log.Printf("sandbox: %s SetSandboxPreviewAuth failed: %v", sandboxID, pErr)
} else {
previewAuthPlaintext = pt
}
}
}
- // Scale to requested resources after creation (virtio-mem hotplug + cgroup).
- // Golden snapshot has fixed CPU/RAM — we create with defaults then scale up.
- if requestedMemoryMB > 0 || requestedCpuCount > 0 {
- scaleMB := requestedMemoryMB
- if scaleMB <= 0 {
- scaleMB = 1024
- }
- cpuCount := requestedCpuCount
- if cpuCount <= 0 {
- cpuCount = scaleMB / 4096 // 1 vCPU per 4GB
- if cpuCount < 1 {
- cpuCount = 1
- }
- }
- maxMemBytes := int64(scaleMB) * 1024 * 1024
- cpuPeriod := int64(100000)
- cpuMax := int64(cpuCount) * cpuPeriod
-
- scaleCtx, scaleCancel := context.WithTimeout(ctx, 10*time.Second)
- _, scaleErr := grpcClient.SetSandboxLimits(scaleCtx, &pb.SetSandboxLimitsRequest{
- SandboxId: grpcResp.SandboxId,
- MaxMemoryBytes: maxMemBytes,
- CpuMaxUsec: cpuMax,
- CpuPeriodUsec: cpuPeriod,
- })
- scaleCancel()
- if scaleErr != nil {
- log.Printf("sandbox: post-create scale failed for %s: %v (continuing with defaults)", grpcResp.SandboxId, scaleErr)
- }
- }
-
- // Issue sandbox-scoped JWT (24h TTL — independent of sandbox idle timeout)
+ // Issue sandbox-scoped JWT (24h TTL — independent of the sandbox idle timeout).
var token string
if s.jwtIssuer != nil {
- t, err := s.jwtIssuer.IssueSandboxToken(orgID, grpcResp.SandboxId, worker.ID, 24*time.Hour)
+ t, err := s.jwtIssuer.IssueSandboxToken(orgID, sandboxID, workerID, 24*time.Hour)
if err != nil {
log.Printf("sandbox: failed to issue JWT: %v", err)
} else {
@@ -1047,14 +987,16 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty
}
}
- s.emitEvent("create", grpcResp.SandboxId, worker.ID, fmt.Sprintf("created on %s", worker.ID[len(worker.ID)-8:]))
+ // Reason text reaches customers through webhooks, so it says what happened
+ // rather than what ran it.
+ s.emitEvent("create", sandboxID, workerID, "sandbox started")
resp := map[string]interface{}{
- "sandboxID": grpcResp.SandboxId,
+ "sandboxID": sandboxID,
"token": token,
- "status": grpcResp.Status,
+ "status": host.status,
"region": region,
- "workerID": worker.ID,
+ "workerID": workerID,
}
if s.sandboxDomain != "" {
resp["sandboxDomain"] = s.sandboxDomain
@@ -1172,6 +1114,25 @@ func (s *Server) killSandbox(c echo.Context) error {
func (s *Server) killSandboxByID(c echo.Context, sandboxID string) error {
deleteSecretStore := shouldDeleteAttachedSecretStore(c)
+ // A sandbox held by a registered backend is torn down there, not dispatched
+ // to a worker. Checked before the worker registry because these rows carry a
+ // synthetic worker_id no registry can resolve — without this the host is
+ // never released and bills compute until its hard duration cap.
+ if backend, mgr, ok := s.backendFor(c.Request().Context(), sandboxID); ok {
+ if err := mgr.Kill(c.Request().Context(), sandboxID); err != nil {
+ log.Printf("%s: terminate %s failed: %v", backend.Name(), sandboxID, err)
+ return respondManagerErr(c, err)
+ }
+ if s.store != nil {
+ msg := "destroyed by request"
+ _ = s.store.UpdateSandboxSessionStatus(c.Request().Context(), sandboxID, "stopped", &msg)
+ }
+ // Reason text reaches customers through webhooks — it says what
+ // happened, not what ran it.
+ s.emitEvent("destroy", sandboxID, "", "sandbox stopped")
+ return c.NoContent(http.StatusNoContent)
+ }
+
// Server mode with worker registry: dispatch destroy via gRPC
if s.workerRegistry != nil {
return s.killSandboxRemote(c, sandboxID, deleteSecretStore)
diff --git a/internal/api/sandbox_tags_hydrate.go b/internal/api/sandbox_tags_hydrate.go
index bbc80779..56f8bb76 100644
--- a/internal/api/sandbox_tags_hydrate.go
+++ b/internal/api/sandbox_tags_hydrate.go
@@ -114,4 +114,3 @@ func (s *Server) withTagsHydratedList(c echo.Context, sandboxes interface{}) int
}
return arr
}
-
diff --git a/internal/api/sandbox_tags_test.go b/internal/api/sandbox_tags_test.go
index dd5ea954..0e885817 100644
--- a/internal/api/sandbox_tags_test.go
+++ b/internal/api/sandbox_tags_test.go
@@ -12,7 +12,7 @@ func TestValidateTags_OK(t *testing.T) {
"env": "prod",
"team": "payments",
"team:payments": "yes", // `:` allowed in keys per design
- "empty": "", // empty values allowed
+ "empty": "", // empty values allowed
})
if err != nil {
t.Fatalf("expected valid, got %v", err)
diff --git a/internal/api/signed_urls.go b/internal/api/signed_urls.go
index d77834d9..10cdc60a 100644
--- a/internal/api/signed_urls.go
+++ b/internal/api/signed_urls.go
@@ -11,8 +11,8 @@ import (
)
const (
- defaultSignedURLExpiry = 3600 // 1 hour in seconds
- maxSignedURLExpiry = 86400 // 24 hours in seconds
+ defaultSignedURLExpiry = 3600 // 1 hour in seconds
+ maxSignedURLExpiry = 86400 // 24 hours in seconds
)
// signedURLSecret returns the HMAC secret or an error if not configured.
diff --git a/internal/api/usage.go b/internal/api/usage.go
index 0c72babc..e90e45a4 100644
--- a/internal/api/usage.go
+++ b/internal/api/usage.go
@@ -21,7 +21,7 @@ import (
// new route.
const (
- usageDefaultWindow = 30 * 24 * time.Hour
+ usageDefaultWindow = 30 * 24 * time.Hour
usageHandlerTimeout = 10 * time.Second
)
diff --git a/internal/api/worker_backend.go b/internal/api/worker_backend.go
new file mode 100644
index 00000000..5bd1372b
--- /dev/null
+++ b/internal/api/worker_backend.go
@@ -0,0 +1,312 @@
+package api
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "log"
+ "sync"
+ "time"
+
+ "github.com/opensandbox/opensandbox/internal/controlplane"
+ "github.com/opensandbox/opensandbox/internal/db"
+ "github.com/opensandbox/opensandbox/internal/sandbox"
+ "github.com/opensandbox/opensandbox/pkg/types"
+ pb "github.com/opensandbox/opensandbox/proto/worker"
+)
+
+// worker_backend.go — the QEMU fleet as a Backend.
+//
+// Placement here is two steps, not one, and the order is forced: the worker
+// reads org_id out of the sandbox_sessions row while booting the VM, so the row
+// must exist before dispatch. That is why Placer splits Claim from Activate —
+// a single Claim that returned a worker_id could not express "persist between
+// these two calls", and a single Claim that persisted internally would have to
+// know about tokens, webhooks, and response shaping.
+//
+// A backend whose hosts are already running (nothing to start) implements
+// Activate as a no-op. A backend that boots on demand puts the boot there.
+
+// workerSelector is the slice of the worker registry placement needs.
+//
+// An interface rather than the concrete registry because selection is the one
+// part of create with real branching — immediate hit, wait-then-hit, give up —
+// and until this existed none of it could be tested: the handler reached
+// straight into a Redis-backed struct.
+type workerSelector interface {
+ GetLeastLoadedWorker(region string) (*controlplane.WorkerEntry, pb.SandboxWorkerClient, error)
+}
+
+// ErrNoCapacity means no worker became available within the wait. Distinct from
+// a transport error so the caller can answer 503 rather than 500.
+var ErrNoCapacity = errors.New("no workers available in region")
+
+// workerWaitTimeout bounds how long a create queues for a worker. The scaler
+// may be mid-launch, so a short wait converts a burst into slow creates rather
+// than failed ones; past that the honest answer is that the cell is full.
+const workerWaitTimeout = 30 * time.Second
+
+// workerWaitInterval paces the retry while queued.
+const workerWaitInterval = 2 * time.Second
+
+// workerCreateTimeout bounds the boot RPC. Generous because a cold fork of a
+// multi-GB checkpoint downloads from blob storage; warm creates return in well
+// under a second regardless.
+const workerCreateTimeout = 5 * time.Minute
+
+// workerScaleTimeout bounds the post-create resize, which is local to the
+// worker (virtio-mem hotplug + cgroup write).
+const workerScaleTimeout = 10 * time.Second
+
+// defaultSandboxMemoryMB is the size a create with no memory request gets.
+const defaultSandboxMemoryMB = 1024
+
+// mbPerVCPU is the implied CPU ratio when a create asks for memory alone.
+const mbPerVCPU = 4096
+
+// workerBackend places sandboxes on the QEMU worker fleet.
+type workerBackend struct {
+ selector workerSelector
+ registry *controlplane.RedisWorkerRegistry
+
+ // waitTimeout and waitInterval are fields rather than constants so a test
+ // can exercise the queue-then-succeed and give-up paths without spending
+ // 30 real seconds. Zero means the constants above.
+ waitTimeout time.Duration
+ waitInterval time.Duration
+
+ // pending holds what Claim selected, until Activate consumes it.
+ mu sync.Mutex
+ pending map[string]claimedWorker
+}
+
+// claimedWorker is the result of a selection, held between Claim and Activate.
+//
+// Kept here rather than returned from Claim so Claim's signature stays uniform
+// across backends — a worker_id is the only thing every backend has in common,
+// and it is the only thing the row needs.
+type claimedWorker struct {
+ entry *controlplane.WorkerEntry
+ client pb.SandboxWorkerClient
+}
+
+func newWorkerBackend(registry *controlplane.RedisWorkerRegistry) *workerBackend {
+ if registry == nil {
+ return nil
+ }
+ return &workerBackend{selector: registry, registry: registry}
+}
+
+func (w *workerBackend) Name() string { return "worker" }
+
+// WorkerIDPrefixes is empty: this backend's sandboxes carry real registered
+// worker ids, so the managed-prefix predicates must not match them. Returning a
+// prefix here would exclude the entire fleet from the orphan sweep.
+func (w *workerBackend) WorkerIDPrefixes() []string { return nil }
+
+// OwnsWorkerID reports whether a live worker holds this id. Deliberately asks
+// the registry rather than pattern-matching the string: worker ids have no
+// reserved shape, and guessing would let this backend claim another runtime's
+// sandboxes.
+func (w *workerBackend) OwnsWorkerID(workerID string) bool {
+ if w == nil || w.registry == nil || workerID == "" {
+ return false
+ }
+ return w.registry.GetWorker(workerID) != nil
+}
+
+// Route returns no in-process manager: the sandbox lives on a worker and is
+// reached by proxying. Reporting false keeps the data-plane dispatcher sending
+// these to the proxy, which is the only thing that can serve them.
+func (w *workerBackend) Route(context.Context, string) (sandbox.Manager, bool) {
+ return nil, false
+}
+
+func (w *workerBackend) Capacity() (healthy, available, running int) {
+ if w == nil || w.registry == nil {
+ return 0, 0, 0
+ }
+ return controlplane.WorkerRegistryCapacity(w.registry).Capacity()
+}
+
+// Reconcile is a no-op: the fleet's sweeps (orphan reconciliation, stale-pending
+// reaping, worker-rejoin reconcile) already run from cmd/server against the
+// registry, and duplicating them here would double-close the same rows.
+func (w *workerBackend) Reconcile(context.Context, *db.Store) {}
+
+// selectWorker picks a worker, queueing briefly when none is free.
+//
+// Extracted from createSandboxRemote so the branching is reachable from a test.
+// The three outcomes differ in what the customer should do — served, served
+// after a wait, or told the cell is full — and none of them had coverage.
+func (w *workerBackend) selectWorker(ctx context.Context, region string) (*controlplane.WorkerEntry, pb.SandboxWorkerClient, error) {
+ worker, client, err := w.selector.GetLeastLoadedWorker(region)
+ if err == nil {
+ return worker, client, nil
+ }
+
+ timeout, interval := w.waitTimeout, w.waitInterval
+ if timeout <= 0 {
+ timeout = workerWaitTimeout
+ }
+ if interval <= 0 {
+ interval = workerWaitInterval
+ }
+
+ deadline := time.After(timeout)
+ ticker := time.NewTicker(interval)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-deadline:
+ return nil, nil, ErrNoCapacity
+ case <-ctx.Done():
+ return nil, nil, ctx.Err()
+ case <-ticker.C:
+ worker, client, err = w.selector.GetLeastLoadedWorker(region)
+ if err == nil {
+ log.Printf("sandbox: worker became available after queuing (region=%s)", region)
+ return worker, client, nil
+ }
+ }
+ }
+}
+
+// Claim chooses a worker. No side effects on the fleet: the VM is not started
+// until Activate, so a failure here costs nothing but the selection attempt.
+func (w *workerBackend) Claim(ctx context.Context, p placement) (string, error) {
+ worker, client, err := w.selectWorker(ctx, p.region)
+ if err != nil {
+ return "", err
+ }
+ w.mu.Lock()
+ if w.pending == nil {
+ w.pending = make(map[string]claimedWorker)
+ }
+ w.pending[p.sandboxID] = claimedWorker{entry: worker, client: client}
+ w.mu.Unlock()
+ return worker.ID, nil
+}
+
+// takePending removes and returns what Claim selected.
+func (w *workerBackend) takePending(sandboxID string) (claimedWorker, bool) {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ cw, ok := w.pending[sandboxID]
+ delete(w.pending, sandboxID)
+ return cw, ok
+}
+
+// dropPending releases a claim that will never be activated, so an abandoned
+// create does not pin a worker entry and its connection for the process's life.
+func (w *workerBackend) dropPending(sandboxID string) {
+ w.mu.Lock()
+ delete(w.pending, sandboxID)
+ w.mu.Unlock()
+}
+
+// RequiresPersistedRow is false: workers report the sandboxes they hold on
+// every heartbeat, so the orphan reconciler rediscovers one whose row failed to
+// write. Failing the create instead would destroy a booted VM over a database
+// blip.
+func (w *workerBackend) RequiresPersistedRow() bool { return false }
+
+// Release forgets the selection. Nothing was started — Claim only picked a
+// worker — so there is no host to reclaim, and the worker's own capacity
+// accounting needs no correction.
+func (w *workerBackend) Release(_ context.Context, sandboxID, _ string) {
+ w.dropPending(sandboxID)
+}
+
+// Activate boots the VM on the worker Claim selected, then scales it to the
+// requested shape.
+//
+// The scale-up is part of activation rather than a step of its own because the
+// golden snapshot has fixed CPU and RAM: a sandbox is not yet the size the
+// customer asked for when CreateSandbox returns. Keeping it here means every
+// backend's Activate has the same postcondition — a host running at the
+// requested shape — instead of the caller knowing which runtimes need a second
+// call.
+//
+// A scale failure is logged, not returned: the sandbox is up and usable at
+// default size, and failing the create would destroy a working box over a
+// resize.
+func (w *workerBackend) Activate(ctx context.Context, a activation) (activated, error) {
+ held, ok := w.takePending(a.sandboxID)
+ if !ok {
+ return activated{}, fmt.Errorf("worker: no claim held for %s", a.sandboxID)
+ }
+ client := held.client
+
+ // The worker caches checkpoints locally (~300ms) but downloads from blob on
+ // a cold fork, where a multi-GB checkpoint under any blob-side contention
+ // needs far more than a tight budget. The happy path returns as soon as the
+ // VM is up, so a generous ceiling costs warm creates nothing.
+ createCtx, cancel := context.WithTimeout(ctx, workerCreateTimeout)
+ defer cancel()
+
+ cfg := a.cfg
+ resp, err := client.CreateSandbox(createCtx, &pb.CreateSandboxRequest{
+ SandboxId: a.sandboxID,
+ Template: cfg.Template,
+ Timeout: int32(cfg.Timeout),
+ Envs: cfg.Envs,
+ NetworkEnabled: cfg.IsNetworkEnabled(),
+ Port: int32(cfg.Port),
+ TemplateRootfsKey: a.templateRootfsKey,
+ TemplateWorkspaceKey: a.templateWorkspaceKey,
+ EgressAllowlist: cfg.EgressAllowlist,
+ SecretAllowedHosts: flattenSecretAllowedHosts(cfg.SecretAllowedHosts),
+ SecretEnvs: cfg.SecretEnvs,
+ DiskMb: int32(cfg.DiskMB),
+ VmdoConnectToken: a.connectToken,
+ })
+ if err != nil {
+ return activated{}, err
+ }
+
+ w.scaleToRequested(ctx, client, resp.SandboxId, cfg)
+
+ // Stamp the golden the worker actually built on, falling back to the one the
+ // registry advertised for pre-golden workers. Every box must end up with
+ // some golden_version — a blank one cannot be migrated.
+ golden := resp.GetGoldenVersion()
+ if golden == "" && held.entry != nil {
+ golden = held.entry.GoldenVersion
+ }
+ return activated{sandboxID: resp.SandboxId, status: resp.Status, goldenVersion: golden}, nil
+}
+
+// scaleToRequested hotplugs the box up to the customer's requested shape.
+func (w *workerBackend) scaleToRequested(ctx context.Context, client pb.SandboxWorkerClient, sandboxID string, cfg types.SandboxConfig) {
+ if cfg.MemoryMB <= 0 && cfg.CpuCount <= 0 {
+ return
+ }
+ memMB := cfg.MemoryMB
+ if memMB <= 0 {
+ memMB = defaultSandboxMemoryMB
+ }
+ cpus := cfg.CpuCount
+ if cpus <= 0 {
+ cpus = memMB / mbPerVCPU // 1 vCPU per 4GB
+ if cpus < 1 {
+ cpus = 1
+ }
+ }
+ const cpuPeriod = int64(100000)
+
+ scaleCtx, cancel := context.WithTimeout(ctx, workerScaleTimeout)
+ defer cancel()
+ if _, err := client.SetSandboxLimits(scaleCtx, &pb.SetSandboxLimitsRequest{
+ SandboxId: sandboxID,
+ MaxMemoryBytes: int64(memMB) * 1024 * 1024,
+ CpuMaxUsec: int64(cpus) * cpuPeriod,
+ CpuPeriodUsec: cpuPeriod,
+ }); err != nil {
+ log.Printf("sandbox: post-create scale failed for %s: %v (continuing with defaults)", sandboxID, err)
+ }
+}
+
+// Close has nothing to release: this backend keeps no warm stock of its own,
+// and the worker connections it hands out are owned by the registry.
+func (w *workerBackend) Close() {}
diff --git a/internal/api/worker_backend_test.go b/internal/api/worker_backend_test.go
new file mode 100644
index 00000000..e56806f2
--- /dev/null
+++ b/internal/api/worker_backend_test.go
@@ -0,0 +1,189 @@
+package api
+
+import (
+ "context"
+ "errors"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/opensandbox/opensandbox/internal/controlplane"
+ pb "github.com/opensandbox/opensandbox/proto/worker"
+)
+
+// worker_backend_test.go — first coverage of worker selection.
+//
+// This branching has run every create on the fleet since the beginning with no
+// test behind it, because the handler reached directly into a Redis-backed
+// struct. The three outcomes are materially different for a customer — served
+// now, served after a wait, or told the cell is full — and the failure mode of
+// the last one is a request that hangs for the full timeout before failing.
+
+// fakeSelector answers a scripted sequence of attempts.
+type fakeSelector struct {
+ // failures is how many attempts fail before one succeeds. Negative means
+ // never succeed.
+ failures int32
+ attempts int32
+}
+
+func (f *fakeSelector) GetLeastLoadedWorker(region string) (*controlplane.WorkerEntry, pb.SandboxWorkerClient, error) {
+ n := atomic.AddInt32(&f.attempts, 1)
+ if f.failures < 0 || n <= f.failures {
+ return nil, nil, errors.New("no workers available")
+ }
+ return &controlplane.WorkerEntry{ID: "w-test-1"}, nil, nil
+}
+
+func testWorkerBackend(f *fakeSelector) *workerBackend {
+ return &workerBackend{
+ selector: f,
+ waitTimeout: 200 * time.Millisecond,
+ waitInterval: 10 * time.Millisecond,
+ }
+}
+
+// The common case must not pay the queue at all — a create with capacity
+// available should never touch the ticker.
+func TestSelectWorkerReturnsImmediatelyWhenCapacityExists(t *testing.T) {
+ f := &fakeSelector{failures: 0}
+ start := time.Now()
+ w, _, err := testWorkerBackend(f).selectWorker(context.Background(), "us-west-2")
+ if err != nil {
+ t.Fatalf("selectWorker: %v", err)
+ }
+ if w == nil || w.ID != "w-test-1" {
+ t.Fatalf("got worker %v, want w-test-1", w)
+ }
+ if elapsed := time.Since(start); elapsed > 50*time.Millisecond {
+ t.Fatalf("immediate selection took %s — it queued when it should not have", elapsed)
+ }
+ if got := atomic.LoadInt32(&f.attempts); got != 1 {
+ t.Fatalf("made %d selection attempts, want 1", got)
+ }
+}
+
+// The scaler may be mid-launch, so a create that arrives during a gap should be
+// served late rather than refused. Losing this turns every burst past current
+// capacity into customer-visible errors.
+func TestSelectWorkerQueuesUntilCapacityArrives(t *testing.T) {
+ f := &fakeSelector{failures: 3}
+ w, _, err := testWorkerBackend(f).selectWorker(context.Background(), "us-west-2")
+ if err != nil {
+ t.Fatalf("selectWorker gave up while capacity was arriving: %v", err)
+ }
+ if w == nil || w.ID != "w-test-1" {
+ t.Fatalf("got worker %v, want w-test-1", w)
+ }
+ if got := atomic.LoadInt32(&f.attempts); got < 2 {
+ t.Fatalf("succeeded after %d attempts — it did not actually retry", got)
+ }
+}
+
+// When capacity never arrives the answer must be ErrNoCapacity, so the caller
+// can say 503 rather than 500. A generic error here reads as our bug and
+// invites a retry into a cell that is genuinely full.
+func TestSelectWorkerGivesUpWithErrNoCapacity(t *testing.T) {
+ f := &fakeSelector{failures: -1}
+ start := time.Now()
+ _, _, err := testWorkerBackend(f).selectWorker(context.Background(), "us-west-2")
+ if !errors.Is(err, ErrNoCapacity) {
+ t.Fatalf("got %v, want ErrNoCapacity", err)
+ }
+ // It must actually wait — giving up instantly would refuse creates the
+ // scaler was about to serve.
+ if elapsed := time.Since(start); elapsed < 100*time.Millisecond {
+ t.Fatalf("gave up after %s, well before the wait budget", elapsed)
+ }
+}
+
+// A cancelled request must abandon the queue immediately. Without this a client
+// that hung up still holds the slot for the full timeout, which is how a burst
+// of abandoned creates starves the ones still waiting.
+func TestSelectWorkerAbandonsOnContextCancel(t *testing.T) {
+ f := &fakeSelector{failures: -1}
+ ctx, cancel := context.WithCancel(context.Background())
+ go func() {
+ time.Sleep(20 * time.Millisecond)
+ cancel()
+ }()
+
+ start := time.Now()
+ _, _, err := testWorkerBackend(f).selectWorker(ctx, "us-west-2")
+ if !errors.Is(err, context.Canceled) {
+ t.Fatalf("got %v, want context.Canceled", err)
+ }
+ if elapsed := time.Since(start); elapsed > 150*time.Millisecond {
+ t.Fatalf("kept queueing %s after cancellation", elapsed)
+ }
+}
+
+// Claim and Activate are two calls with a database write between them, so the
+// selection has to survive the gap. If it does not, Activate has no worker to
+// dispatch to and the create fails after the row already exists.
+func TestClaimHoldsTheSelectionForActivate(t *testing.T) {
+ w := testWorkerBackend(&fakeSelector{failures: 0})
+
+ if _, err := w.Claim(context.Background(), placement{sandboxID: "sb-1", region: "us-west-2"}); err != nil {
+ t.Fatalf("Claim: %v", err)
+ }
+ held, ok := w.takePending("sb-1")
+ if !ok {
+ t.Fatal("Claim did not hold the selection — Activate would have nothing to dispatch to")
+ }
+ if held.entry == nil || held.entry.ID != "w-test-1" {
+ t.Fatalf("held %v, want the worker Claim selected", held.entry)
+ }
+ // Taking it must consume it: a second create for the same id is a different
+ // sandbox, and reusing a stale selection would dispatch it to a worker that
+ // was chosen for something else.
+ if _, ok := w.takePending("sb-1"); ok {
+ t.Error("the selection survived being taken")
+ }
+}
+
+// Activating a sandbox this backend never claimed must fail rather than proceed
+// with a nil client, which would panic on the dispatch.
+func TestActivateWithoutAClaimFails(t *testing.T) {
+ w := testWorkerBackend(&fakeSelector{failures: 0})
+ if _, err := w.Activate(context.Background(), activation{sandboxID: "sb-never-claimed"}); err == nil {
+ t.Fatal("Activate proceeded without a held claim")
+ }
+}
+
+// An abandoned create must release its claim. Without this every failed create
+// pins a worker entry and its connection for the life of the process.
+func TestDropPendingReleasesAnAbandonedClaim(t *testing.T) {
+ w := testWorkerBackend(&fakeSelector{failures: 0})
+ if _, err := w.Claim(context.Background(), placement{sandboxID: "sb-1"}); err != nil {
+ t.Fatalf("Claim: %v", err)
+ }
+ w.dropPending("sb-1")
+ if _, ok := w.takePending("sb-1"); ok {
+ t.Error("dropPending left the claim held")
+ }
+}
+
+// The fleet must never be excluded from the orphan sweep: its sandboxes carry
+// real worker ids, and a prefix here would make the sweep skip every one of
+// them, leaving dead workers' rows billing forever.
+func TestWorkerBackendDeclaresNoManagedPrefixes(t *testing.T) {
+ if got := (&workerBackend{}).WorkerIDPrefixes(); len(got) != 0 {
+ t.Fatalf("worker backend declared prefixes %v — the orphan sweep would skip the fleet", got)
+ }
+}
+
+// A nil backend is the state on a cell with no worker registry. Every entry
+// point must be inert rather than panicking.
+func TestNilWorkerBackendIsInert(t *testing.T) {
+ var w *workerBackend
+ if w.OwnsWorkerID("w-anything") {
+ t.Error("nil worker backend claimed a worker id")
+ }
+ if h, a, r := w.Capacity(); h != 0 || a != 0 || r != 0 {
+ t.Errorf("nil worker backend reported capacity (%d,%d,%d)", h, a, r)
+ }
+ if _, ok := w.Route(context.Background(), "sb-1"); ok {
+ t.Error("nil worker backend claimed a route")
+ }
+}
diff --git a/internal/awsvm/agent.go b/internal/awsvm/agent.go
new file mode 100644
index 00000000..4996cad6
--- /dev/null
+++ b/internal/awsvm/agent.go
@@ -0,0 +1,262 @@
+package awsvm
+
+import (
+ "context"
+ "crypto/tls"
+ "fmt"
+ "net"
+ "net/http"
+ "sync"
+ "time"
+
+ "github.com/gorilla/websocket"
+ "github.com/opensandbox/opensandbox/internal/wsconn"
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/connectivity"
+ "google.golang.org/grpc/credentials/insecure"
+ "google.golang.org/grpc/keepalive"
+
+ pb "github.com/opensandbox/opensandbox/proto/agent"
+)
+
+// agent.go — talking to osb-agent inside a MicroVM.
+//
+// This is the load-bearing assumption of the whole backend. In the QEMU world
+// the host reaches the agent over a private virtio-serial/vsock channel it owns
+// end to end. Here there is no host: the only way in is Lambda's public HTTPS
+// endpoint for that MicroVM, which proxies to a guest port when the request
+// carries a JWE in X-aws-proxy-auth and the port in X-aws-proxy-port.
+//
+// Plain gRPC over that proxy does NOT work, and this is the file where that was
+// found. The proxy speaks HTTP/2, but it strips HTTP/2 trailers — and gRPC
+// delivers grpc-status in trailers. The result is the worst possible failure
+// mode: the RPC reaches the agent, the command runs in the guest, and the client
+// then reports "server closed the stream without sending trailers" with no
+// result. Confirmed by round-tripping an unannounced trailer through the proxy
+// (lost) versus the same exchange against a local Go server (preserved), so it
+// is the platform and not our stack.
+//
+// Two further constraints found the same way, both load-bearing:
+// - The proxy forwards ONLY to the port declared in the image's hook config.
+// A second listener is unreachable: gRPC to the agent's own port returned
+// 502 while the identical call to the declared port was answered.
+// - Requests do arrive intact in every other respect, and WebSockets pass
+// through cleanly, which is what makes the tunnel below possible.
+//
+// So the agent protocol IS reused unchanged — every RPC, streaming included —
+// but carried inside a WebSocket where the proxy cannot see or discard the
+// trailers. The token comes from a provider function rather than a fixed string
+// because tokens expire after at most 60 minutes and a long-lived sandbox will
+// outlive several of them.
+
+// tokenProvider returns a currently-valid JWE for a MicroVM. Called on every
+// RPC, so it must be cheap on the hit path (Client.AuthToken caches).
+type tokenProvider func(ctx context.Context) (string, error)
+
+// agentConn is one MicroVM's agent channel.
+type agentConn struct {
+ conn *grpc.ClientConn
+ client pb.SandboxAgentClient
+}
+
+// agentTunnelPath is the guest WebSocket endpoint carrying gRPC. Must match
+// cmd/microvm-hooks.
+const agentTunnelPath = "/osb/agent-grpc"
+
+// dialAgent opens a gRPC channel to the agent behind a MicroVM endpoint.
+//
+// The channel runs over a WebSocket rather than straight HTTP/2, because
+// Lambda's proxy strips HTTP/2 trailers and gRPC carries its status there — so
+// direct gRPC executes the command in the guest and then loses the result.
+// Inside a WebSocket the proxy forwards opaque frames and the gRPC stream,
+// trailers included, survives untouched. See internal/wsconn.
+//
+// Deliberately NOT grpc.WithBlock(): the endpoint is a public TLS service that
+// may be mid-resume, and blocking here would put connection setup on the
+// caller's critical path. gRPC connects lazily on the first RPC, and if the box
+// is suspended, Lambda holds that request while it auto-resumes.
+func dialAgent(endpoint string, port int32, token tokenProvider) (*agentConn, error) {
+ if endpoint == "" {
+ return nil, fmt.Errorf("awsvm: empty MicroVM endpoint")
+ }
+ host := hostOnly(endpoint)
+
+ // The proxy authenticates the WebSocket handshake, so the auth headers ride
+ // on the upgrade rather than on each RPC. Per-RPC metadata would never be
+ // seen by the proxy at all — it only sees the opaque tunnel.
+ dialTunnel := func(ctx context.Context, _ string) (net.Conn, error) {
+ v, err := token(ctx)
+ if err != nil {
+ return nil, fmt.Errorf("awsvm: auth token: %w", err)
+ }
+ hdr := http.Header{}
+ hdr.Set("X-aws-proxy-auth", v)
+ hdr.Set("X-aws-proxy-port", fmt.Sprintf("%d", port))
+
+ d := &websocket.Dialer{
+ HandshakeTimeout: 20 * time.Second,
+ TLSClientConfig: &tls.Config{ServerName: host, MinVersion: tls.VersionTLS12},
+ ReadBufferSize: 64 * 1024,
+ WriteBufferSize: 64 * 1024,
+ }
+ ws, resp, err := d.DialContext(ctx, "wss://"+host+agentTunnelPath, hdr)
+ if err != nil {
+ if resp != nil {
+ return nil, fmt.Errorf("awsvm: agent tunnel handshake to %s (http %d): %w", host, resp.StatusCode, err)
+ }
+ return nil, fmt.Errorf("awsvm: agent tunnel handshake to %s: %w", host, err)
+ }
+ return wsconn.New(ws), nil
+ }
+
+ conn, err := grpc.NewClient(host+":443",
+ // The tunnel already runs over TLS to the proxy; inside it we speak
+ // cleartext HTTP/2 to the guest's loopback agent.
+ grpc.WithTransportCredentials(insecure.NewCredentials()),
+ grpc.WithContextDialer(dialTunnel),
+ // The guest can return large file reads; match the QEMU path's ceiling
+ // so behaviour doesn't silently differ between backends.
+ grpc.WithDefaultCallOptions(
+ grpc.MaxCallRecvMsgSize(256*1024*1024),
+ grpc.MaxCallSendMsgSize(256*1024*1024),
+ ),
+ // Keepalive without permit-without-stream: an idle sandbox should be
+ // allowed to go idle and suspend, which is exactly how this backend
+ // stops billing compute for it. Pinging a suspended box would defeat
+ // the idle policy and keep it needlessly RUNNING.
+ grpc.WithKeepaliveParams(keepalive.ClientParameters{
+ Time: 60 * time.Second,
+ Timeout: 20 * time.Second,
+ PermitWithoutStream: false,
+ }),
+ )
+ if err != nil {
+ return nil, fmt.Errorf("awsvm: dial agent at %s: %w", host, err)
+ }
+ return &agentConn{conn: conn, client: pb.NewSandboxAgentClient(conn)}, nil
+}
+
+// DialAgentConnected dials the agent tunnel and waits until the channel is
+// actually READY, rather than returning a lazy channel that would do the real
+// work on the first RPC. That distinction is the whole point: gRPC connects on
+// demand by default, so a "pre-dialled" channel that was never forced open
+// would still hand the full handshake cost to the first exec.
+func (c *Client) DialAgentConnected(ctx context.Context, microvmID, endpoint string) (*agentConn, error) {
+ a, err := dialAgent(endpoint, c.cfg.AgentPort, func(ctx context.Context) (string, error) {
+ return c.AuthToken(ctx, microvmID)
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ a.conn.Connect()
+ for {
+ s := a.conn.GetState()
+ if s == connectivity.Ready {
+ return a, nil
+ }
+ if !a.conn.WaitForStateChange(ctx, s) {
+ _ = a.Close()
+ return nil, fmt.Errorf("awsvm: agent tunnel to %s not ready: %w", microvmID, ctx.Err())
+ }
+ }
+}
+
+func (a *agentConn) Close() error {
+ if a == nil || a.conn == nil {
+ return nil
+ }
+ return a.conn.Close()
+}
+
+// hostOnly strips scheme and any trailing path from an endpoint so it can be
+// used as a gRPC dial target and TLS server name.
+func hostOnly(endpoint string) string {
+ h := endpoint
+ for _, prefix := range []string{"https://", "http://"} {
+ if len(h) > len(prefix) && h[:len(prefix)] == prefix {
+ h = h[len(prefix):]
+ break
+ }
+ }
+ for i := 0; i < len(h); i++ {
+ if h[i] == '/' {
+ return h[:i]
+ }
+ }
+ return h
+}
+
+// agentPool keeps one channel per sandbox. gRPC channels are expensive to build
+// relative to an exec (TLS handshake + HTTP/2 setup), and the benchmark's shape
+// — create, exec, destroy — would otherwise pay that handshake on the one call
+// that gets measured.
+type agentPool struct {
+ mu sync.Mutex
+ conns map[string]*agentConn
+}
+
+func newAgentPool() *agentPool {
+ return &agentPool{conns: make(map[string]*agentConn)}
+}
+
+// get returns the cached channel for a sandbox, dialing if needed.
+func (p *agentPool) get(sandboxID, endpoint string, port int32, token tokenProvider) (*agentConn, error) {
+ p.mu.Lock()
+ if c, ok := p.conns[sandboxID]; ok {
+ p.mu.Unlock()
+ return c, nil
+ }
+ p.mu.Unlock()
+
+ c, err := dialAgent(endpoint, port, token)
+ if err != nil {
+ return nil, err
+ }
+
+ p.mu.Lock()
+ // Another goroutine may have dialed while we were: keep theirs, drop ours,
+ // so a burst of concurrent execs on one box converges to a single channel.
+ if existing, ok := p.conns[sandboxID]; ok {
+ p.mu.Unlock()
+ _ = c.Close()
+ return existing, nil
+ }
+ p.conns[sandboxID] = c
+ p.mu.Unlock()
+ return c, nil
+}
+
+// put installs an already-dialled channel for a sandbox — used by the claim
+// path to adopt the tunnel the pool established while the box waited in stock.
+func (p *agentPool) put(sandboxID string, c *agentConn) {
+ p.mu.Lock()
+ old := p.conns[sandboxID]
+ p.conns[sandboxID] = c
+ p.mu.Unlock()
+ if old != nil && old != c {
+ _ = old.Close()
+ }
+}
+
+// drop closes and forgets a sandbox's channel — on destroy, or after an error
+// that suggests the endpoint is gone.
+func (p *agentPool) drop(sandboxID string) {
+ p.mu.Lock()
+ c := p.conns[sandboxID]
+ delete(p.conns, sandboxID)
+ p.mu.Unlock()
+ if c != nil {
+ _ = c.Close()
+ }
+}
+
+func (p *agentPool) closeAll() {
+ p.mu.Lock()
+ conns := p.conns
+ p.conns = make(map[string]*agentConn)
+ p.mu.Unlock()
+ for _, c := range conns {
+ _ = c.Close()
+ }
+}
diff --git a/internal/awsvm/client.go b/internal/awsvm/client.go
new file mode 100644
index 00000000..9d16af2f
--- /dev/null
+++ b/internal/awsvm/client.go
@@ -0,0 +1,403 @@
+// Package awsvm backs sandboxes with AWS Lambda MicroVMs instead of locally
+// managed QEMU processes.
+//
+// The shape is deliberately different from internal/qemu: there is no host to
+// manage. Every MicroVM is created by an API call and comes back with its own
+// dedicated public HTTPS endpoint, so a single regional worker process — holding
+// nothing but AWS credentials — can stand in for what used to be a fleet of
+// hypervisor hosts. Everything above the worker (edge, control plane, PoolStock,
+// billing) keeps working against the same sandbox.Manager contract.
+//
+// Reaching into a box goes through Lambda's proxy: an HTTPS request to the
+// MicroVM's endpoint carrying a JWE in X-aws-proxy-auth and the target guest
+// port in X-aws-proxy-port. The proxy speaks HTTP/2, WebSockets, gRPC and SSE,
+// which is why our existing in-guest osb-agent can be reused unchanged — it
+// just listens on TCP in the image rather than on virtio-serial/vsock.
+//
+// What this backend does NOT have, by construction: live migration (AWS places
+// the VMs), golden-snapshot restore, and S3 checkpoints. Hibernate/wake map onto
+// native Suspend/Resume, which preserves memory and disk far more cheaply than
+// our savevm/loadvm path ever did.
+package awsvm
+
+import (
+ "context"
+ "fmt"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms"
+ "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms/types"
+)
+
+const (
+ // authTokenMaxMinutes is the service ceiling on token lifetime. Tokens are
+ // per-MicroVM and per-port, so a long-lived sandbox outlives every token it
+ // is ever issued and the cache below has to refresh in the background.
+ authTokenMaxMinutes = 60
+
+ // authTokenRefreshAt is the fraction of a token's life after which we mint a
+ // replacement. Refreshing early keeps a token miss off the exec hot path —
+ // a create burst that stalls on token minting looks exactly like a slow
+ // sandbox to the customer.
+ authTokenRefreshAt = 0.75
+
+ // maxDurationCeilingSeconds is the service ceiling on how long a MicroVM may
+ // exist, counting RUNNING and SUSPENDED time together. This is the hard
+ // product constraint of this backend: there is no such thing as a sandbox
+ // that outlives it.
+ maxDurationCeilingSeconds = 28_800 // 8 hours
+)
+
+// Config is the regional backend configuration. Everything here is fleet-wide;
+// per-sandbox variation rides on RunOptions.
+type Config struct {
+ Region string
+
+ // ImageIdentifier is the MicroVM image ARN holding osb-agent plus the
+ // lifecycle hook server. ImageVersion empty means "latest active".
+ ImageIdentifier string
+ ImageVersion string
+
+ // ExecutionRoleArn is assumed by the MicroVM itself, for the guest's own AWS
+ // access. It is NOT the role this worker uses to call the API.
+ ExecutionRoleArn string
+
+ IngressNetworkConnectors []string
+ EgressNetworkConnectors []string
+
+ // AgentPort is the guest TCP port we send agent traffic to. Auth tokens are
+ // scoped to it, so a leaked token cannot reach an unrelated guest service.
+ //
+ // This is the image's declared HOOK port, not the port osb-agent itself
+ // binds. Lambda's proxy forwards guest traffic only to the declared port —
+ // any other listener is unreachable and returns 502 even while it is
+ // demonstrably accepting connections inside the guest. cmd/microvm-hooks
+ // therefore serves the hooks and reverse-proxies everything else to the
+ // agent, so this port carries both.
+ AgentPort int32
+
+ // MaxDurationSeconds bounds a sandbox's total lifetime. Clamped to the
+ // service ceiling; 0 means use the ceiling.
+ MaxDurationSeconds int32
+
+ // Idle policy. AutoResume lets an exec against a suspended box wake it
+ // transparently — Lambda holds the request while it resumes — which is the
+ // native version of our wake-on-first-request behaviour.
+ AutoResume bool
+ MaxIdleDurationSeconds int32
+ SuspendedDurationSeconds int32
+}
+
+func (c *Config) applyDefaults() {
+ if c.AgentPort == 0 {
+ // The declared hook port — see the field comment for why this is not
+ // 8081, which is where the agent actually listens.
+ c.AgentPort = 8080
+ }
+ if c.MaxDurationSeconds <= 0 || c.MaxDurationSeconds > maxDurationCeilingSeconds {
+ c.MaxDurationSeconds = maxDurationCeilingSeconds
+ }
+ if c.MaxIdleDurationSeconds <= 0 {
+ c.MaxIdleDurationSeconds = 900
+ }
+ if c.SuspendedDurationSeconds <= 0 {
+ // Suspended boxes bill snapshot storage rather than compute, so holding
+ // them is cheap — but they still count against the region's memory
+ // quota, which is what actually caps warm-pool depth.
+ c.SuspendedDurationSeconds = 1800
+ }
+}
+
+// Box is one MicroVM as this package sees it.
+type Box struct {
+ ID string
+ Endpoint string
+ State types.MicrovmState
+ ImageArn string
+ StartedAt time.Time
+}
+
+// Alive reports whether the box can still serve traffic — either directly, or
+// after an auto-resume. TERMINATING/TERMINATED cannot.
+func (b Box) Alive() bool {
+ switch b.State {
+ case types.MicrovmStatePending, types.MicrovmStateRunning,
+ types.MicrovmStateSuspending, types.MicrovmStateSuspended:
+ return true
+ default:
+ return false
+ }
+}
+
+// API is the subset of the generated client this package uses. Narrow on
+// purpose: it keeps the manager unit-testable without the AWS SDK, and makes
+// the backend's true blast radius obvious at a glance.
+type API interface {
+ RunMicrovm(context.Context, *lambdamicrovms.RunMicrovmInput, ...func(*lambdamicrovms.Options)) (*lambdamicrovms.RunMicrovmOutput, error)
+ GetMicrovm(context.Context, *lambdamicrovms.GetMicrovmInput, ...func(*lambdamicrovms.Options)) (*lambdamicrovms.GetMicrovmOutput, error)
+ SuspendMicrovm(context.Context, *lambdamicrovms.SuspendMicrovmInput, ...func(*lambdamicrovms.Options)) (*lambdamicrovms.SuspendMicrovmOutput, error)
+ ResumeMicrovm(context.Context, *lambdamicrovms.ResumeMicrovmInput, ...func(*lambdamicrovms.Options)) (*lambdamicrovms.ResumeMicrovmOutput, error)
+ TerminateMicrovm(context.Context, *lambdamicrovms.TerminateMicrovmInput, ...func(*lambdamicrovms.Options)) (*lambdamicrovms.TerminateMicrovmOutput, error)
+ ListMicrovms(context.Context, *lambdamicrovms.ListMicrovmsInput, ...func(*lambdamicrovms.Options)) (*lambdamicrovms.ListMicrovmsOutput, error)
+ CreateMicrovmAuthToken(context.Context, *lambdamicrovms.CreateMicrovmAuthTokenInput, ...func(*lambdamicrovms.Options)) (*lambdamicrovms.CreateMicrovmAuthTokenOutput, error)
+}
+
+// Client wraps the MicroVM API with the bits every caller needs: idempotent
+// runs, a token cache, and state translation.
+type Client struct {
+ api API
+ cfg Config
+
+ mu sync.Mutex
+ tokens map[string]*cachedToken
+}
+
+type cachedToken struct {
+ value string
+ refreshAt time.Time
+ expiresAt time.Time
+}
+
+// NewClient builds a Client from an already-resolved AWS config.
+func NewClient(awsCfg aws.Config, cfg Config) *Client {
+ cfg.applyDefaults()
+ return &Client{
+ api: lambdamicrovms.NewFromConfig(awsCfg),
+ cfg: cfg,
+ tokens: make(map[string]*cachedToken),
+ }
+}
+
+// NewClientWithAPI injects a custom API implementation (tests).
+func NewClientWithAPI(api API, cfg Config) *Client {
+ cfg.applyDefaults()
+ return &Client{api: api, cfg: cfg, tokens: make(map[string]*cachedToken)}
+}
+
+// Config exposes the resolved configuration (defaults applied).
+func (c *Client) Config() Config { return c.cfg }
+
+// Run launches a MicroVM. clientToken makes the call idempotent: a retry after a
+// timeout rejoins the original VM instead of leaking a second one, which matters
+// because a leaked VM burns regional memory quota until it ages out — and quota
+// is what caps warm-pool depth.
+func (c *Client) Run(ctx context.Context, clientToken string) (*Box, error) {
+ in := &lambdamicrovms.RunMicrovmInput{
+ ImageIdentifier: aws.String(c.cfg.ImageIdentifier),
+ MaximumDurationInSeconds: aws.Int32(c.cfg.MaxDurationSeconds),
+ IdlePolicy: &types.IdlePolicy{
+ AutoResumeEnabled: aws.Bool(c.cfg.AutoResume),
+ MaxIdleDurationSeconds: aws.Int32(c.cfg.MaxIdleDurationSeconds),
+ SuspendedDurationSeconds: aws.Int32(c.cfg.SuspendedDurationSeconds),
+ },
+ }
+ if c.cfg.ImageVersion != "" {
+ in.ImageVersion = aws.String(c.cfg.ImageVersion)
+ }
+ if c.cfg.ExecutionRoleArn != "" {
+ in.ExecutionRoleArn = aws.String(c.cfg.ExecutionRoleArn)
+ }
+ if clientToken != "" {
+ in.ClientToken = aws.String(clientToken)
+ }
+ if len(c.cfg.IngressNetworkConnectors) > 0 {
+ in.IngressNetworkConnectors = c.cfg.IngressNetworkConnectors
+ }
+ if len(c.cfg.EgressNetworkConnectors) > 0 {
+ in.EgressNetworkConnectors = c.cfg.EgressNetworkConnectors
+ }
+
+ out, err := c.api.RunMicrovm(ctx, in)
+ if err != nil {
+ // Classified before wrapping so callers can tell "no room left in the
+ // region" from "asking too fast" — see errors.go.
+ return nil, fmt.Errorf("awsvm: run microvm: %w", classifyLaunchError(err))
+ }
+ return &Box{
+ ID: aws.ToString(out.MicrovmId),
+ Endpoint: aws.ToString(out.Endpoint),
+ ImageArn: aws.ToString(out.ImageArn),
+ State: types.MicrovmStatePending,
+ }, nil
+}
+
+// Get reads a MicroVM's current state.
+func (c *Client) Get(ctx context.Context, id string) (*Box, error) {
+ out, err := c.api.GetMicrovm(ctx, &lambdamicrovms.GetMicrovmInput{
+ MicrovmIdentifier: aws.String(id),
+ })
+ if err != nil {
+ return nil, fmt.Errorf("awsvm: get microvm %s: %w", id, err)
+ }
+ return &Box{
+ ID: aws.ToString(out.MicrovmId),
+ Endpoint: aws.ToString(out.Endpoint),
+ ImageArn: aws.ToString(out.ImageArn),
+ State: out.State,
+ }, nil
+}
+
+// WaitRunning blocks until a box reaches RUNNING, or ctx/timeout expires.
+//
+// RunMicrovm is asynchronous: it returns an id and endpoint immediately, while
+// the VM is still restoring from the image snapshot and has not yet run its
+// /run hook. Lambda forwards no traffic until that hook returns 200, so talking
+// to a box in PENDING gets 502 Bad Gateway from the proxy — with nothing in the
+// guest logs, because the guest genuinely has not been asked to do anything
+// yet. Anything that parks boxes for later use must gate on this, or it stocks
+// boxes that are not actually ready and the 502 surfaces as a customer-facing
+// exec failure.
+func (c *Client) WaitRunning(ctx context.Context, id string, timeout time.Duration) (*Box, error) {
+ deadline := time.Now().Add(timeout)
+ // Poll gently: GetMicrovm has its own rate quota, and a pool topping up many
+ // boxes at once would otherwise spend that quota on impatience.
+ const pollInterval = 250 * time.Millisecond
+ for {
+ box, err := c.Get(ctx, id)
+ if err != nil {
+ return nil, err
+ }
+ switch box.State {
+ case types.MicrovmStateRunning:
+ return box, nil
+ case types.MicrovmStatePending:
+ // still booting
+ default:
+ // Suspended/terminating/anything else is not something waiting fixes.
+ return nil, fmt.Errorf("awsvm: microvm %s reached state %s while waiting for RUNNING", id, box.State)
+ }
+ if time.Now().After(deadline) {
+ return nil, fmt.Errorf("awsvm: microvm %s still PENDING after %s", id, timeout)
+ }
+ select {
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ case <-time.After(pollInterval):
+ }
+ }
+}
+
+// Suspend snapshots the box's memory and disk and stops billing compute for it.
+func (c *Client) Suspend(ctx context.Context, id string) error {
+ if _, err := c.api.SuspendMicrovm(ctx, &lambdamicrovms.SuspendMicrovmInput{
+ MicrovmIdentifier: aws.String(id),
+ }); err != nil {
+ return fmt.Errorf("awsvm: suspend microvm %s: %w", id, err)
+ }
+ return nil
+}
+
+// Resume restores a suspended box. Callers that are about to send a request can
+// usually skip this entirely and let auto-resume handle it — Lambda holds the
+// inbound request while restoring, so an explicit Resume only pays the latency
+// earlier, it does not avoid it.
+func (c *Client) Resume(ctx context.Context, id string) error {
+ if _, err := c.api.ResumeMicrovm(ctx, &lambdamicrovms.ResumeMicrovmInput{
+ MicrovmIdentifier: aws.String(id),
+ }); err != nil {
+ return fmt.Errorf("awsvm: resume microvm %s: %w", id, err)
+ }
+ return nil
+}
+
+// Terminate destroys the box and releases its quota.
+func (c *Client) Terminate(ctx context.Context, id string) error {
+ if _, err := c.api.TerminateMicrovm(ctx, &lambdamicrovms.TerminateMicrovmInput{
+ MicrovmIdentifier: aws.String(id),
+ }); err != nil {
+ return fmt.Errorf("awsvm: terminate microvm %s: %w", id, err)
+ }
+ c.forgetToken(id)
+ return nil
+}
+
+// List enumerates this account's MicroVMs in the region. Used for reconciling
+// our view against reality — the analogue of the QEMU orphan reaper, since a VM
+// we lose track of keeps consuming quota.
+func (c *Client) List(ctx context.Context) ([]Box, error) {
+ var boxes []Box
+ var next *string
+ for {
+ out, err := c.api.ListMicrovms(ctx, &lambdamicrovms.ListMicrovmsInput{NextToken: next})
+ if err != nil {
+ return nil, fmt.Errorf("awsvm: list microvms: %w", err)
+ }
+ for _, m := range out.Items {
+ // Note: the list projection carries no endpoint — only Get does. A
+ // caller that needs to talk to one of these has to fetch it.
+ boxes = append(boxes, Box{
+ ID: aws.ToString(m.MicrovmId),
+ ImageArn: aws.ToString(m.ImageArn),
+ State: m.State,
+ StartedAt: aws.ToTime(m.StartedAt),
+ })
+ }
+ if out.NextToken == nil || aws.ToString(out.NextToken) == "" {
+ return boxes, nil
+ }
+ next = out.NextToken
+ }
+}
+
+// AuthToken returns a JWE for the box's agent port, minting one only when the
+// cache is cold or stale. Tokens cap at 60 minutes, so any sandbox that lives
+// longer will outlive several of them; refreshing at 75% of the lifetime keeps
+// that churn off the request path.
+func (c *Client) AuthToken(ctx context.Context, id string) (string, error) {
+ now := time.Now()
+
+ c.mu.Lock()
+ if t, ok := c.tokens[id]; ok && now.Before(t.refreshAt) {
+ v := t.value
+ c.mu.Unlock()
+ return v, nil
+ }
+ c.mu.Unlock()
+
+ out, err := c.api.CreateMicrovmAuthToken(ctx, &lambdamicrovms.CreateMicrovmAuthTokenInput{
+ MicrovmIdentifier: aws.String(id),
+ ExpirationInMinutes: aws.Int32(authTokenMaxMinutes),
+ AllowedPorts: []types.PortSpecification{
+ &types.PortSpecificationMemberPort{Value: c.cfg.AgentPort},
+ },
+ })
+ if err != nil {
+ return "", fmt.Errorf("awsvm: create auth token %s: %w", id, err)
+ }
+ value := out.AuthToken["X-aws-proxy-auth"]
+ if value == "" {
+ return "", fmt.Errorf("awsvm: auth token response for %s had no X-aws-proxy-auth", id)
+ }
+
+ life := time.Duration(authTokenMaxMinutes) * time.Minute
+ c.mu.Lock()
+ c.tokens[id] = &cachedToken{
+ value: value,
+ refreshAt: now.Add(time.Duration(float64(life) * authTokenRefreshAt)),
+ expiresAt: now.Add(life),
+ }
+ c.mu.Unlock()
+ return value, nil
+}
+
+func (c *Client) forgetToken(id string) {
+ c.mu.Lock()
+ delete(c.tokens, id)
+ c.mu.Unlock()
+}
+
+// AgentURL is the base URL for talking to the in-guest agent on a box. The
+// endpoint the API hands back may or may not carry a scheme depending on the
+// call, so normalise rather than trusting it.
+func AgentURL(endpoint string) string {
+ if endpoint == "" {
+ return ""
+ }
+ if strings.HasPrefix(endpoint, "http://") || strings.HasPrefix(endpoint, "https://") {
+ return endpoint
+ }
+ return "https://" + endpoint
+}
diff --git a/internal/awsvm/client_test.go b/internal/awsvm/client_test.go
new file mode 100644
index 00000000..8b0721aa
--- /dev/null
+++ b/internal/awsvm/client_test.go
@@ -0,0 +1,189 @@
+package awsvm
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms"
+ "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms/types"
+)
+
+// fakeAPI records what the client asked AWS for, so the tests can assert on the
+// request rather than on a live service.
+type fakeAPI struct {
+ API
+ runIn *lambdamicrovms.RunMicrovmInput
+ tokenIn *lambdamicrovms.CreateMicrovmAuthTokenInput
+ tokenHits int
+ listPages [][]types.MicrovmItem
+}
+
+func (f *fakeAPI) RunMicrovm(_ context.Context, in *lambdamicrovms.RunMicrovmInput, _ ...func(*lambdamicrovms.Options)) (*lambdamicrovms.RunMicrovmOutput, error) {
+ f.runIn = in
+ return &lambdamicrovms.RunMicrovmOutput{
+ MicrovmId: aws.String("mvm-1"),
+ Endpoint: aws.String("abc.microvm.aws.dev"),
+ ImageArn: aws.String("arn:image"),
+ }, nil
+}
+
+func (f *fakeAPI) CreateMicrovmAuthToken(_ context.Context, in *lambdamicrovms.CreateMicrovmAuthTokenInput, _ ...func(*lambdamicrovms.Options)) (*lambdamicrovms.CreateMicrovmAuthTokenOutput, error) {
+ f.tokenIn = in
+ f.tokenHits++
+ return &lambdamicrovms.CreateMicrovmAuthTokenOutput{
+ AuthToken: map[string]string{"X-aws-proxy-auth": "jwe-value"},
+ }, nil
+}
+
+func (f *fakeAPI) ListMicrovms(_ context.Context, in *lambdamicrovms.ListMicrovmsInput, _ ...func(*lambdamicrovms.Options)) (*lambdamicrovms.ListMicrovmsOutput, error) {
+ page := 0
+ if in.NextToken != nil {
+ page = 1
+ }
+ out := &lambdamicrovms.ListMicrovmsOutput{Items: f.listPages[page]}
+ if page == 0 && len(f.listPages) > 1 {
+ out.NextToken = aws.String("next")
+ }
+ return out, nil
+}
+
+func (f *fakeAPI) TerminateMicrovm(_ context.Context, _ *lambdamicrovms.TerminateMicrovmInput, _ ...func(*lambdamicrovms.Options)) (*lambdamicrovms.TerminateMicrovmOutput, error) {
+ return &lambdamicrovms.TerminateMicrovmOutput{}, nil
+}
+
+// A MicroVM may not outlive the service ceiling; an over-large config must be
+// clamped rather than passed through to be rejected at run time.
+func TestRunClampsMaximumDurationToCeiling(t *testing.T) {
+ f := &fakeAPI{}
+ c := NewClientWithAPI(f, Config{ImageIdentifier: "arn:image", MaxDurationSeconds: 999_999})
+
+ if _, err := c.Run(context.Background(), "tok"); err != nil {
+ t.Fatalf("Run: %v", err)
+ }
+ if got := aws.ToInt32(f.runIn.MaximumDurationInSeconds); got != maxDurationCeilingSeconds {
+ t.Fatalf("MaximumDurationInSeconds = %d, want clamped to %d", got, maxDurationCeilingSeconds)
+ }
+ if aws.ToString(f.runIn.ClientToken) != "tok" {
+ t.Fatalf("ClientToken not forwarded — retries would leak a second VM and burn quota")
+ }
+}
+
+// The token must be scoped to the agent port. Minting an allPorts token would
+// let a leaked JWE reach any service in the guest.
+func TestAuthTokenScopedToAgentPortAndCached(t *testing.T) {
+ f := &fakeAPI{}
+ c := NewClientWithAPI(f, Config{ImageIdentifier: "arn:image", AgentPort: 9099})
+
+ v, err := c.AuthToken(context.Background(), "mvm-1")
+ if err != nil {
+ t.Fatalf("AuthToken: %v", err)
+ }
+ if v != "jwe-value" {
+ t.Fatalf("token = %q, want jwe-value", v)
+ }
+ if got := aws.ToInt32(f.tokenIn.ExpirationInMinutes); got > authTokenMaxMinutes {
+ t.Fatalf("ExpirationInMinutes = %d exceeds the service max of %d", got, authTokenMaxMinutes)
+ }
+ port, ok := f.tokenIn.AllowedPorts[0].(*types.PortSpecificationMemberPort)
+ if !ok || port.Value != 9099 {
+ t.Fatalf("AllowedPorts = %#v, want a single-port spec for 9099", f.tokenIn.AllowedPorts)
+ }
+
+ // Second call inside the refresh window must not hit the API — token minting
+ // on the exec path is indistinguishable from a slow sandbox.
+ if _, err := c.AuthToken(context.Background(), "mvm-1"); err != nil {
+ t.Fatalf("AuthToken (cached): %v", err)
+ }
+ if f.tokenHits != 1 {
+ t.Fatalf("minted %d tokens, want 1 (cache miss on the hot path)", f.tokenHits)
+ }
+}
+
+// A stale cache entry must be re-minted, or a long-lived sandbox starts failing
+// the moment its first token expires.
+func TestAuthTokenRefreshesWhenStale(t *testing.T) {
+ f := &fakeAPI{}
+ c := NewClientWithAPI(f, Config{ImageIdentifier: "arn:image"})
+
+ if _, err := c.AuthToken(context.Background(), "mvm-1"); err != nil {
+ t.Fatalf("AuthToken: %v", err)
+ }
+ c.mu.Lock()
+ c.tokens["mvm-1"].refreshAt = time.Now().Add(-time.Minute)
+ c.mu.Unlock()
+
+ if _, err := c.AuthToken(context.Background(), "mvm-1"); err != nil {
+ t.Fatalf("AuthToken (stale): %v", err)
+ }
+ if f.tokenHits != 2 {
+ t.Fatalf("minted %d tokens, want 2 (stale entry must refresh)", f.tokenHits)
+ }
+}
+
+// Terminate must drop the cached token; reusing an id (or leaking entries) would
+// hand out a token for a VM that no longer exists.
+func TestTerminateForgetsToken(t *testing.T) {
+ f := &fakeAPI{}
+ c := NewClientWithAPI(f, Config{ImageIdentifier: "arn:image"})
+ if _, err := c.AuthToken(context.Background(), "mvm-1"); err != nil {
+ t.Fatalf("AuthToken: %v", err)
+ }
+ if err := c.Terminate(context.Background(), "mvm-1"); err != nil {
+ t.Fatalf("Terminate: %v", err)
+ }
+ c.mu.Lock()
+ _, still := c.tokens["mvm-1"]
+ c.mu.Unlock()
+ if still {
+ t.Fatal("token cache still holds an entry for a terminated MicroVM")
+ }
+}
+
+// Losing track of a VM means leaking regional memory quota, so List has to walk
+// every page rather than stopping at the first.
+func TestListPaginates(t *testing.T) {
+ f := &fakeAPI{listPages: [][]types.MicrovmItem{
+ {{MicrovmId: aws.String("mvm-1"), State: types.MicrovmStateRunning}},
+ {{MicrovmId: aws.String("mvm-2"), State: types.MicrovmStateSuspended}},
+ }}
+ c := NewClientWithAPI(f, Config{ImageIdentifier: "arn:image"})
+
+ boxes, err := c.List(context.Background())
+ if err != nil {
+ t.Fatalf("List: %v", err)
+ }
+ if len(boxes) != 2 {
+ t.Fatalf("got %d boxes, want 2 — pagination stopped early", len(boxes))
+ }
+}
+
+func TestAliveExcludesTerminalStates(t *testing.T) {
+ for _, tc := range []struct {
+ state types.MicrovmState
+ alive bool
+ }{
+ {types.MicrovmStateRunning, true},
+ {types.MicrovmStateSuspended, true}, // auto-resume can still serve it
+ {types.MicrovmStatePending, true},
+ {types.MicrovmStateTerminating, false},
+ {types.MicrovmStateTerminated, false},
+ } {
+ if got := (Box{State: tc.state}).Alive(); got != tc.alive {
+ t.Errorf("Alive(%s) = %v, want %v", tc.state, got, tc.alive)
+ }
+ }
+}
+
+func TestAgentURLNormalisesScheme(t *testing.T) {
+ for in, want := range map[string]string{
+ "abc.microvm.aws.dev": "https://abc.microvm.aws.dev",
+ "https://abc.microvm.aws.dev": "https://abc.microvm.aws.dev",
+ "": "",
+ } {
+ if got := AgentURL(in); got != want {
+ t.Errorf("AgentURL(%q) = %q, want %q", in, got, want)
+ }
+ }
+}
diff --git a/internal/awsvm/errors.go b/internal/awsvm/errors.go
new file mode 100644
index 00000000..d7af1d50
--- /dev/null
+++ b/internal/awsvm/errors.go
@@ -0,0 +1,48 @@
+package awsvm
+
+import (
+ "errors"
+
+ "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms/types"
+)
+
+// Launch failures split into two kinds that must not be conflated, because the
+// right answer to each is opposite:
+//
+// - ErrQuotaExceeded is terminal for now. The account is at its regional
+// MicroVM memory ceiling and no amount of retrying frees a slot; the only
+// fixes are a customer sandbox ending or AWS raising the quota. Callers
+// should say "out of capacity" and stop.
+// - ErrThrottled is transient. RunMicrovm is rate-limited (5/s), so this
+// means "too fast", not "too full" — the same request a moment later
+// succeeds. Retrying is correct.
+//
+// Reporting a throttle as out-of-capacity would tell an operator to raise a
+// quota that is not the problem; reporting a quota exhaustion as a throttle
+// would spin retries against a wall.
+var (
+ ErrQuotaExceeded = errors.New("awsvm: regional MicroVM quota exhausted")
+ ErrThrottled = errors.New("awsvm: MicroVM API rate limit exceeded")
+)
+
+// classifyLaunchError maps an AWS launch error onto the sentinels above,
+// leaving anything else untouched. Errors are matched by type rather than by
+// message so an SDK wording change cannot silently reclassify them.
+func classifyLaunchError(err error) error {
+ if err == nil {
+ return nil
+ }
+ var quota *types.ServiceQuotaExceededException
+ if errors.As(err, &quota) {
+ return errors.Join(ErrQuotaExceeded, err)
+ }
+ var throttle *types.ThrottlingException
+ if errors.As(err, &throttle) {
+ return errors.Join(ErrThrottled, err)
+ }
+ var tooMany *types.TooManyRequestsException
+ if errors.As(err, &tooMany) {
+ return errors.Join(ErrThrottled, err)
+ }
+ return err
+}
diff --git a/internal/awsvm/errors_test.go b/internal/awsvm/errors_test.go
new file mode 100644
index 00000000..cd1ed6f0
--- /dev/null
+++ b/internal/awsvm/errors_test.go
@@ -0,0 +1,63 @@
+package awsvm
+
+import (
+ "errors"
+ "fmt"
+ "testing"
+
+ "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms/types"
+)
+
+// Quota exhaustion and throttling arrive as different AWS types and demand
+// opposite responses — stop vs retry. These pin that they never collapse into
+// each other, because the code path only runs when a region is actually full,
+// which is exactly when nobody is watching.
+func TestClassifyLaunchErrorSeparatesQuotaFromThrottle(t *testing.T) {
+ cases := []struct {
+ name string
+ in error
+ isQuota bool
+ isThrot bool
+ }{
+ {"quota", &types.ServiceQuotaExceededException{}, true, false},
+ {"throttling", &types.ThrottlingException{}, false, true},
+ {"too many requests", &types.TooManyRequestsException{}, false, true},
+ {"unrelated", errors.New("connection reset"), false, false},
+ {"validation", &types.ValidationException{}, false, false},
+ }
+ for _, tc := range cases {
+ got := classifyLaunchError(tc.in)
+ if errors.Is(got, ErrQuotaExceeded) != tc.isQuota {
+ t.Errorf("%s: ErrQuotaExceeded=%v, want %v", tc.name, !tc.isQuota, tc.isQuota)
+ }
+ if errors.Is(got, ErrThrottled) != tc.isThrot {
+ t.Errorf("%s: ErrThrottled=%v, want %v", tc.name, !tc.isThrot, tc.isThrot)
+ }
+ }
+}
+
+// The original AWS error must survive classification — it carries the request
+// id and message an operator needs, and losing it would leave only our label.
+func TestClassifyLaunchErrorKeepsTheCause(t *testing.T) {
+ cause := &types.ServiceQuotaExceededException{}
+ got := classifyLaunchError(cause)
+ var quota *types.ServiceQuotaExceededException
+ if !errors.As(got, &quota) {
+ t.Fatal("classification discarded the underlying AWS error")
+ }
+}
+
+// Classification happens below several wrapping layers, so matching must work
+// through them.
+func TestClassifyLaunchErrorSurvivesWrapping(t *testing.T) {
+ wrapped := fmt.Errorf("awsvm: run microvm: %w", classifyLaunchError(&types.ServiceQuotaExceededException{}))
+ if !errors.Is(wrapped, ErrQuotaExceeded) {
+ t.Fatal("wrapping hid the quota classification")
+ }
+}
+
+func TestClassifyLaunchErrorPassesNil(t *testing.T) {
+ if got := classifyLaunchError(nil); got != nil {
+ t.Fatalf("classifyLaunchError(nil) = %v, want nil", got)
+ }
+}
diff --git a/internal/awsvm/integration_image_test.go b/internal/awsvm/integration_image_test.go
new file mode 100644
index 00000000..7e69637f
--- /dev/null
+++ b/internal/awsvm/integration_image_test.go
@@ -0,0 +1,37 @@
+package awsvm
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms"
+)
+
+// TestIntegrationInspectImages answers the image half of the plan: what base
+// images Lambda offers to build on, and what the existing images in this
+// account actually are. MicroVM images are NOT bring-your-own-OCI — a build
+// layers a code artifact onto a Lambda-managed base — so the available bases
+// determine how close we can get to our own `base` template.
+//
+// AWSVM_INTEGRATION=1 AWS_REGION=us-east-1 go test ./internal/awsvm/ -run TestIntegrationInspectImages -v
+func TestIntegrationInspectImages(t *testing.T) {
+ client, _ := integrationClient(t)
+ ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
+ defer cancel()
+
+ managed, err := client.ListManagedMicrovmImages(ctx, &lambdamicrovms.ListManagedMicrovmImagesInput{})
+ if err != nil {
+ t.Fatalf("ListManagedMicrovmImages: %v", err)
+ }
+ t.Logf("Lambda-managed base images: %d", len(managed.Items))
+ for _, m := range managed.Items {
+ t.Logf(" base arn=%s", aws.ToString(m.ImageArn))
+ }
+
+ // Deliberately NOT enumerating or inspecting the images already in this
+ // account. It is shared with managed-agents, which serves customers, and
+ // this package has no business reading their build metadata. Anything we
+ // need, we build under our own distinctly-named image.
+}
diff --git a/internal/awsvm/integration_test.go b/internal/awsvm/integration_test.go
new file mode 100644
index 00000000..a83b936d
--- /dev/null
+++ b/internal/awsvm/integration_test.go
@@ -0,0 +1,62 @@
+package awsvm
+
+import (
+ "context"
+ "os"
+ "testing"
+ "time"
+
+ awsconfig "github.com/aws/aws-sdk-go-v2/config"
+ "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms"
+)
+
+// integration_test.go — tests that talk to real AWS.
+//
+// Skipped unless AWSVM_INTEGRATION=1, so `go test ./...` stays hermetic. These
+// exist because the questions that decide this backend's architecture — is the
+// service even enabled for us, how long does a cold RunMicrovm actually take at
+// burst width, does it throttle — cannot be answered from documentation.
+//
+// AWSVM_INTEGRATION=1 AWS_REGION=us-east-1 go test ./internal/awsvm/ -run Integration -v
+
+func integrationClient(t *testing.T) (*lambdamicrovms.Client, string) {
+ t.Helper()
+ if os.Getenv("AWSVM_INTEGRATION") != "1" {
+ t.Skip("set AWSVM_INTEGRATION=1 to run tests against real AWS")
+ }
+ region := os.Getenv("AWS_REGION")
+ if region == "" {
+ region = "us-east-1"
+ }
+ cfg, err := awsconfig.LoadDefaultConfig(context.Background(), awsconfig.WithRegion(region))
+ if err != nil {
+ t.Fatalf("load AWS config: %v", err)
+ }
+ return lambdamicrovms.NewFromConfig(cfg), region
+}
+
+// TestIntegrationDiscover answers the three go/no-go questions in one shot:
+// can this account see the service, is there an image we can borrow, and is
+// anything already running that would be eating quota.
+func TestIntegrationDiscover(t *testing.T) {
+ client, region := integrationClient(t)
+ ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
+ defer cancel()
+
+ t.Logf("region=%s", region)
+
+ // Reachability only — counts, never contents. This account is shared with
+ // managed-agents, which serves customers; enumerating their images or VMs
+ // is none of this package's business. Our own resources are identified by
+ // the names we give them, not by trawling the account.
+ images, err := client.ListMicrovmImages(ctx, &lambdamicrovms.ListMicrovmImagesInput{})
+ if err != nil {
+ t.Fatalf("ListMicrovmImages failed — the service may not be enabled for this account: %v", err)
+ }
+ vms, err := client.ListMicrovms(ctx, &lambdamicrovms.ListMicrovmsInput{})
+ if err != nil {
+ t.Fatalf("ListMicrovms: %v", err)
+ }
+ t.Logf("service reachable: %d image(s), %d microvm(s) exist in this account",
+ len(images.Items), len(vms.Items))
+}
diff --git a/internal/awsvm/manager.go b/internal/awsvm/manager.go
new file mode 100644
index 00000000..8f4d591a
--- /dev/null
+++ b/internal/awsvm/manager.go
@@ -0,0 +1,623 @@
+package awsvm
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "log"
+ "sync"
+ "time"
+
+ "github.com/opensandbox/opensandbox/internal/sandbox"
+ "github.com/opensandbox/opensandbox/internal/storage"
+ "github.com/opensandbox/opensandbox/pkg/types"
+ pb "github.com/opensandbox/opensandbox/proto/agent"
+)
+
+// manager.go — sandbox.Manager over Lambda MicroVMs.
+//
+// The QEMU manager owns processes, disks, networking and snapshots. This one
+// owns almost nothing: AWS holds the VM, and the two things we keep locally are
+// a sandboxID→MicroVM mapping and a pool of agent channels. That asymmetry is
+// the point — it is why the backend is a few hundred lines instead of the
+// tens of thousands internal/qemu needs.
+//
+// Deliberately unsupported here (see ErrUnsupported): checkpoints, fork-from-
+// checkpoint, template/checkpoint caches, reboot and power-cycle. Those are
+// snapshot-and-disk operations with no counterpart in this service; a MicroVM
+// image is built through an API, not captured from a running box. They return a
+// typed error the control plane can turn into a clean 4xx rather than a panic
+// or, worse, a silent success.
+
+// ErrUnsupported marks a Manager capability this backend does not implement.
+// Callers should surface it as "not available on this runtime", never retry it.
+//
+// The API boundary substitutes its own text, so this string is not
+// customer-visible today — but error text is exactly what escapes into a
+// response, a webhook, or a support ticket later, so it stays generic.
+var ErrUnsupported = errors.New("awsvm: operation not supported by this sandbox runtime")
+
+func unsupported(op string) error { return fmt.Errorf("%s: %w", op, ErrUnsupported) }
+
+// entry is one sandbox's local bookkeeping.
+type entry struct {
+ sandboxID string
+ microvmID string
+ endpoint string
+ template string
+ cpuCount int
+ memoryMB int
+ startedAt time.Time
+}
+
+// Manager implements sandbox.Manager against AWS Lambda MicroVMs.
+type Manager struct {
+ client *Client
+ agents *agentPool
+ dataDir string
+
+ mu sync.RWMutex
+ byID map[string]*entry
+}
+
+// Compile-time proof this backend satisfies the same contract as internal/qemu.
+// internal/firecracker carried this same assertion and still rotted, because
+// nothing built it — keep this package in the build/test matrix.
+var _ sandbox.Manager = (*Manager)(nil)
+
+// NewManager builds the backend. dataDir is only used for the Manager's own
+// scratch space; unlike QEMU there are no disks to keep there.
+func NewManager(client *Client, dataDir string) *Manager {
+ return &Manager{
+ client: client,
+ agents: newAgentPool(),
+ dataDir: dataDir,
+ byID: make(map[string]*entry),
+ }
+}
+
+// track records a sandboxID→MicroVM binding. Exported so the pool filler can
+// hand pre-launched boxes to the manager at claim time without a second
+// RunMicrovm — the fast path where the edge answers a create from stock.
+// TrackClaimed binds a pooled box to a sandbox id and adopts the tunnel the
+// pool already established, so the customer's first exec is warm (~85ms) rather
+// than paying the ~1.4s dial. This is the claim path: still zero AWS calls.
+func (m *Manager) TrackClaimed(sandboxID string, e *StockEntry, cfg types.SandboxConfig) {
+ m.Track(sandboxID, &Box{ID: e.MicrovmID, Endpoint: e.Endpoint}, cfg)
+ if e.agent != nil {
+ m.agents.put(sandboxID, e.agent)
+ }
+}
+
+// Default sizing for a MicroVM whose SandboxConfig does not state one.
+//
+// These are NOT cosmetic: the usage ticker reads memoryMB/cpuCount off List()
+// and puts them in every usage_tick, which is what pro-tier metering prices on.
+// Left at zero — which is what a create without an explicit size, or a Restore
+// after a control-plane restart, would otherwise produce — every sandbox meters
+// as if it consumed nothing.
+//
+// 2048 MiB matches the image's minimumMemoryInMiB, and Lambda gives a full vCPU
+// at that baseline (peak scales to 4x).
+const (
+ defaultMicrovmMemoryMB = 2048
+ defaultMicrovmCPUCount = 1
+)
+
+func (m *Manager) Track(sandboxID string, box *Box, cfg types.SandboxConfig) {
+ memoryMB, cpuCount := cfg.MemoryMB, cfg.CpuCount
+ if memoryMB <= 0 {
+ memoryMB = defaultMicrovmMemoryMB
+ }
+ if cpuCount <= 0 {
+ cpuCount = defaultMicrovmCPUCount
+ }
+ m.mu.Lock()
+ m.byID[sandboxID] = &entry{
+ sandboxID: sandboxID,
+ microvmID: box.ID,
+ endpoint: box.Endpoint,
+ template: cfg.Template,
+ cpuCount: cpuCount,
+ memoryMB: memoryMB,
+ startedAt: time.Now(),
+ }
+ m.mu.Unlock()
+}
+
+// MicrovmIDFor returns the AWS MicroVM id bound to a sandbox, from memory only.
+//
+// Separate from Get because Get calls AWS to report live status. Callers on a
+// hot path that only need the binding — the event publisher stamps one on every
+// envelope it flushes — must not turn that into a GetMicrovm per event.
+func (m *Manager) MicrovmIDFor(sandboxID string) (string, bool) {
+ e, err := m.lookup(sandboxID)
+ if err != nil {
+ return "", false
+ }
+ return e.microvmID, true
+}
+
+func (m *Manager) lookup(sandboxID string) (*entry, error) {
+ m.mu.RLock()
+ e, ok := m.byID[sandboxID]
+ m.mu.RUnlock()
+ if !ok {
+ return nil, fmt.Errorf("awsvm: sandbox %s not found", sandboxID)
+ }
+ return e, nil
+}
+
+// agentFor returns the sandbox's agent channel, dialing on first use. The token
+// provider closes over the MicroVM id so refreshes are transparent to callers.
+func (m *Manager) agentFor(e *entry) (*agentConn, error) {
+ return m.agents.get(e.sandboxID, e.endpoint, m.client.Config().AgentPort,
+ func(ctx context.Context) (string, error) {
+ return m.client.AuthToken(ctx, e.microvmID)
+ })
+}
+
+// ── Lifecycle ───────────────────────────────────────────────────────────────
+
+// Create launches a MicroVM for a sandbox. The sandbox id is used as the AWS
+// client token so a retried create rejoins the same VM instead of leaking one —
+// leaked VMs hold regional memory quota, which is the real cap on pool depth.
+func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (*types.Sandbox, error) {
+ sandboxID := cfg.SandboxID
+ if sandboxID == "" {
+ return nil, fmt.Errorf("awsvm: create requires a pre-assigned sandbox id")
+ }
+ box, err := m.client.Run(ctx, sandboxID)
+ if err != nil {
+ return nil, err
+ }
+ m.Track(sandboxID, box, cfg)
+ log.Printf("awsvm: created %s (microvm=%s endpoint=%s)", sandboxID, box.ID, box.Endpoint)
+
+ return &types.Sandbox{
+ ID: sandboxID,
+ Template: cfg.Template,
+ Status: types.SandboxStatusRunning,
+ StartedAt: time.Now(),
+ CpuCount: cfg.CpuCount,
+ MemoryMB: cfg.MemoryMB,
+ }, nil
+}
+
+func (m *Manager) Get(ctx context.Context, id string) (*types.Sandbox, error) {
+ e, err := m.lookup(id)
+ if err != nil {
+ return nil, err
+ }
+ box, err := m.client.Get(ctx, e.microvmID)
+ if err != nil {
+ return nil, err
+ }
+ return &types.Sandbox{
+ ID: id,
+ Template: e.template,
+ Status: statusFor(box),
+ StartedAt: e.startedAt,
+ CpuCount: e.cpuCount,
+ MemoryMB: e.memoryMB,
+ }, nil
+}
+
+// statusFor maps MicroVM lifecycle onto our sandbox status. SUSPENDED reads as
+// hibernated: state is preserved and auto-resume brings it back on demand,
+// which is exactly our paused-hibernation contract.
+func statusFor(b *Box) types.SandboxStatus {
+ switch {
+ case b == nil:
+ return types.SandboxStatusStopped
+ case !b.Alive():
+ return types.SandboxStatusStopped
+ default:
+ return types.SandboxStatusRunning
+ }
+}
+
+func (m *Manager) Kill(ctx context.Context, id string) error {
+ e, err := m.lookup(id)
+ if err != nil {
+ return nil // already gone; destroy is idempotent
+ }
+ m.agents.drop(id)
+ if err := m.client.Terminate(ctx, e.microvmID); err != nil {
+ return err
+ }
+ m.mu.Lock()
+ delete(m.byID, id)
+ m.mu.Unlock()
+ return nil
+}
+
+func (m *Manager) List(ctx context.Context) ([]types.Sandbox, error) {
+ m.mu.RLock()
+ entries := make([]*entry, 0, len(m.byID))
+ for _, e := range m.byID {
+ entries = append(entries, e)
+ }
+ m.mu.RUnlock()
+
+ out := make([]types.Sandbox, 0, len(entries))
+ for _, e := range entries {
+ out = append(out, types.Sandbox{
+ ID: e.sandboxID,
+ Template: e.template,
+ Status: types.SandboxStatusRunning,
+ StartedAt: e.startedAt,
+ CpuCount: e.cpuCount,
+ MemoryMB: e.memoryMB,
+ })
+ }
+ return out, nil
+}
+
+func (m *Manager) Count(ctx context.Context) (int, error) {
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+ return len(m.byID), nil
+}
+
+// IsSandboxAlive gates billing, so it asks AWS rather than trusting local state:
+// a stale in-memory entry driving usage events on a terminated VM is the exact
+// "ghost VM" bug this call exists to prevent.
+func (m *Manager) IsSandboxAlive(ctx context.Context, id string) (bool, error) {
+ e, err := m.lookup(id)
+ if err != nil {
+ return false, nil
+ }
+ box, err := m.client.Get(ctx, e.microvmID)
+ if err != nil {
+ return false, nil
+ }
+ return box.Alive(), nil
+}
+
+func (m *Manager) Close() { m.agents.closeAll() }
+
+// ── Execution ───────────────────────────────────────────────────────────────
+
+func (m *Manager) Exec(ctx context.Context, sandboxID string, cfg types.ProcessConfig) (*types.ProcessResult, error) {
+ e, err := m.lookup(sandboxID)
+ if err != nil {
+ return nil, err
+ }
+ a, err := m.agentFor(e)
+ if err != nil {
+ return nil, err
+ }
+
+ timeout := int32(cfg.Timeout)
+ if timeout <= 0 {
+ timeout = 60
+ }
+ command, args := cfg.Command, cfg.Args
+ if len(args) == 0 {
+ args = []string{"-c", command}
+ command = "/bin/sh"
+ }
+
+ resp, err := a.client.Exec(ctx, &pb.ExecRequest{
+ Command: command,
+ Args: args,
+ Envs: cfg.Env,
+ Cwd: cfg.Cwd,
+ TimeoutSeconds: timeout,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("awsvm: exec in %s: %w", sandboxID, err)
+ }
+ return &types.ProcessResult{
+ ExitCode: int(resp.ExitCode),
+ Stdout: resp.Stdout,
+ Stderr: resp.Stderr,
+ }, nil
+}
+
+// ── Filesystem ──────────────────────────────────────────────────────────────
+
+func (m *Manager) ReadFile(ctx context.Context, sandboxID, path string) (string, error) {
+ a, err := m.agent(sandboxID)
+ if err != nil {
+ return "", err
+ }
+ resp, err := a.client.ReadFile(ctx, &pb.ReadFileRequest{Path: path})
+ if err != nil {
+ return "", err
+ }
+ return string(resp.Content), nil
+}
+
+func (m *Manager) WriteFile(ctx context.Context, sandboxID, path, content string) error {
+ a, err := m.agent(sandboxID)
+ if err != nil {
+ return err
+ }
+ _, err = a.client.WriteFile(ctx, &pb.WriteFileRequest{Path: path, Content: []byte(content)})
+ return err
+}
+
+func (m *Manager) ListDir(ctx context.Context, sandboxID, path string) ([]types.EntryInfo, error) {
+ a, err := m.agent(sandboxID)
+ if err != nil {
+ return nil, err
+ }
+ resp, err := a.client.ListDir(ctx, &pb.ListDirRequest{Path: path})
+ if err != nil {
+ return nil, err
+ }
+ out := make([]types.EntryInfo, 0, len(resp.Entries))
+ for _, e := range resp.Entries {
+ out = append(out, types.EntryInfo{Name: e.Name, IsDir: e.IsDir, Size: e.Size, Path: e.Path})
+ }
+ return out, nil
+}
+
+func (m *Manager) MakeDir(ctx context.Context, sandboxID, path string) error {
+ a, err := m.agent(sandboxID)
+ if err != nil {
+ return err
+ }
+ _, err = a.client.MakeDir(ctx, &pb.MakeDirRequest{Path: path})
+ return err
+}
+
+func (m *Manager) Remove(ctx context.Context, sandboxID, path string) error {
+ a, err := m.agent(sandboxID)
+ if err != nil {
+ return err
+ }
+ _, err = a.client.Remove(ctx, &pb.RemoveRequest{Path: path})
+ return err
+}
+
+func (m *Manager) Exists(ctx context.Context, sandboxID, path string) (bool, error) {
+ a, err := m.agent(sandboxID)
+ if err != nil {
+ return false, err
+ }
+ resp, err := a.client.Exists(ctx, &pb.ExistsRequest{Path: path})
+ if err != nil {
+ return false, err
+ }
+ return resp.Exists, nil
+}
+
+func (m *Manager) Stat(ctx context.Context, sandboxID, path string) (*types.FileInfo, error) {
+ a, err := m.agent(sandboxID)
+ if err != nil {
+ return nil, err
+ }
+ resp, err := a.client.Stat(ctx, &pb.StatRequest{Path: path})
+ if err != nil {
+ return nil, err
+ }
+ return &types.FileInfo{
+ Name: resp.Name, IsDir: resp.IsDir, Size: resp.Size,
+ Mode: resp.Mode, ModTime: resp.ModTime, Path: resp.Path,
+ }, nil
+}
+
+// agent is the lookup+dial shorthand the filesystem methods share.
+func (m *Manager) agent(sandboxID string) (*agentConn, error) {
+ e, err := m.lookup(sandboxID)
+ if err != nil {
+ return nil, err
+ }
+ return m.agentFor(e)
+}
+
+// ── Monitoring ──────────────────────────────────────────────────────────────
+
+func (m *Manager) Stats(ctx context.Context, sandboxID string) (*sandbox.SandboxStats, error) {
+ a, err := m.agent(sandboxID)
+ if err != nil {
+ return nil, err
+ }
+ resp, err := a.client.Stats(ctx, &pb.StatsRequest{})
+ if err != nil {
+ return nil, err
+ }
+ return &sandbox.SandboxStats{
+ CPUPercent: resp.CpuPercent,
+ MemUsage: resp.MemUsage,
+ MemLimit: resp.MemLimit,
+ NetInput: resp.NetInput,
+ NetOutput: resp.NetOutput,
+ PIDs: int(resp.Pids),
+ }, nil
+}
+
+func (m *Manager) DataDir() string { return m.dataDir }
+
+func (m *Manager) ContainerName(id string) string { return "microvm-" + id }
+
+// HostPort has no meaning here: there is no host publishing a port. Customer
+// traffic reaches the guest through the MicroVM's own HTTPS endpoint, so 0 is
+// the honest answer rather than a fabricated port.
+func (m *Manager) HostPort(ctx context.Context, sandboxID string) (int, error) { return 0, nil }
+
+// ContainerAddr returns the endpoint a caller should use to reach a guest port.
+// Unlike the QEMU backend this is a public HTTPS endpoint, and the caller must
+// also present an auth token plus X-aws-proxy-port.
+func (m *Manager) ContainerAddr(ctx context.Context, sandboxID string, port int) (string, error) {
+ e, err := m.lookup(sandboxID)
+ if err != nil {
+ return "", err
+ }
+ return AgentURL(e.endpoint), nil
+}
+
+// ── Hibernation ─────────────────────────────────────────────────────────────
+
+// Hibernate suspends the MicroVM. AWS snapshots memory and disk itself, so
+// there is no checkpoint to upload and no key to hand back — which is why
+// SizeBytes is 0 and the store argument is ignored.
+func (m *Manager) Hibernate(ctx context.Context, sandboxID string, _ *storage.CheckpointStore) (*sandbox.HibernateResult, error) {
+ e, err := m.lookup(sandboxID)
+ if err != nil {
+ return nil, err
+ }
+ if err := m.client.Suspend(ctx, e.microvmID); err != nil {
+ return nil, err
+ }
+ return &sandbox.HibernateResult{SandboxID: sandboxID, HibernationKey: e.microvmID}, nil
+}
+
+// Wake resumes a suspended MicroVM. Callers that are about to send a request
+// could skip this and let auto-resume cover it, but waking explicitly keeps the
+// control plane's state machine honest about when the box became RUNNING.
+func (m *Manager) Wake(ctx context.Context, sandboxID string, _ string, _ *storage.CheckpointStore, _ int) (*types.Sandbox, error) {
+ e, err := m.lookup(sandboxID)
+ if err != nil {
+ return nil, err
+ }
+ if err := m.client.Resume(ctx, e.microvmID); err != nil {
+ return nil, err
+ }
+ return &types.Sandbox{
+ ID: sandboxID, Template: e.template, Status: types.SandboxStatusRunning,
+ StartedAt: e.startedAt, CpuCount: e.cpuCount, MemoryMB: e.memoryMB,
+ }, nil
+}
+
+// ── Not supported on this backend ───────────────────────────────────────────
+
+// SetResourceLimits is a no-op: a MicroVM's shape is fixed by its image and run
+// configuration, and cannot be resized in place the way virtio-mem allows.
+// Returning nil rather than an error keeps the control plane's post-claim grow
+// step harmless instead of failing every create.
+func (m *Manager) SetResourceLimits(ctx context.Context, sandboxID string, maxPids int32, maxMemoryBytes, cpuMaxUsec, cpuPeriodUsec int64) error {
+ return nil
+}
+
+func (m *Manager) UpdateSandboxSecret(ctx context.Context, sandboxID, secretName, value string) (bool, error) {
+ return false, unsupported("UpdateSandboxSecret")
+}
+
+// ReadFileStream streams a file out of the guest.
+//
+// This works for the same reason exec does: the agent channel is a real gRPC
+// connection tunnelled inside a WebSocket, so server-streaming RPCs traverse it
+// unchanged. (It was briefly stubbed as unsupported on the assumption that
+// streaming through Lambda's proxy was unsafe — the tunnel is precisely what
+// makes that assumption obsolete.)
+func (m *Manager) ReadFileStream(ctx context.Context, sandboxID, path string) (io.ReadCloser, int64, error) {
+ a, err := m.agent(sandboxID)
+ if err != nil {
+ return nil, 0, err
+ }
+ stream, err := a.client.ReadFileStream(ctx, &pb.ReadFileStreamRequest{Path: path})
+ if err != nil {
+ return nil, 0, fmt.Errorf("awsvm: read file stream %s: %w", path, err)
+ }
+
+ // Pull the first chunk eagerly: total_size only rides on it, and callers
+ // need the size before they start reading.
+ first, err := stream.Recv()
+ if err != nil {
+ if err == io.EOF {
+ return io.NopCloser(bytes.NewReader(nil)), 0, nil
+ }
+ return nil, 0, fmt.Errorf("awsvm: read file stream %s: %w", path, err)
+ }
+
+ pr, pw := io.Pipe()
+ go func() {
+ defer pw.Close()
+ if _, err := pw.Write(first.Data); err != nil {
+ return
+ }
+ for {
+ chunk, err := stream.Recv()
+ if err == io.EOF {
+ return
+ }
+ if err != nil {
+ // Surface the failure to the reader rather than truncating
+ // silently, which would look like a short but successful file.
+ pw.CloseWithError(fmt.Errorf("awsvm: read file stream %s: %w", path, err))
+ return
+ }
+ if _, err := pw.Write(chunk.Data); err != nil {
+ return
+ }
+ }
+ }()
+ return pr, first.TotalSize, nil
+}
+
+// WriteFileStream streams a file into the guest. Client-streaming gRPC over the
+// same tunnel; path and mode ride the first message only, per the proto.
+func (m *Manager) WriteFileStream(ctx context.Context, sandboxID, path string, mode uint32, r io.Reader) (int64, error) {
+ a, err := m.agent(sandboxID)
+ if err != nil {
+ return 0, err
+ }
+ stream, err := a.client.WriteFileStream(ctx)
+ if err != nil {
+ return 0, fmt.Errorf("awsvm: write file stream %s: %w", path, err)
+ }
+
+ buf := make([]byte, 256*1024)
+ first := true
+ for {
+ n, readErr := r.Read(buf)
+ if n > 0 {
+ msg := &pb.WriteFileStreamRequest{Data: buf[:n]}
+ if first {
+ msg.Path, msg.Mode = path, mode
+ first = false
+ }
+ if err := stream.Send(msg); err != nil {
+ return 0, fmt.Errorf("awsvm: write file stream %s: %w", path, err)
+ }
+ }
+ if readErr == io.EOF {
+ break
+ }
+ if readErr != nil {
+ return 0, fmt.Errorf("awsvm: write file stream %s: read source: %w", path, readErr)
+ }
+ }
+ // An empty file still needs one message, or the agent never learns the path.
+ if first {
+ if err := stream.Send(&pb.WriteFileStreamRequest{Path: path, Mode: mode}); err != nil {
+ return 0, fmt.Errorf("awsvm: write file stream %s: %w", path, err)
+ }
+ }
+
+ resp, err := stream.CloseAndRecv()
+ if err != nil {
+ return 0, fmt.Errorf("awsvm: write file stream %s: %w", path, err)
+ }
+ return resp.BytesWritten, nil
+}
+
+func (m *Manager) RebootSandbox(ctx context.Context, sandboxID string) error {
+ return unsupported("RebootSandbox")
+}
+
+func (m *Manager) PowerCycleSandbox(ctx context.Context, sandboxID string) (int, error) {
+ return 0, unsupported("PowerCycleSandbox")
+}
+
+func (m *Manager) TemplateCachePath(templateID, filename string) string { return "" }
+
+func (m *Manager) CheckpointCachePath(checkpointID, filename string) string { return "" }
+
+func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID string, _ *storage.CheckpointStore, _ func()) (string, string, int64, error) {
+ return "", "", 0, unsupported("CreateCheckpoint")
+}
+
+func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpointID string) error {
+ return unsupported("RestoreFromCheckpoint")
+}
+
+func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, cfg types.SandboxConfig) (*types.Sandbox, error) {
+ return nil, unsupported("ForkFromCheckpoint")
+}
diff --git a/internal/awsvm/pool.go b/internal/awsvm/pool.go
new file mode 100644
index 00000000..9a9f379b
--- /dev/null
+++ b/internal/awsvm/pool.go
@@ -0,0 +1,389 @@
+package awsvm
+
+import (
+ "context"
+ "log"
+ "sync"
+ "time"
+)
+
+// pool.go — a warm pool of RUNNING MicroVMs.
+//
+// The shape here is dictated entirely by the service's rate limits, not by
+// preference. Lambda MicroVMs allows (account+region defaults):
+//
+// RunMicrovm 5/s ResumeMicrovm 5/s
+// SuspendMicrovm 2/s TerminateMicrovm 10/s
+// CreateMicrovmAuthToken 50/s
+//
+// A burst of 100 creates cannot call RunMicrovm — that is 20 seconds of
+// launching. It cannot call ResumeMicrovm either, so the cheaper design of
+// holding stock SUSPENDED (which bills snapshot storage instead of compute) is
+// unavailable: waking 100 suspended boxes is throttled just as hard as
+// launching them.
+//
+// What is left is the only shape that survives a burst: keep the stock RUNNING
+// and make the claim path do ZERO AWS calls. The edge pops a pre-launched box
+// with a pre-minted token and answers immediately; every rate-limited call
+// happens on this background loop, minutes before the customer arrives.
+//
+// The costs of that choice, all of them real:
+// - stocked boxes bill compute the whole time they wait, not storage
+// - idle-suspend must be off, or stock silently drifts into SUSPENDED and the
+// next claim pays a throttled Resume
+// - every box dies at the 8h service cap (running+suspended combined,
+// adjustable=false), so the pool needs continuous rolling replacement
+// - auth tokens last at most 60 minutes, so stock has to be re-tokened in
+// place or it goes stale while waiting
+type PoolConfig struct {
+ // TargetStock is how many RUNNING boxes to keep ready.
+ TargetStock int
+
+ // MaxBoxAge retires a box before the service's hard 8h ceiling. Leave
+ // headroom: a box that hits the cap is terminated by Lambda underneath us,
+ // and a claim that lands on it fails the customer's create.
+ MaxBoxAge time.Duration
+
+ // LaunchInterval paces RunMicrovm calls. Must stay at or under the account's
+ // RunMicrovm rate quota — exceeding it earns ThrottlingException, and a
+ // throttled top-up means the pool silently runs dry under churn.
+ LaunchInterval time.Duration
+
+ // TokenRefreshMargin re-mints a stocked box's token this long before it
+ // expires, so a claim never hands out a token about to die.
+ TokenRefreshMargin time.Duration
+
+ // ReadyTimeout bounds how long a launching box may stay PENDING before we
+ // give up and terminate it. A box that never reaches RUNNING still burns
+ // regional memory quota, so waiting forever quietly shrinks pool capacity.
+ ReadyTimeout time.Duration
+
+ // PreDialTimeout bounds establishing a stocked box's agent tunnel. Exceeding
+ // it costs only a cold first exec on that box, never the box itself.
+ PreDialTimeout time.Duration
+}
+
+func (c *PoolConfig) applyDefaults() {
+ // Zero is a real setting, not "unset": it means run cold-create-only, with
+ // no warm stock. Every caller resolves its own default before constructing
+ // a PoolConfig (the control plane via envInt, the harness via a flag), so a
+ // 0 arriving here is deliberate. Defaulting it up — as this did — silently
+ // launched 20 boxes for an operator who asked for none, which is the same
+ // zero-value trap that made OPENSANDBOX_MAX_WORKERS=0 keep provisioning.
+ if c.TargetStock < 0 {
+ c.TargetStock = 0
+ }
+ if c.MaxBoxAge <= 0 {
+ // 8h service cap minus an hour of slack for retirement to keep up.
+ c.MaxBoxAge = 7 * time.Hour
+ }
+ if c.LaunchInterval <= 0 {
+ // 5/s is the default RunMicrovm quota; 250ms paces at 4/s to leave room
+ // for retirement launches and any other caller in the account.
+ c.LaunchInterval = 250 * time.Millisecond
+ }
+ if c.TokenRefreshMargin <= 0 {
+ c.TokenRefreshMargin = 10 * time.Minute
+ }
+ if c.ReadyTimeout <= 0 {
+ c.ReadyTimeout = 45 * time.Second
+ }
+ if c.PreDialTimeout <= 0 {
+ c.PreDialTimeout = 30 * time.Second
+ }
+}
+
+// StockEntry is one ready-to-claim box. Everything a caller needs to talk to it
+// is here, which is the whole point: claiming touches no AWS API.
+type StockEntry struct {
+ MicrovmID string
+ Endpoint string
+ Token string
+
+ // agent is a gRPC channel already dialled and connected through the
+ // WebSocket tunnel. Establishing it costs ~1.4s (token mint, WS handshake,
+ // HTTP/2 setup) against ~85ms for an exec on an established channel, so
+ // leaving it to the first exec would put that 1.4s squarely on the
+ // customer's create→first-command path. Doing it here spends it while the
+ // box is idle in stock, for the same reason tokens are pre-minted.
+ agent *agentConn
+
+ tokenMintedAt time.Time
+ launchedAt time.Time
+}
+
+// Pool keeps TargetStock boxes launched, tokened and fresh.
+type Pool struct {
+ client *Client
+ cfg PoolConfig
+
+ // preDial establishes a box's agent tunnel while it waits in stock. It is a
+ // field rather than a direct call so tests can disable it: dialling is real
+ // network I/O against a real MicroVM endpoint, which a fake AWS API cannot
+ // satisfy — without this seam the unit tests block on a doomed handshake.
+ preDial func(ctx context.Context, microvmID, endpoint string) (*agentConn, error)
+
+ mu sync.Mutex
+ stock []*StockEntry
+ // inflight counts launches that have called RunMicrovm but are still
+ // waiting to reach RUNNING. Without it the ticker sees a low Depth() and
+ // keeps launching, overshooting the target by however many boxes fit in one
+ // boot time — each one burning memory quota we cannot get back quickly.
+ inflight int
+}
+
+func NewPool(client *Client, cfg PoolConfig) *Pool {
+ cfg.applyDefaults()
+ p := &Pool{client: client, cfg: cfg}
+ p.preDial = client.DialAgentConnected
+ return p
+}
+
+// Claim removes a ready box from stock and returns it. No AWS calls, no
+// blocking, no error path — a miss simply means the caller must fall back to a
+// direct create (and eat the RunMicrovm rate limit) or fail fast.
+func (p *Pool) Claim() (*StockEntry, bool) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ for len(p.stock) > 0 {
+ e := p.stock[len(p.stock)-1]
+ p.stock = p.stock[:len(p.stock)-1]
+ // Skip anything that aged out while queued rather than handing a
+ // customer a box Lambda is about to terminate underneath them.
+ if time.Since(e.launchedAt) < p.cfg.MaxBoxAge {
+ return e, true
+ }
+ go p.terminate(e)
+ }
+ return nil, false
+}
+
+// Depth reports current stock, for telemetry and for the sizing invariant: the
+// edge's shards must not target more stock in aggregate than the pool can hold,
+// or shards starve while hoarding — the same failure that cost us 1045ms vs
+// 174ms on the QEMU fleet.
+func (p *Pool) Depth() int {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ return len(p.stock)
+}
+
+// Run drives the maintenance loop until ctx is cancelled. Everything
+// rate-limited lives here, deliberately far from any customer request.
+func (p *Pool) Run(ctx context.Context) {
+ log.Printf("awsvm: pool starting (target=%d maxAge=%s launchInterval=%s)",
+ p.cfg.TargetStock, p.cfg.MaxBoxAge, p.cfg.LaunchInterval)
+
+ launch := time.NewTicker(p.cfg.LaunchInterval)
+ defer launch.Stop()
+ maintain := time.NewTicker(30 * time.Second)
+ defer maintain.Stop()
+
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-launch.C:
+ // One launch per tick is what keeps us under the RunMicrovm quota.
+ // Topping up "as fast as possible" is exactly how you earn a
+ // ThrottlingException storm.
+ //
+ // The launch itself runs in its own goroutine because it now waits
+ // for the box to reach RUNNING. Doing that inline would pace the
+ // pool at boot time rather than at the quota, turning a parallel
+ // fill into a serial one.
+ if p.committed() < p.cfg.TargetStock {
+ go func() {
+ if err := p.launchOne(ctx); err != nil {
+ log.Printf("awsvm: pool launch failed: %v", err)
+ }
+ }()
+ }
+ case <-maintain.C:
+ p.refreshTokens(ctx)
+ p.retireAged(ctx)
+ }
+ }
+}
+
+// launchOne adds a single box to stock: run it, mint its token, park it.
+// committed is stock plus launches still in flight — what the pool will have
+// once everything settles, and therefore the right number to compare against
+// the target when deciding whether to launch more.
+func (p *Pool) committed() int {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ return len(p.stock) + p.inflight
+}
+
+func (p *Pool) launchOne(ctx context.Context) error {
+ p.mu.Lock()
+ p.inflight++
+ p.mu.Unlock()
+ defer func() {
+ p.mu.Lock()
+ p.inflight--
+ p.mu.Unlock()
+ }()
+
+ // Generous relative to boot: this bounds the whole launch including the wait
+ // for RUNNING, and ReadyTimeout is the tighter budget inside it.
+ runCtx, cancel := context.WithTimeout(ctx, 2*time.Minute)
+ defer cancel()
+
+ // No client token: each pool box is a fresh VM with no caller-facing
+ // identity to be idempotent against. Sandbox ids are assigned at claim.
+ box, err := p.client.Run(runCtx, "")
+ if err != nil {
+ return err
+ }
+
+ // Do not park a box until Lambda says it is RUNNING. RunMicrovm returns
+ // while the VM is still restoring, and a claim that lands on a PENDING box
+ // gets 502 from the proxy — the pool's whole job is to absorb that wait so
+ // the customer never sees it.
+ ready, err := p.client.WaitRunning(runCtx, box.ID, p.cfg.ReadyTimeout)
+ if err != nil {
+ go p.terminateID(box.ID)
+ return err
+ }
+ box = ready
+
+ token, err := p.client.AuthToken(runCtx, box.ID)
+ if err != nil {
+ // A box we cannot token is useless as stock and would otherwise sit
+ // burning quota and compute until the age cap.
+ go p.terminateID(box.ID)
+ return err
+ }
+
+ // Pre-establish the agent tunnel so the first exec is warm. A failure here
+ // is not fatal: the box is still perfectly usable, the first exec just pays
+ // the dial itself, which is strictly better than discarding a launched box.
+ var agent *agentConn
+ if p.preDial != nil {
+ dialCtx, cancelDial := context.WithTimeout(runCtx, p.cfg.PreDialTimeout)
+ a, derr := p.preDial(dialCtx, box.ID, box.Endpoint)
+ cancelDial()
+ if derr != nil {
+ log.Printf("awsvm: pool pre-dial %s failed, box still usable cold: %v", box.ID, derr)
+ } else {
+ agent = a
+ }
+ }
+
+ p.mu.Lock()
+ p.stock = append(p.stock, &StockEntry{
+ MicrovmID: box.ID,
+ Endpoint: box.Endpoint,
+ Token: token,
+ agent: agent,
+ tokenMintedAt: time.Now(),
+ launchedAt: time.Now(),
+ })
+ depth := len(p.stock)
+ p.mu.Unlock()
+
+ log.Printf("awsvm: pool +1 %s (depth=%d/%d)", box.ID, depth, p.cfg.TargetStock)
+ return nil
+}
+
+// refreshTokens re-mints tokens that are approaching expiry. Tokens cap at 60
+// minutes, so any box that waits in stock longer than that outlives its token;
+// without this the pool fills with entries whose credentials are already dead.
+// CreateMicrovmAuthToken is quota'd at 50/s, comfortably above stock size, so
+// this can run in one pass.
+func (p *Pool) refreshTokens(ctx context.Context) {
+ cutoff := time.Duration(authTokenMaxMinutes)*time.Minute - p.cfg.TokenRefreshMargin
+
+ p.mu.Lock()
+ stale := make([]*StockEntry, 0)
+ for _, e := range p.stock {
+ if time.Since(e.tokenMintedAt) >= cutoff {
+ stale = append(stale, e)
+ }
+ }
+ p.mu.Unlock()
+
+ for _, e := range stale {
+ tokenCtx, cancel := context.WithTimeout(ctx, 15*time.Second)
+ token, err := p.client.AuthToken(tokenCtx, e.MicrovmID)
+ cancel()
+ if err != nil {
+ log.Printf("awsvm: pool token refresh %s: %v", e.MicrovmID, err)
+ continue
+ }
+ p.mu.Lock()
+ e.Token = token
+ e.tokenMintedAt = time.Now()
+ p.mu.Unlock()
+ }
+ if len(stale) > 0 {
+ log.Printf("awsvm: pool refreshed %d token(s)", len(stale))
+ }
+}
+
+// retireAged terminates stock approaching the 8h ceiling so the launch loop can
+// replace it. Retiring early is the point: a box terminated by Lambda mid-claim
+// is a failed create, and success rate multiplies the benchmark score directly.
+func (p *Pool) retireAged(ctx context.Context) {
+ p.mu.Lock()
+ kept := p.stock[:0]
+ var retire []*StockEntry
+ for _, e := range p.stock {
+ if time.Since(e.launchedAt) >= p.cfg.MaxBoxAge {
+ retire = append(retire, e)
+ continue
+ }
+ kept = append(kept, e)
+ }
+ p.stock = kept
+ p.mu.Unlock()
+
+ for _, e := range retire {
+ p.terminate(e)
+ }
+ if len(retire) > 0 {
+ log.Printf("awsvm: pool retired %d aged box(es)", len(retire))
+ }
+}
+
+func (p *Pool) terminate(e *StockEntry) {
+ // Close the pre-dialled tunnel too, or retiring stock leaks a goroutine and
+ // a socket per box.
+ if e.agent != nil {
+ _ = e.agent.Close()
+ }
+ p.terminateID(e.MicrovmID)
+}
+
+func (p *Pool) terminateID(id string) {
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ if err := p.client.Terminate(ctx, id); err != nil {
+ log.Printf("awsvm: pool terminate %s: %v", id, err)
+ }
+}
+
+// Drain terminates all stock. Called on shutdown so a restarting filler does not
+// abandon boxes — abandoned boxes hold both compute cost and regional quota
+// until they hit the 8h cap.
+func (p *Pool) Drain() {
+ p.mu.Lock()
+ stock := p.stock
+ p.stock = nil
+ p.mu.Unlock()
+
+ var wg sync.WaitGroup
+ for _, e := range stock {
+ wg.Add(1)
+ go func(e *StockEntry) {
+ defer wg.Done()
+ p.terminate(e)
+ }(e)
+ }
+ wg.Wait()
+ if len(stock) > 0 {
+ log.Printf("awsvm: pool drained %d box(es)", len(stock))
+ }
+}
diff --git a/internal/awsvm/pool_test.go b/internal/awsvm/pool_test.go
new file mode 100644
index 00000000..3f3f39ea
--- /dev/null
+++ b/internal/awsvm/pool_test.go
@@ -0,0 +1,244 @@
+package awsvm
+
+import (
+ "context"
+ "fmt"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms"
+ "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms/types"
+)
+
+// poolAPI counts the AWS calls the pool makes, so the tests can assert on the
+// property that actually matters: claiming must not touch AWS at all.
+type poolAPI struct {
+ API
+ mu sync.Mutex
+ runs int
+ gets int
+ tokens int
+ terminates []string
+}
+
+func (f *poolAPI) RunMicrovm(_ context.Context, _ *lambdamicrovms.RunMicrovmInput, _ ...func(*lambdamicrovms.Options)) (*lambdamicrovms.RunMicrovmOutput, error) {
+ f.mu.Lock()
+ f.runs++
+ id := fmt.Sprintf("mvm-%d", f.runs)
+ f.mu.Unlock()
+ return &lambdamicrovms.RunMicrovmOutput{
+ MicrovmId: aws.String(id),
+ Endpoint: aws.String(id + ".microvm.aws.dev"),
+ ImageArn: aws.String("arn:image"),
+ }, nil
+}
+
+// GetMicrovm reports RUNNING immediately. Real boxes spend seconds PENDING —
+// that gap is exactly why the pool waits before stocking a box — but these
+// tests are about call accounting, not boot timing, so waiting here would only
+// make them slow.
+func (f *poolAPI) GetMicrovm(_ context.Context, in *lambdamicrovms.GetMicrovmInput, _ ...func(*lambdamicrovms.Options)) (*lambdamicrovms.GetMicrovmOutput, error) {
+ f.mu.Lock()
+ f.gets++
+ f.mu.Unlock()
+ id := aws.ToString(in.MicrovmIdentifier)
+ return &lambdamicrovms.GetMicrovmOutput{
+ MicrovmId: aws.String(id),
+ Endpoint: aws.String(id + ".microvm.aws.dev"),
+ ImageArn: aws.String("arn:image"),
+ State: types.MicrovmStateRunning,
+ }, nil
+}
+
+func (f *poolAPI) CreateMicrovmAuthToken(_ context.Context, in *lambdamicrovms.CreateMicrovmAuthTokenInput, _ ...func(*lambdamicrovms.Options)) (*lambdamicrovms.CreateMicrovmAuthTokenOutput, error) {
+ f.mu.Lock()
+ f.tokens++
+ n := f.tokens
+ f.mu.Unlock()
+ return &lambdamicrovms.CreateMicrovmAuthTokenOutput{
+ AuthToken: map[string]string{"X-aws-proxy-auth": fmt.Sprintf("jwe-%d", n)},
+ }, nil
+}
+
+func (f *poolAPI) TerminateMicrovm(_ context.Context, in *lambdamicrovms.TerminateMicrovmInput, _ ...func(*lambdamicrovms.Options)) (*lambdamicrovms.TerminateMicrovmOutput, error) {
+ f.mu.Lock()
+ f.terminates = append(f.terminates, aws.ToString(in.MicrovmIdentifier))
+ f.mu.Unlock()
+ return &lambdamicrovms.TerminateMicrovmOutput{}, nil
+}
+
+func (f *poolAPI) counts() (int, int, int) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.runs, f.tokens, len(f.terminates)
+}
+
+func testPool(t *testing.T, cfg PoolConfig) (*Pool, *poolAPI) {
+ t.Helper()
+ f := &poolAPI{}
+ c := NewClientWithAPI(f, Config{ImageIdentifier: "arn:image"})
+ p := NewPool(c, cfg)
+ // No real endpoints behind the fake API, so pre-dialling would block on a
+ // handshake that can never complete. The claim-path accounting these tests
+ // assert on is unaffected.
+ p.preDial = nil
+ return p, f
+}
+
+// The whole design rests on this: a claim must make ZERO AWS calls. Any call on
+// this path reintroduces the 5/s RunMicrovm / ResumeMicrovm ceiling and a
+// burst-100 becomes a 20-second launch window.
+func TestClaimMakesNoAWSCalls(t *testing.T) {
+ p, f := testPool(t, PoolConfig{TargetStock: 5})
+ for i := 0; i < 5; i++ {
+ if err := p.launchOne(context.Background()); err != nil {
+ t.Fatalf("launchOne: %v", err)
+ }
+ }
+ runsBefore, tokensBefore, termsBefore := f.counts()
+
+ for i := 0; i < 5; i++ {
+ e, ok := p.Claim()
+ if !ok {
+ t.Fatalf("claim %d missed on a full pool", i)
+ }
+ if e.Endpoint == "" || e.Token == "" {
+ t.Fatalf("claim returned an entry without endpoint/token: %+v", e)
+ }
+ }
+
+ runs, tokens, terms := f.counts()
+ if runs != runsBefore || tokens != tokensBefore || terms != termsBefore {
+ t.Fatalf("claiming hit AWS: runs %d→%d tokens %d→%d terminates %d→%d",
+ runsBefore, runs, tokensBefore, tokens, termsBefore, terms)
+ }
+}
+
+// An empty pool must fail fast rather than block or launch inline — the caller
+// decides whether to eat a rate-limited direct create.
+func TestClaimOnEmptyPoolMisses(t *testing.T) {
+ p, f := testPool(t, PoolConfig{TargetStock: 1})
+ if _, ok := p.Claim(); ok {
+ t.Fatal("claim succeeded on an empty pool")
+ }
+ if runs, _, _ := f.counts(); runs != 0 {
+ t.Fatalf("empty claim triggered %d RunMicrovm call(s)", runs)
+ }
+}
+
+// Boxes die at the 8h service cap whether we like it or not. Handing one out
+// near the ceiling means Lambda terminates it under the customer, so aged stock
+// must be skipped and cleaned up instead.
+func TestClaimSkipsAndTerminatesAgedStock(t *testing.T) {
+ p, f := testPool(t, PoolConfig{TargetStock: 2, MaxBoxAge: time.Hour})
+ for i := 0; i < 2; i++ {
+ if err := p.launchOne(context.Background()); err != nil {
+ t.Fatalf("launchOne: %v", err)
+ }
+ }
+ p.mu.Lock()
+ for _, e := range p.stock {
+ e.launchedAt = time.Now().Add(-2 * time.Hour)
+ }
+ p.mu.Unlock()
+
+ if _, ok := p.Claim(); ok {
+ t.Fatal("claim handed out a box past MaxBoxAge")
+ }
+ // Termination is fired asynchronously; give it a moment.
+ deadline := time.Now().Add(2 * time.Second)
+ for time.Now().Before(deadline) {
+ if _, _, terms := f.counts(); terms == 2 {
+ return
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ _, _, terms := f.counts()
+ t.Fatalf("aged stock not terminated: %d of 2", terms)
+}
+
+// Stock that outlives its token is worse than no stock: the claim succeeds and
+// the customer's first request fails auth.
+func TestRefreshTokensRemintsStaleEntries(t *testing.T) {
+ p, f := testPool(t, PoolConfig{TargetStock: 2, TokenRefreshMargin: 10 * time.Minute})
+ for i := 0; i < 2; i++ {
+ if err := p.launchOne(context.Background()); err != nil {
+ t.Fatalf("launchOne: %v", err)
+ }
+ }
+ _, tokensAfterLaunch, _ := f.counts()
+
+ p.mu.Lock()
+ for _, e := range p.stock {
+ e.tokenMintedAt = time.Now().Add(-55 * time.Minute) // inside the margin
+ // Force a client-cache miss too, else AuthToken returns the cached value.
+ delete(p.client.tokens, e.MicrovmID)
+ }
+ p.mu.Unlock()
+
+ p.refreshTokens(context.Background())
+
+ _, tokensNow, _ := f.counts()
+ if tokensNow != tokensAfterLaunch+2 {
+ t.Fatalf("re-minted %d token(s), want 2", tokensNow-tokensAfterLaunch)
+ }
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ for _, e := range p.stock {
+ if time.Since(e.tokenMintedAt) > time.Minute {
+ t.Fatal("entry still carries a stale tokenMintedAt after refresh")
+ }
+ }
+}
+
+// A restarting filler must not abandon boxes: they hold compute cost and
+// regional quota until the 8h cap.
+func TestDrainTerminatesAllStock(t *testing.T) {
+ p, f := testPool(t, PoolConfig{TargetStock: 3})
+ for i := 0; i < 3; i++ {
+ if err := p.launchOne(context.Background()); err != nil {
+ t.Fatalf("launchOne: %v", err)
+ }
+ }
+ p.Drain()
+
+ if got := p.Depth(); got != 0 {
+ t.Fatalf("depth after drain = %d, want 0", got)
+ }
+ if _, _, terms := f.counts(); terms != 3 {
+ t.Fatalf("drain terminated %d box(es), want 3", terms)
+ }
+}
+
+// The launch loop must respect the RunMicrovm quota. Defaults pace under 5/s.
+func TestDefaultLaunchIntervalStaysUnderRunQuota(t *testing.T) {
+ var cfg PoolConfig
+ cfg.applyDefaults()
+ rate := float64(time.Second) / float64(cfg.LaunchInterval)
+ if rate > 5.0 {
+ t.Fatalf("default launch rate %.1f/s exceeds the RunMicrovm quota of 5/s", rate)
+ }
+ if cfg.MaxBoxAge >= 8*time.Hour {
+ t.Fatalf("MaxBoxAge %s leaves no headroom under the 8h service cap", cfg.MaxBoxAge)
+ }
+}
+
+// TargetStock 0 means "no warm stock, cold-create only" — a real operating mode
+// now that a pool miss launches a box instead of failing. It used to be
+// defaulted up to 20, which launched twenty boxes for an operator who asked for
+// none, and quietly invalidated any test of the cold path.
+func TestZeroTargetStockKeepsPoolEmpty(t *testing.T) {
+ p, f := testPool(t, PoolConfig{TargetStock: 0})
+ _ = f
+ if got := p.cfg.TargetStock; got != 0 {
+ t.Fatalf("TargetStock 0 became %d — pool would stock boxes nobody asked for", got)
+ }
+ if d := p.Depth(); d != 0 {
+ t.Fatalf("empty-target pool reported depth %d", d)
+ }
+ if _, ok := p.Claim(); ok {
+ t.Fatal("claimed a box from a pool configured to hold none")
+ }
+}
diff --git a/internal/controlplane/capacity_reporter.go b/internal/controlplane/capacity_reporter.go
index cfdfaa37..45bb5419 100644
--- a/internal/controlplane/capacity_reporter.go
+++ b/internal/controlplane/capacity_reporter.go
@@ -62,10 +62,49 @@ type capacityPayload struct {
RunningSandboxes int `json:"running_sandboxes"`
}
+// CapacitySource supplies the three placement numbers for a cell.
+//
+// Behind an interface because "capacity" is not inherently a worker count —
+// that is just how a QEMU cell measures it. A cell backed by AWS Lambda
+// MicroVMs has no workers at all, and with the registry hardcoded here it could
+// never emit cell_capacity, so the edge's isHealthy() gate (which requires
+// available_workers > 0) refused to route to it — including an explicit
+// cellId pin. The cell was unreachable, not unhealthy.
+//
+// available is the one that matters to placement: the edge treats > 0 as "this
+// cell can accept a create" and ignores the other two.
+type CapacitySource interface {
+ Capacity() (healthy, available, running int)
+}
+
+// workerRegistryCapacity is the QEMU cell's answer: count workers whose REAL
+// memory usage is under the pressure threshold. Unchanged from when this logic
+// lived inline in emit().
+type workerRegistryCapacity struct{ registry *RedisWorkerRegistry }
+
+// WorkerRegistryCapacity adapts a worker registry to a CapacitySource.
+func WorkerRegistryCapacity(r *RedisWorkerRegistry) CapacitySource {
+ return workerRegistryCapacity{registry: r}
+}
+
+func (w workerRegistryCapacity) Capacity() (healthy, available, running int) {
+ for _, wk := range w.registry.GetAllWorkers() {
+ if wk == nil || wk.Draining {
+ continue
+ }
+ healthy++
+ running += wk.Current
+ if wk.MemPct < memPressureThresholdPct {
+ available++
+ }
+ }
+ return healthy, available, running
+}
+
// CapacityReporter periodically XADDs cell_capacity events.
type CapacityReporter struct {
rdb *redis.Client
- registry *RedisWorkerRegistry
+ source CapacitySource
cellID string
streamKey string
interval time.Duration
@@ -77,8 +116,11 @@ type CapacityReporter struct {
// CapacityReporterConfig configures the reporter.
type CapacityReporterConfig struct {
- Redis *redis.Client
+ Redis *redis.Client
+ // Registry is the QEMU shorthand for Source. Exactly one of the two must be
+ // set; Registry wins when both are, so existing callers keep their meaning.
Registry *RedisWorkerRegistry
+ Source CapacitySource
CellID string
Interval time.Duration // default 30s
}
@@ -89,8 +131,12 @@ func NewCapacityReporter(cfg CapacityReporterConfig) (*CapacityReporter, error)
if cfg.Redis == nil {
return nil, errors.New("capacity_reporter: Redis required")
}
- if cfg.Registry == nil {
- return nil, errors.New("capacity_reporter: Registry required")
+ source := cfg.Source
+ if cfg.Registry != nil {
+ source = WorkerRegistryCapacity(cfg.Registry)
+ }
+ if source == nil {
+ return nil, errors.New("capacity_reporter: Registry or Source required")
}
if cfg.CellID == "" {
return nil, errors.New("capacity_reporter: CellID required")
@@ -101,7 +147,7 @@ func NewCapacityReporter(cfg CapacityReporterConfig) (*CapacityReporter, error)
}
return &CapacityReporter{
rdb: cfg.Redis,
- registry: cfg.Registry,
+ source: source,
cellID: cfg.CellID,
streamKey: "events:" + cfg.CellID,
interval: iv,
@@ -142,18 +188,7 @@ func (r *CapacityReporter) runLoop(ctx context.Context) {
}
func (r *CapacityReporter) emit(ctx context.Context) {
- workers := r.registry.GetAllWorkers()
- var healthy, available, running int
- for _, w := range workers {
- if w == nil || w.Draining {
- continue
- }
- healthy++
- running += w.Current
- if w.MemPct < memPressureThresholdPct {
- available++
- }
- }
+ healthy, available, running := r.source.Capacity()
payload, err := json.Marshal(capacityPayload{
HealthyWorkers: healthy,
diff --git a/internal/controlplane/capacity_reporter_test.go b/internal/controlplane/capacity_reporter_test.go
new file mode 100644
index 00000000..23227fd0
--- /dev/null
+++ b/internal/controlplane/capacity_reporter_test.go
@@ -0,0 +1,44 @@
+package controlplane
+
+import (
+ "testing"
+
+ "github.com/redis/go-redis/v9"
+)
+
+type fakeCapacity struct{ healthy, available, running int }
+
+func (f fakeCapacity) Capacity() (int, int, int) { return f.healthy, f.available, f.running }
+
+// A cell that reports no capacity is not routed to by the edge — isHealthy()
+// gates on available_workers > 0. So a reporter constructed with no source at
+// all must fail loudly at startup rather than run and emit zeros, which would
+// read as "cell full" and silently strand every create.
+func TestNewCapacityReporterRequiresASource(t *testing.T) {
+ _, err := NewCapacityReporter(CapacityReporterConfig{
+ Redis: nil,
+ CellID: "cell-a",
+ })
+ if err == nil {
+ t.Fatal("constructed a reporter with neither Registry nor Source")
+ }
+}
+
+// The MicroVM control plane supplies capacity directly: it has no worker
+// registry, and requiring one is exactly what made such a cell unroutable.
+func TestNewCapacityReporterAcceptsACustomSource(t *testing.T) {
+ src := fakeCapacity{healthy: 1, available: 3, running: 7}
+ r, err := NewCapacityReporter(CapacityReporterConfig{
+ // Never dialled — the constructor only nil-checks it.
+ Redis: redis.NewClient(&redis.Options{Addr: "127.0.0.1:1"}),
+ Source: src,
+ CellID: "cell-a",
+ })
+ if err != nil {
+ t.Fatalf("NewCapacityReporter: %v", err)
+ }
+ h, a, run := r.source.Capacity()
+ if h != 1 || a != 3 || run != 7 {
+ t.Fatalf("source reported (%d,%d,%d), want (1,3,7)", h, a, run)
+ }
+}
diff --git a/internal/db/store.go b/internal/db/store.go
index 3e1e06aa..2222497b 100644
--- a/internal/db/store.go
+++ b/internal/db/store.go
@@ -1261,7 +1261,21 @@ func (s *Store) RecoverStaleMigrations(ctx context.Context, maxAge time.Duration
// of worker IDs currently registered. Without the returned IDs the maintenance
// loop's PG sweep would never reach D1 sandboxes_index, which is exactly
// the post-cutover ghost-row bug.
-func (s *Store) MarkOrphanedSandboxes(ctx context.Context, liveWorkers map[string]bool) ([]OrphanedSandbox, error) {
+// likePatterns turns worker_id prefixes into SQL LIKE patterns. A nil result
+// would make `LIKE ANY` match nothing, so callers with no managed backends get
+// a pattern that cannot match a real worker_id rather than an empty array.
+func likePatterns(prefixes []string) []string {
+ if len(prefixes) == 0 {
+ return []string{"\x00-no-managed-backends"}
+ }
+ out := make([]string, 0, len(prefixes))
+ for _, p := range prefixes {
+ out = append(out, p+"%")
+ }
+ return out
+}
+
+func (s *Store) MarkOrphanedSandboxes(ctx context.Context, liveWorkers map[string]bool, managedPrefixes []string) ([]OrphanedSandbox, error) {
// Include 'pending' as well as 'running': a create that never reached
// running (still 'pending') on a worker that has since disappeared must also
// be closed, since its scale_event is open and would keep billing. 'pending'
@@ -1272,9 +1286,18 @@ func (s *Store) MarkOrphanedSandboxes(ctx context.Context, liveWorkers map[strin
// bound (RAM-resident QEMU pause), so if its worker is dead the box must be
// reaped too. Without this, a worker holding only paused boxes would never
// be seen as "dead" and its boxes would stay stuck 'hibernated' forever.
+ // Managed-host rows are excluded: their worker_id is synthetic because
+ // the host is managed for us and no worker exists to register. They are
+ // absent from liveWorkers by construction, so this sweep would mark
+ // every one of them 'error / worker lost' within a tick of being
+ // created. Their liveness is reconciled against their own backend
+ // instead. The prefixes come from the registered backends, so a new
+ // runtime is covered without editing this query.
`SELECT DISTINCT worker_id FROM sandbox_sessions
- WHERE status IN ('running', 'pending')
- OR (status = 'hibernated' AND hibernation_mode = 'paused')`)
+ WHERE NOT (worker_id LIKE ANY($1))
+ AND (status IN ('running', 'pending')
+ OR (status = 'hibernated' AND hibernation_mode = 'paused'))`,
+ likePatterns(managedPrefixes))
if err != nil {
return nil, err
}
@@ -1306,9 +1329,10 @@ func (s *Store) MarkOrphanedSandboxes(ctx context.Context, liveWorkers map[strin
// (mode != 'paused') have a durable S3 checkpoint and are left alone.
`UPDATE sandbox_sessions SET status = 'error', error_msg = 'worker lost', stopped_at = now()
WHERE worker_id = $1
+ AND NOT (worker_id LIKE ANY($2))
AND (status IN ('running', 'pending')
OR (status = 'hibernated' AND hibernation_mode = 'paused'))
- RETURNING sandbox_id, org_id, worker_id`, workerID)
+ RETURNING sandbox_id, org_id, worker_id`, workerID, likePatterns(managedPrefixes))
if err != nil {
tx.Rollback(ctx)
continue
@@ -1508,6 +1532,56 @@ type WorkerSandboxRef struct {
// when a worker rejoins after a gap, we look up what cell PG thinks is *running*
// on that worker, ask the worker what it actually has, and close any cell-PG row
// the worker doesn't claim. Bounded to 1000 rows so a runaway query never blows.
+// MicrovmSessionRef is a persisted MicroVM-backed sandbox: our sandbox id plus
+// the encoded worker_id that carries the AWS MicroVM id.
+type MicrovmSessionRef struct {
+ SandboxID string
+ WorkerID string
+ // Config is the persisted SandboxConfig JSON. Carried here because the
+ // restore path has to re-derive the sandbox's size from it: usage ticks
+ // price on memory/cpu, so a restore that dropped them would silently
+ // re-meter every surviving sandbox at the backend's default.
+ Config []byte
+}
+
+// ListMicrovmSessions returns running MicroVM-backed sandboxes.
+//
+// These rows carry worker_id "microvm:<microvmID>" rather than a real worker,
+// because AWS holds the VM and there is no worker to name. Encoding the MicroVM
+// id there — instead of adding a column — is what lets a restarting control
+// plane rebuild its in-memory sandbox→MicroVM map. Without it those sandboxes
+// survive in the database but become unroutable, and nothing ever reaps the
+// boxes, which then bill compute until the 8h service cap.
+func (s *Store) ListMicrovmSessions(ctx context.Context, prefixes []string) ([]MicrovmSessionRef, error) {
+ if len(prefixes) == 0 {
+ return nil, nil
+ }
+ rows, err := s.pool.Query(ctx,
+ // Prefixes come from the registered backends rather than literals here,
+ // so adding a runtime cannot leave this predicate behind — the failure
+ // that would look like sandboxes surviving a restart unroutable, with
+ // their hosts running and nothing able to reap them.
+ `SELECT sandbox_id, worker_id, config FROM sandbox_sessions
+ WHERE worker_id LIKE ANY($1) AND status = 'running'
+ ORDER BY started_at DESC
+ LIMIT 1000`, likePatterns(prefixes))
+ if err != nil {
+ return nil, fmt.Errorf("list microvm sessions: %w", err)
+ }
+ defer rows.Close()
+
+ var out []MicrovmSessionRef
+ for rows.Next() {
+ var sandboxID, workerID string
+ var config []byte
+ if err := rows.Scan(&sandboxID, &workerID, &config); err != nil {
+ return nil, err
+ }
+ out = append(out, MicrovmSessionRef{SandboxID: sandboxID, WorkerID: workerID, Config: config})
+ }
+ return out, rows.Err()
+}
+
func (s *Store) ListSandboxesByWorkerStatus(ctx context.Context, workerID, status string) ([]WorkerSandboxRef, error) {
rows, err := s.pool.Query(ctx,
`SELECT sandbox_id, org_id FROM sandbox_sessions
diff --git a/internal/worker/redis_event_publisher.go b/internal/worker/redis_event_publisher.go
index 50d343f4..1707b783 100644
--- a/internal/worker/redis_event_publisher.go
+++ b/internal/worker/redis_event_publisher.go
@@ -34,6 +34,20 @@ type SandboxEventEnvelope struct {
// fields blank, which the CF ingest treats as "unknown — log only, no debit."
type MetadataResolver func(sandboxID string) (orgID, plan string, ok bool)
+// WorkerIDResolver returns the worker id that currently owns a sandbox.
+//
+// A QEMU worker owns every sandbox in its SandboxDBs, so it leaves this nil and
+// the publisher stamps its own id. The control plane's MicroVM backend does
+// not: AWS holds the VMs and each carries its own `microvm:<id>` owner, so it
+// resolves per sandbox.
+//
+// This is not cosmetic. events-ingest drops a usage_tick whose worker_id
+// disagrees with sandboxes_index.worker_id — that guard is what stops a
+// migration source or an abandoned `-incoming` receiver from double-billing a
+// box something else already bills. Stamping one id for differently-owned
+// sandboxes would trip it and silently lose the ticks.
+type WorkerIDResolver func(sandboxID string) (workerID string, ok bool)
+
// RedisEventPublisher polls per-sandbox SQLite every poll interval for unsynced
// events and XADDs them to events:{cell_id} with MaxLen approx 100k. Marks
// events synced on successful XADD.
@@ -41,9 +55,10 @@ type MetadataResolver func(sandboxID string) (orgID, plan string, ok bool)
// Runs parallel to the legacy NATS publisher during cutover — see
// docs/dev-cutover-runbook.md.
type RedisEventPublisher struct {
- rdb *redis.Client
- sandboxDBs *sandbox.SandboxDBManager
- resolver MetadataResolver
+ rdb *redis.Client
+ sandboxDBs *sandbox.SandboxDBManager
+ resolver MetadataResolver
+ workerResolver WorkerIDResolver
cellID string
workerID string
@@ -60,21 +75,27 @@ type RedisEventPublisher struct {
// RedisEventPublisherConfig configures the publisher.
type RedisEventPublisherConfig struct {
- RedisURL string
- SandboxDBs *sandbox.SandboxDBManager
- Resolver MetadataResolver // optional — if nil, org_id/plan fields are blank
- CellID string
- WorkerID string
- MaxLen int64
- PollInterval time.Duration // default 2s
- BatchSize int // GetAllUnsyncedEventsFlat limitPerDB; default 100
+ RedisURL string
+ // Client, when set, is used instead of dialing RedisURL. The control plane
+ // already holds a configured client (TLS, auth, pool); re-deriving one from
+ // a URL would be a second place for that config to drift. The publisher
+ // never closes a client it did not open.
+ Client *redis.Client
+ SandboxDBs *sandbox.SandboxDBManager
+ Resolver MetadataResolver // optional — if nil, org_id/plan fields are blank
+ WorkerIDResolver WorkerIDResolver // optional — if nil, every envelope carries WorkerID
+ CellID string
+ WorkerID string
+ MaxLen int64
+ PollInterval time.Duration // default 2s
+ BatchSize int // GetAllUnsyncedEventsFlat limitPerDB; default 100
}
-// NewRedisEventPublisher constructs a publisher. CellID, WorkerID,
-// SandboxDBs and RedisURL are required.
+// NewRedisEventPublisher constructs a publisher. CellID, WorkerID, SandboxDBs
+// and one of RedisURL / Client are required.
func NewRedisEventPublisher(cfg RedisEventPublisherConfig) (*RedisEventPublisher, error) {
- if cfg.RedisURL == "" {
- return nil, errors.New("redis_event_publisher: RedisURL required")
+ if cfg.RedisURL == "" && cfg.Client == nil {
+ return nil, errors.New("redis_event_publisher: RedisURL or Client required")
}
if cfg.CellID == "" {
return nil, errors.New("redis_event_publisher: CellID required")
@@ -86,22 +107,25 @@ func NewRedisEventPublisher(cfg RedisEventPublisherConfig) (*RedisEventPublisher
return nil, errors.New("redis_event_publisher: SandboxDBs required")
}
- opts, err := redis.ParseURL(cfg.RedisURL)
- if err != nil {
- return nil, fmt.Errorf("invalid redis URL: %w", err)
- }
- opts.PoolSize = 3
- opts.MinIdleConns = 1
- opts.ConnMaxIdleTime = 5 * time.Minute
- opts.ConnMaxLifetime = 30 * time.Minute
- opts.MaxRetries = 3
-
- rdb := redis.NewClient(opts)
- pingCtx, pingCancel := context.WithTimeout(context.Background(), 5*time.Second)
- defer pingCancel()
- if err := rdb.Ping(pingCtx).Err(); err != nil {
- rdb.Close()
- return nil, fmt.Errorf("redis ping failed: %w", err)
+ rdb := cfg.Client
+ if rdb == nil {
+ opts, err := redis.ParseURL(cfg.RedisURL)
+ if err != nil {
+ return nil, fmt.Errorf("invalid redis URL: %w", err)
+ }
+ opts.PoolSize = 3
+ opts.MinIdleConns = 1
+ opts.ConnMaxIdleTime = 5 * time.Minute
+ opts.ConnMaxLifetime = 30 * time.Minute
+ opts.MaxRetries = 3
+
+ rdb = redis.NewClient(opts)
+ pingCtx, pingCancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer pingCancel()
+ if err := rdb.Ping(pingCtx).Err(); err != nil {
+ rdb.Close()
+ return nil, fmt.Errorf("redis ping failed: %w", err)
+ }
}
if cfg.PollInterval <= 0 {
@@ -115,9 +139,11 @@ func NewRedisEventPublisher(cfg RedisEventPublisherConfig) (*RedisEventPublisher
}
return &RedisEventPublisher{
- rdb: rdb,
- sandboxDBs: cfg.SandboxDBs,
- resolver: cfg.Resolver,
+ rdb: rdb,
+ sandboxDBs: cfg.SandboxDBs,
+ resolver: cfg.Resolver,
+ workerResolver: cfg.WorkerIDResolver,
+
cellID: cfg.CellID,
workerID: cfg.WorkerID,
streamKey: "events:" + cfg.CellID,
@@ -162,6 +188,20 @@ func (p *RedisEventPublisher) run(ctx context.Context) {
}
}
+// workerIDFor returns the owner to stamp on a sandbox's envelopes, falling back
+// to the publisher's own id when no resolver is configured or the sandbox is
+// unknown to it. Falling back rather than dropping is deliberate: an unstamped
+// envelope still bills (events-ingest skips the ownership check when either
+// side is blank), while a dropped one is revenue lost silently.
+func (p *RedisEventPublisher) workerIDFor(sandboxID string) string {
+ if p.workerResolver != nil {
+ if id, ok := p.workerResolver(sandboxID); ok && id != "" {
+ return id
+ }
+ }
+ return p.workerID
+}
+
// FlushSandbox synchronously publishes all unsynced events for a single
// sandbox. Used as the SandboxDBManager.OnRemove hook so terminal events
// (stopped, hibernated) make it to Redis before the per-sandbox SQLite file
@@ -198,6 +238,8 @@ func (p *RedisEventPublisher) FlushSandbox(ctx context.Context, sandboxID string
}
}
+ workerID := p.workerIDFor(sandboxID)
+
var syncedIDs []int64
for _, e := range events {
ts, err := time.Parse(time.RFC3339Nano, e.CreatedAt)
@@ -220,7 +262,7 @@ func (p *RedisEventPublisher) FlushSandbox(ctx context.Context, sandboxID string
SandboxID: sandboxID,
OrgID: orgID,
Plan: plan,
- WorkerID: p.workerID,
+ WorkerID: workerID,
CellID: p.cellID,
Payload: json.RawMessage(e.Payload),
Timestamp: ts,
@@ -271,7 +313,7 @@ func (p *RedisEventPublisher) flush(ctx context.Context) {
ID: fmt.Sprintf("%s:%d:%d", se.SandboxID, se.Generation, se.Event.ID),
Type: se.Event.Type,
SandboxID: se.SandboxID,
- WorkerID: p.workerID,
+ WorkerID: p.workerIDFor(se.SandboxID),
CellID: p.cellID,
Payload: json.RawMessage(se.Event.Payload),
Timestamp: se.Timestamp,
diff --git a/internal/worker/redis_event_publisher_test.go b/internal/worker/redis_event_publisher_test.go
new file mode 100644
index 00000000..79dbb8aa
--- /dev/null
+++ b/internal/worker/redis_event_publisher_test.go
@@ -0,0 +1,46 @@
+package worker
+
+import "testing"
+
+// The envelope's worker_id is not decoration: events-ingest drops a usage_tick
+// whose worker_id disagrees with sandboxes_index.worker_id, so getting this
+// wrong loses revenue silently — the ticks are published, acknowledged, and
+// then discarded downstream with nothing on our side to show for it.
+
+// A QEMU worker owns everything in its SandboxDBs and configures no resolver.
+// It must keep stamping its own id.
+func TestWorkerIDForDefaultsToPublisherID(t *testing.T) {
+ p := &RedisEventPublisher{workerID: "worker-eastus2-7"}
+ if got := p.workerIDFor("sb-abc"); got != "worker-eastus2-7" {
+ t.Fatalf("workerIDFor = %q, want the publisher's own id", got)
+ }
+}
+
+// The MicroVM control plane publishes for sandboxes with differing owners, so
+// the resolver — not the publisher's id — decides.
+func TestWorkerIDForUsesResolver(t *testing.T) {
+ p := &RedisEventPublisher{
+ workerID: "microvm-cp",
+ workerResolver: func(sandboxID string) (string, bool) {
+ return "microvm:" + sandboxID, true
+ },
+ }
+ if got := p.workerIDFor("sb-abc"); got != "microvm:sb-abc" {
+ t.Fatalf("workerIDFor = %q, want the resolved owner", got)
+ }
+}
+
+// A sandbox the resolver cannot place still has to bill. Both the not-ok and
+// the empty-string returns fall back rather than emitting a blank owner, since
+// dropping the id here is the one outcome nothing downstream would report.
+func TestWorkerIDForFallsBackWhenUnresolved(t *testing.T) {
+ for name, resolver := range map[string]WorkerIDResolver{
+ "not found": func(string) (string, bool) { return "", false },
+ "empty id": func(string) (string, bool) { return "", true },
+ } {
+ p := &RedisEventPublisher{workerID: "microvm-cp", workerResolver: resolver}
+ if got := p.workerIDFor("sb-gone"); got != "microvm-cp" {
+ t.Fatalf("%s: workerIDFor = %q, want the fallback id", name, got)
+ }
+ }
+}
diff --git a/internal/wsconn/wsconn.go b/internal/wsconn/wsconn.go
new file mode 100644
index 00000000..edbe52b3
--- /dev/null
+++ b/internal/wsconn/wsconn.go
@@ -0,0 +1,116 @@
+// Package wsconn adapts a WebSocket into a net.Conn.
+//
+// It exists because AWS Lambda MicroVMs' auth proxy strips HTTP/2 trailers.
+// gRPC delivers its status (grpc-status/grpc-message) in trailers, so an RPC
+// forwarded through that proxy as ordinary HTTP/2 completes in the guest and
+// then fails at the client with "server closed the stream without sending
+// trailers" — verified directly by round-tripping an unannounced trailer, which
+// vanished, while the identical exchange against a local Go server preserved it.
+//
+// A WebSocket, however, passes through intact. Wrapping it as a net.Conn lets
+// gRPC run its own HTTP/2 over the tunnel: the proxy sees opaque WebSocket
+// frames and never inspects — or discards — the trailers inside. The agent's
+// entire API keeps working unchanged, which is the point; the alternatives
+// (gRPC-Web, Connect, a bespoke HTTP/JSON exec route) all mean reworking the
+// service definition the QEMU backend already depends on.
+package wsconn
+
+import (
+ "errors"
+ "io"
+ "net"
+ "sync"
+ "time"
+
+ "github.com/gorilla/websocket"
+)
+
+// Conn is a net.Conn backed by a WebSocket connection.
+type Conn struct {
+ ws *websocket.Conn
+
+ // readMu serialises readers and guards the partial-message remainder.
+ // gorilla permits only one concurrent reader and one concurrent writer,
+ // while HTTP/2 above us will happily use the conn from several goroutines.
+ readMu sync.Mutex
+ rest io.Reader
+
+ writeMu sync.Mutex
+}
+
+// New wraps a WebSocket connection as a net.Conn.
+func New(ws *websocket.Conn) *Conn { return &Conn{ws: ws} }
+
+// Read fills p from the current WebSocket message, pulling the next message
+// when the current one is exhausted.
+//
+// Message boundaries carry no meaning here: HTTP/2 has its own framing, and a
+// reader may ask for fewer bytes than a message holds. Keeping the remainder is
+// what makes this a byte stream rather than a datagram channel.
+func (c *Conn) Read(p []byte) (int, error) {
+ c.readMu.Lock()
+ defer c.readMu.Unlock()
+
+ for {
+ if c.rest != nil {
+ n, err := c.rest.Read(p)
+ if err == io.EOF {
+ c.rest = nil
+ // A zero-length message must not surface as a spurious EOF to
+ // the caller — go back for the next one.
+ if n == 0 {
+ continue
+ }
+ return n, nil
+ }
+ return n, err
+ }
+ _, r, err := c.ws.NextReader()
+ if err != nil {
+ return 0, translateErr(err)
+ }
+ c.rest = r
+ }
+}
+
+// Write sends p as a single binary WebSocket message.
+func (c *Conn) Write(p []byte) (int, error) {
+ c.writeMu.Lock()
+ defer c.writeMu.Unlock()
+ if err := c.ws.WriteMessage(websocket.BinaryMessage, p); err != nil {
+ return 0, translateErr(err)
+ }
+ return len(p), nil
+}
+
+func (c *Conn) Close() error { return c.ws.Close() }
+
+func (c *Conn) LocalAddr() net.Addr { return c.ws.LocalAddr() }
+func (c *Conn) RemoteAddr() net.Addr { return c.ws.RemoteAddr() }
+
+func (c *Conn) SetDeadline(t time.Time) error {
+ if err := c.ws.SetReadDeadline(t); err != nil {
+ return err
+ }
+ return c.ws.SetWriteDeadline(t)
+}
+
+func (c *Conn) SetReadDeadline(t time.Time) error { return c.ws.SetReadDeadline(t) }
+func (c *Conn) SetWriteDeadline(t time.Time) error { return c.ws.SetWriteDeadline(t) }
+
+// translateErr maps a normal WebSocket close onto io.EOF. Without this, an
+// orderly shutdown reaches gRPC as an unexpected transport failure and surfaces
+// to callers as an error rather than a clean end of stream.
+func translateErr(err error) error {
+ if err == nil {
+ return nil
+ }
+ var ce *websocket.CloseError
+ if errors.As(err, &ce) {
+ switch ce.Code {
+ case websocket.CloseNormalClosure, websocket.CloseGoingAway:
+ return io.EOF
+ }
+ }
+ return err
+}