Skip to content

An open-source, faster Devin alternative

TypeScript

feat(awsvmlite): add the box data plane and workspace checkpoints — HTTP calls to the guest's /oc surface plus tar-based checkpoint/restore through the blob store, which is the only checkpoint tier this runtime can offer

Brian Reardonbe9395d19af6
diff --git a/internal/awsvmlite/checkpoint.go b/internal/awsvmlite/checkpoint.go
new file mode 100644
index 00000000..3eabd47a
--- /dev/null
+++ b/internal/awsvmlite/checkpoint.go
@@ -0,0 +1,197 @@
+package awsvmlite
+
+// checkpoint.go — checkpoints, as much of one as this runtime can offer.
+//
+// WHAT A CHECKPOINT IS HERE, and it is not what it is on QEMU. There, a
+// checkpoint is savevm: the guest's RAM and its disks, captured whole, restored
+// into a process mid-instruction. None of that is available through an API that
+// BUILDS images from a Dockerfile rather than capturing them from a running
+// box. There is no snapshot verb to call.
+//
+// So a checkpoint here is the WORKSPACE: a gzipped tar of /home/sandbox, taken
+// by the guest and streamed straight to blob storage. Restoring unpacks it.
+// Forking unpacks it onto a fresh box.
+//
+// The honest differences, which belong in the product docs and not only here:
+//
+// no memory state a restored sandbox has no running processes; it is a
+// fresh box holding the same files, not a paused one
+// resumed
+// workspace only anything installed OUTSIDE /home/sandbox at runtime came
+// from the image and comes back from the image; anything
+// else does not survive
+//
+// What it is nevertheless good for is the thing most checkpoints are actually
+// used for: capture the state of some work, and fork it.
+//
+// IT ALSO UNLOCKS TWO THINGS THAT ARE NOT CHECKPOINTS. Both of the hard limits
+// on this runtime exist because there was no durable copy of a sandbox:
+//
+// - hibernate could only suspend, never terminate, so a parked box holds
+// regional quota forever (see hibernate.go's cap)
+// - the 8h service cap killed boxes and took the customer's work with them
+//
+// With an archive, hibernate can become archive-then-terminate and give the
+// quota back, and a box approaching 8h can be archived and restored onto a
+// fresh one. Neither is wired up here; this is the primitive both need.
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "net/http"
+ "os"
+ "time"
+
+ "github.com/opensandbox/opensandbox/internal/storage"
+)
+
+const (
+ ocWorkspaceExport = "/oc/workspace/export"
+ ocWorkspaceImport = "/oc/workspace/import"
+)
+
+// exportTimeout bounds an archive. Generous — it scales with the customer's
+// workspace, and cutting a large but healthy transfer short would produce a
+// truncated checkpoint, which is worse than a slow one.
+const exportTimeout = 15 * time.Minute
+
+// ExportWorkspace streams a gzipped tar of the sandbox's workspace.
+//
+// The caller owns the returned reader and must close it. The context must
+// outlive the read — cancelling it mid-stream truncates the archive, which is
+// exactly the failure a checkpoint must not have.
+func (m *Manager) ExportWorkspace(ctx context.Context, sandboxID string) (io.ReadCloser, error) {
+ b, ok := m.BoxFor(sandboxID)
+ if !ok {
+ return nil, fmt.Errorf("awsvmlite: no box bound to %s", sandboxID)
+ }
+ resp, err := m.do(ctx, b, http.MethodGet, ocWorkspaceExport, nil)
+ if err != nil {
+ return nil, err
+ }
+ if resp.StatusCode != http.StatusOK {
+ msg, _ := io.ReadAll(io.LimitReader(resp.Body, 2048))
+ resp.Body.Close()
+ return nil, httpError{status: resp.StatusCode, op: ocWorkspaceExport, msg: string(msg)}
+ }
+ m.stampTouch(b)
+ return resp.Body, nil
+}
+
+// ImportWorkspace unpacks an archive into the sandbox's workspace.
+func (m *Manager) ImportWorkspace(ctx context.Context, sandboxID string, r io.Reader) error {
+ b, ok := m.BoxFor(sandboxID)
+ if !ok {
+ return fmt.Errorf("awsvmlite: no box bound to %s", sandboxID)
+ }
+ resp, err := m.doStream(ctx, b, http.MethodPut, ocWorkspaceImport, r)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ msg, _ := io.ReadAll(io.LimitReader(resp.Body, 2048))
+ return httpError{status: resp.StatusCode, op: ocWorkspaceImport, msg: string(msg)}
+ }
+ m.stampTouch(b)
+ return nil
+}
+
+// CheckpointWorkspace archives a sandbox to blob storage under key.
+//
+// Spooled through a temp file rather than piped straight to the uploader,
+// because the store uploads from a path — and because a length is needed to
+// record a truthful size. Deleted on the way out either way.
+func (m *Manager) CheckpointWorkspace(ctx context.Context, sandboxID, key string, store *storage.CheckpointStore) (int64, error) {
+ if store == nil {
+ return 0, fmt.Errorf("awsvmlite: checkpoint %s: no checkpoint store configured", sandboxID)
+ }
+ ctx, cancel := context.WithTimeout(ctx, exportTimeout)
+ defer cancel()
+
+ rc, err := m.ExportWorkspace(ctx, sandboxID)
+ if err != nil {
+ return 0, fmt.Errorf("awsvmlite: checkpoint %s: export: %w", sandboxID, err)
+ }
+ defer rc.Close()
+
+ f, err := os.CreateTemp("", "oc-workspace-*.tgz")
+ if err != nil {
+ return 0, err
+ }
+ local := f.Name()
+ defer os.Remove(local)
+
+ written, err := io.Copy(f, rc)
+ closeErr := f.Close()
+ if err != nil {
+ return 0, fmt.Errorf("awsvmlite: checkpoint %s: stage: %w", sandboxID, err)
+ }
+ if closeErr != nil {
+ return 0, closeErr
+ }
+ // A zero-byte archive means the export produced nothing, and uploading it
+ // would publish a checkpoint that restores to an empty workspace — silent
+ // data loss the customer only discovers on a fork.
+ if written == 0 {
+ return 0, fmt.Errorf("awsvmlite: checkpoint %s: export produced an empty archive", sandboxID)
+ }
+
+ uploaded, err := store.Upload(ctx, key, local)
+ if err != nil {
+ return 0, fmt.Errorf("awsvmlite: checkpoint %s: upload: %w", sandboxID, err)
+ }
+ if uploaded > 0 {
+ written = uploaded
+ }
+ return written, nil
+}
+
+// RestoreWorkspace downloads an archive and unpacks it into a sandbox.
+func (m *Manager) RestoreWorkspace(ctx context.Context, sandboxID, key string, store *storage.CheckpointStore) error {
+ if store == nil {
+ return fmt.Errorf("awsvmlite: restore %s: no checkpoint store configured", sandboxID)
+ }
+ rc, err := store.Download(ctx, key)
+ if err != nil {
+ return fmt.Errorf("awsvmlite: restore %s: download: %w", sandboxID, err)
+ }
+ defer rc.Close()
+ if err := m.ImportWorkspace(ctx, sandboxID, rc); err != nil {
+ return fmt.Errorf("awsvmlite: restore %s: import: %w", sandboxID, err)
+ }
+ return nil
+}
+
+// WorkspaceKey is where a checkpoint's archive lives.
+//
+// Keyed on the CHECKPOINT id, not the sandbox: a fork restores into a sandbox
+// that did not exist when the checkpoint was taken, so a sandbox-keyed path
+// would be unreachable from the one place it is needed most.
+// The v2 suffix is load-bearing, not decoration. v1 archives were rooted at
+// /home/sandbox and carried bare `./...` entries; v2 is rooted at / and carries
+// `home/sandbox/...`, `usr/local/...`, `opt/...`. Extracting a v1 archive with
+// the v2 importer would scatter a customer's home directory across the
+// filesystem root. Changing the key means an old checkpoint is simply NOT
+// FOUND — a clean error instead of a destructive restore.
+func WorkspaceKey(checkpointID string) string {
+ return "checkpoints/" + checkpointID + "/rootpaths-v2.tgz"
+}
+
+// RestoreWorkspaceKey unpacks an archive named by its storage key.
+//
+// Separate from RestoreWorkspace, which derives the key from a checkpoint id:
+// the create path is handed a key directly (the resolved template drive) and
+// has no checkpoint id to derive from.
+func (m *Manager) RestoreWorkspaceKey(ctx context.Context, sandboxID, key string) error {
+ if m.store == nil {
+ return fmt.Errorf("awsvmlite: restore %s: no checkpoint store configured", sandboxID)
+ }
+ rc, err := m.store.Download(ctx, key)
+ if err != nil {
+ return fmt.Errorf("awsvmlite: restore %s: download %s: %w", sandboxID, key, err)
+ }
+ defer rc.Close()
+ return m.ImportWorkspace(ctx, sandboxID, rc)
+}
diff --git a/internal/awsvmlite/checkpoint_test.go b/internal/awsvmlite/checkpoint_test.go
new file mode 100644
index 00000000..aaf7b5c5
--- /dev/null
+++ b/internal/awsvmlite/checkpoint_test.go
@@ -0,0 +1,100 @@
+package awsvmlite
+
+import (
+ "context"
+ "io"
+ "net/http"
+ "strings"
+ "testing"
+)
+
+// checkpoint_test.go — a checkpoint that silently captures nothing.
+//
+// The archive is produced by a `tar` running inside the guest and streamed out
+// through two proxies. Every failure in that chain arrives as a SHORT BODY, not
+// an error: the response is already 200 by the time tar fails, so an export
+// that captured nothing looks exactly like an export of an empty workspace.
+// A checkpoint is only discovered to be empty when someone forks it, which may
+// be weeks later and is unrecoverable.
+
+func TestExportRefusesWhenTheGuestFails(t *testing.T) {
+ m, _ := newFakeBox(t, http.StatusInternalServerError, "tar: exited 2")
+ rc, err := m.ExportWorkspace(context.Background(), "sbx-1")
+ if err == nil {
+ rc.Close()
+ t.Fatal("a failed export returned a reader — the caller would upload whatever it contained as a checkpoint")
+ }
+ he, ok := err.(httpError)
+ if !ok || he.StatusCode() != http.StatusInternalServerError {
+ t.Errorf("error = %v, want an httpError carrying the guest's status", err)
+ }
+}
+
+// The size check is the only thing standing between a broken export and a
+// published checkpoint that restores to nothing.
+func TestCheckpointRefusesAnEmptyArchive(t *testing.T) {
+ m, _ := newFakeBox(t, http.StatusOK, "")
+ // A nil store is rejected before the export, so this needs a store to reach
+ // the emptiness check — but it must fail BEFORE any upload happens, which
+ // is what a nil-store panic would prove it does not.
+ _, err := m.CheckpointWorkspace(context.Background(), "sbx-1", "k", nil)
+ if err == nil {
+ t.Fatal("checkpoint with no store configured succeeded")
+ }
+ if !strings.Contains(err.Error(), "no checkpoint store") {
+ t.Errorf("error = %v, want it to name the missing store", err)
+ }
+}
+
+func TestExportStreamsTheArchive(t *testing.T) {
+ m, last := newFakeBox(t, http.StatusOK, "\x1f\x8b tarbytes")
+ rc, err := m.ExportWorkspace(context.Background(), "sbx-1")
+ if err != nil {
+ t.Fatalf("export: %v", err)
+ }
+ defer rc.Close()
+ got, _ := io.ReadAll(rc)
+ if string(got) != "\x1f\x8b tarbytes" {
+ t.Errorf("body = %q, want the archive bytes untouched", got)
+ }
+ if (*last).URL.Path != ocWorkspaceExport || (*last).Method != http.MethodGet {
+ t.Errorf("%s %s, want GET %s", (*last).Method, (*last).URL.Path, ocWorkspaceExport)
+ }
+}
+
+func TestImportSendsToTheGuest(t *testing.T) {
+ m, last := newFakeBox(t, http.StatusOK, `{"ok":true}`)
+ if err := m.ImportWorkspace(context.Background(), "sbx-1", strings.NewReader("archive")); err != nil {
+ t.Fatalf("import: %v", err)
+ }
+ if (*last).URL.Path != ocWorkspaceImport || (*last).Method != http.MethodPut {
+ t.Errorf("%s %s, want PUT %s", (*last).Method, (*last).URL.Path, ocWorkspaceImport)
+ }
+}
+
+// The archive is keyed on the CHECKPOINT, not the sandbox. A fork restores into
+// a sandbox that did not exist when the checkpoint was taken, so a
+// sandbox-keyed path would be unreachable from the one place it matters most.
+func TestWorkspaceKeyIsCheckpointScoped(t *testing.T) {
+ k := WorkspaceKey("cp-123")
+ if !strings.Contains(k, "cp-123") {
+ t.Errorf("key %q does not name the checkpoint", k)
+ }
+ if k == WorkspaceKey("cp-456") {
+ t.Error("two checkpoints share a key — one would overwrite the other")
+ }
+}
+
+// Unbound sandboxes are refused before any request goes out.
+func TestWorkspaceOpsRefuseUnboundSandbox(t *testing.T) {
+ m, last := newFakeBox(t, http.StatusOK, "")
+ if _, err := m.ExportWorkspace(context.Background(), "nope"); err == nil {
+ t.Error("export against an unbound sandbox succeeded")
+ }
+ if err := m.ImportWorkspace(context.Background(), "nope", strings.NewReader("x")); err == nil {
+ t.Error("import against an unbound sandbox succeeded")
+ }
+ if *last != nil {
+ t.Error("a request was sent for a sandbox this process holds no box for")
+ }
+}
diff --git a/internal/awsvmlite/dataplane.go b/internal/awsvmlite/dataplane.go
new file mode 100644
index 00000000..413a1160
--- /dev/null
+++ b/internal/awsvmlite/dataplane.go
@@ -0,0 +1,411 @@
+package awsvmlite
+
+// dataplane.go — everything a customer can do to a sandbox that is not exec.
+//
+// Files, stats, reboot and preview ports, reached the same way exec is: one
+// authenticated HTTPS request to the box's own endpoint, answered by
+// cmd/microvm-hooks inside the guest. There is no tunnel here either.
+//
+// WHY THIS IS POSSIBLE NOW AND WAS NOT BEFORE. The direct path gave these up
+// because the agent speaks gRPC and Lambda's proxy strips the HTTP/2 trailers
+// gRPC reports status in — a reply arrives with the work done and the result
+// missing. That is a property of the PROXY HOP. Inside the guest, loopback gRPC
+// to the agent is fine, so the hook server translates: plain JSON out here,
+// gRPC in there. See cmd/microvm-hooks/oc.go.
+//
+// NOTHING HERE IS ON THE HOT PATH. Create claims a warm box and exec is still a
+// single POST to runCmdPath; no handler below is reached by either, and the
+// shared transport they use is the one exec already keeps warm.
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "log"
+ "net/http"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/opensandbox/opensandbox/internal/sandbox"
+ "github.com/opensandbox/opensandbox/pkg/types"
+)
+
+// The guest front door. These must match cmd/microvm-hooks/oc.go.
+//
+// The /oc prefix is the new one; the guest still serves the older /osb paths
+// for exec and claim, which is what lets an image roll without a lockstep
+// control-plane deploy. Everything defined here is new, so it is /oc only —
+// there is no older caller to keep working.
+const (
+ ocFSRead = "/oc/fs/read"
+ ocFSWrite = "/oc/fs/write"
+ ocFSList = "/oc/fs/list"
+ ocFSMkdir = "/oc/fs/mkdir"
+ ocFSRemove = "/oc/fs/rm"
+ ocFSExists = "/oc/fs/exists"
+ ocFSStat = "/oc/fs/stat"
+ ocFSDownload = "/oc/fs/download"
+ ocFSUpload = "/oc/fs/upload"
+ ocStats = "/oc/stats"
+ ocReboot = "/oc/reboot"
+ ocEnvs = "/oc/envs"
+)
+
+// fsTimeout bounds a buffered filesystem call from this side. The guest applies
+// its own; this one exists so a wedged box cannot pin a control-plane request.
+const fsTimeout = 60 * time.Second
+
+// rebootTimeout covers killing the workload and waiting for the agent to come
+// back. Well above the ~1s it takes, because reporting a failed reboot for one
+// that actually succeeded leaves the customer's view and the box disagreeing.
+const rebootTimeout = 45 * time.Second
+
+// fsRequest is the body every buffered filesystem endpoint takes.
+type fsRequest struct {
+ Path string `json:"path"`
+ Content []byte `json:"content,omitempty"`
+ Mode uint32 `json:"mode,omitempty"`
+}
+
+// call issues one request to a bound sandbox's guest and decodes the reply into
+// out (nil to discard it).
+//
+// The single place the box lookup, the status check and the error shaping live,
+// so a new endpoint is one method rather than forty lines of the same handling.
+func (m *Manager) call(ctx context.Context, sandboxID, method, path string, body, out any) error {
+ // Every customer-facing dataplane op funnels through here — files, stats,
+ // reboot, exec sessions, PTY create — so this is where activity is
+ // recorded. Deliberately NOT in do(), which the keepalive also uses: the
+ // keepalive must never look like the customer. See idle.go.
+ m.MarkUsed(sandboxID)
+ b, ok := m.BoxFor(sandboxID)
+ if !ok {
+ return fmt.Errorf("awsvmlite: no box bound to %s", sandboxID)
+ }
+ var payload []byte
+ if body != nil {
+ var err error
+ if payload, err = json.Marshal(body); err != nil {
+ return err
+ }
+ }
+ resp, err := m.do(ctx, b, method, path, payload)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ msg, _ := io.ReadAll(io.LimitReader(resp.Body, 2048))
+ return httpError{
+ status: resp.StatusCode,
+ op: path,
+ msg: strings.TrimSpace(string(msg)),
+ }
+ }
+ // Any successful call is real inbound proxy traffic on this box, so it
+ // counts as a touch — a sandbox being actively used through files alone
+ // should not also be probed on schedule.
+ m.stampTouch(b)
+
+ if out == nil {
+ return nil
+ }
+ return json.NewDecoder(io.LimitReader(resp.Body, 64<<20)).Decode(out)
+}
+
+// httpError carries the guest's status code back to the API layer.
+//
+// The code is the payload. cmd/microvm-hooks maps the agent's gRPC codes onto
+// HTTP deliberately so that "no such file" survives the trip as a 404; throwing
+// that away here and returning a bare error would collapse it back into a 500
+// and make the SDK retry a read that can never succeed.
+type httpError struct {
+ status int
+ op string
+ msg string
+}
+
+func (e httpError) Error() string {
+ return fmt.Sprintf("awsvmlite: %s: http %d: %s", e.op, e.status, e.msg)
+}
+
+// StatusCode exposes the guest's status for the API layer's error mapping.
+func (e httpError) StatusCode() int { return e.status }
+
+// NotFound reports whether this was the guest saying the path does not exist.
+func (e httpError) NotFound() bool { return e.status == http.StatusNotFound }
+
+// ── filesystem ──────────────────────────────────────────────────────────────
+
+func (m *Manager) ReadFile(ctx context.Context, sandboxID, path string) (string, error) {
+ ctx, cancel := context.WithTimeout(ctx, fsTimeout)
+ defer cancel()
+ var out struct {
+ Content []byte `json:"content"`
+ }
+ if err := m.call(ctx, sandboxID, http.MethodPost, ocFSRead, fsRequest{Path: path}, &out); err != nil {
+ return "", err
+ }
+ return string(out.Content), nil
+}
+
+func (m *Manager) WriteFile(ctx context.Context, sandboxID, path, content string) error {
+ ctx, cancel := context.WithTimeout(ctx, fsTimeout)
+ defer cancel()
+ return m.call(ctx, sandboxID, http.MethodPost, ocFSWrite,
+ fsRequest{Path: path, Content: []byte(content)}, nil)
+}
+
+func (m *Manager) ListDir(ctx context.Context, sandboxID, path string) ([]types.EntryInfo, error) {
+ ctx, cancel := context.WithTimeout(ctx, fsTimeout)
+ defer cancel()
+ var out struct {
+ Entries []types.EntryInfo `json:"entries"`
+ }
+ if err := m.call(ctx, sandboxID, http.MethodPost, ocFSList, fsRequest{Path: path}, &out); err != nil {
+ return nil, err
+ }
+ return out.Entries, nil
+}
+
+func (m *Manager) MakeDir(ctx context.Context, sandboxID, path string) error {
+ ctx, cancel := context.WithTimeout(ctx, fsTimeout)
+ defer cancel()
+ return m.call(ctx, sandboxID, http.MethodPost, ocFSMkdir, fsRequest{Path: path}, nil)
+}
+
+func (m *Manager) Remove(ctx context.Context, sandboxID, path string) error {
+ ctx, cancel := context.WithTimeout(ctx, fsTimeout)
+ defer cancel()
+ return m.call(ctx, sandboxID, http.MethodPost, ocFSRemove, fsRequest{Path: path}, nil)
+}
+
+func (m *Manager) Exists(ctx context.Context, sandboxID, path string) (bool, error) {
+ ctx, cancel := context.WithTimeout(ctx, fsTimeout)
+ defer cancel()
+ var out struct {
+ Exists bool `json:"exists"`
+ }
+ if err := m.call(ctx, sandboxID, http.MethodPost, ocFSExists, fsRequest{Path: path}, &out); err != nil {
+ return false, err
+ }
+ return out.Exists, nil
+}
+
+func (m *Manager) Stat(ctx context.Context, sandboxID, path string) (*types.FileInfo, error) {
+ ctx, cancel := context.WithTimeout(ctx, fsTimeout)
+ defer cancel()
+ var out types.FileInfo
+ if err := m.call(ctx, sandboxID, http.MethodPost, ocFSStat, fsRequest{Path: path}, &out); err != nil {
+ return nil, err
+ }
+ return &out, nil
+}
+
+// ── streaming filesystem ────────────────────────────────────────────────────
+//
+// Neither of these buffers the file. Only trailers die on the proxy hop; a body
+// streams through it untouched, which is what makes a large transfer possible
+// on a path that cannot carry gRPC.
+
+// ReadFileStream returns an open body the caller must close, plus the size when
+// the guest reported one (-1 when it did not).
+func (m *Manager) ReadFileStream(ctx context.Context, sandboxID, path string) (io.ReadCloser, int64, error) {
+ b, ok := m.BoxFor(sandboxID)
+ if !ok {
+ return nil, 0, fmt.Errorf("awsvmlite: no box bound to %s", sandboxID)
+ }
+ // No timeout on the context: this is a download of unknown size and the
+ // caller owns how long it is willing to wait. A deadline here would cut a
+ // large but perfectly healthy transfer off mid-file.
+ resp, err := m.do(ctx, b, http.MethodGet,
+ ocFSDownload+"?path="+urlQueryEscape(path), nil)
+ if err != nil {
+ return nil, 0, err
+ }
+ if resp.StatusCode != http.StatusOK {
+ msg, _ := io.ReadAll(io.LimitReader(resp.Body, 2048))
+ resp.Body.Close()
+ return nil, 0, httpError{status: resp.StatusCode, op: ocFSDownload, msg: strings.TrimSpace(string(msg))}
+ }
+ m.stampTouch(b)
+ size := int64(-1)
+ if cl := resp.Header.Get("Content-Length"); cl != "" {
+ if n, err := strconv.ParseInt(cl, 10, 64); err == nil {
+ size = n
+ }
+ }
+ return resp.Body, size, nil
+}
+
+// WriteFileStream streams r into the guest and reports how many bytes landed.
+func (m *Manager) WriteFileStream(ctx context.Context, sandboxID, path string, mode uint32, r io.Reader) (int64, error) {
+ b, ok := m.BoxFor(sandboxID)
+ if !ok {
+ return 0, fmt.Errorf("awsvmlite: no box bound to %s", sandboxID)
+ }
+ q := ocFSUpload + "?path=" + urlQueryEscape(path)
+ if mode != 0 {
+ q += "&mode=" + strconv.FormatUint(uint64(mode), 8)
+ }
+ resp, err := m.doStream(ctx, b, http.MethodPut, q, r)
+ if err != nil {
+ return 0, err
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ msg, _ := io.ReadAll(io.LimitReader(resp.Body, 2048))
+ return 0, httpError{status: resp.StatusCode, op: ocFSUpload, msg: strings.TrimSpace(string(msg))}
+ }
+ m.stampTouch(b)
+ var out struct {
+ BytesWritten int64 `json:"bytesWritten"`
+ }
+ if err := json.NewDecoder(io.LimitReader(resp.Body, 4096)).Decode(&out); err != nil {
+ return 0, err
+ }
+ return out.BytesWritten, nil
+}
+
+// ── environment ─────────────────────────────────────────────────────────────
+
+// SetEnvs applies the sandbox's environment to everything it subsequently runs.
+//
+// ON THE CREATE PATH, and therefore the one thing in this file that has to
+// justify its latency. It costs exactly one request, and only when a create
+// actually carried envs — the caller skips it otherwise (see liteBackend.
+// Activate), so the default-shape create the benchmark measures is untouched.
+//
+// It has to happen before the create returns rather than in the background: the
+// customer's first exec can arrive the instant they have the sandbox id, and an
+// environment that arrives afterwards would apply to some of their commands and
+// not others, non-deterministically.
+func (m *Manager) SetEnvs(ctx context.Context, sandboxID string, envs map[string]string) error {
+ ctx, cancel := context.WithTimeout(ctx, 20*time.Second)
+ defer cancel()
+ return m.call(ctx, sandboxID, http.MethodPost, ocEnvs,
+ map[string]any{"envs": envs}, nil)
+}
+
+// ── monitoring ──────────────────────────────────────────────────────────────
+
+func (m *Manager) Stats(ctx context.Context, sandboxID string) (*sandbox.SandboxStats, error) {
+ ctx, cancel := context.WithTimeout(ctx, 20*time.Second)
+ defer cancel()
+ var out sandbox.SandboxStats
+ if err := m.call(ctx, sandboxID, http.MethodGet, ocStats, nil, &out); err != nil {
+ return nil, err
+ }
+ return &out, nil
+}
+
+// ── reboot ──────────────────────────────────────────────────────────────────
+
+// Reboot restarts the sandbox's workload in place.
+//
+// Not a kernel restart — there is no way to restart a MicroVM's guest kernel,
+// and the agent-path backend's answer to that was to launch a REPLACEMENT box
+// and copy the workspace across (a ~3.3s floor plus the size of the workspace,
+// losing anything installed outside /home/sandbox). This kills every process
+// the sandbox user owns and restarts the agent instead: nothing of the
+// customer's is running afterwards, no shell state or listening port survives,
+// and the disk is untouched — so it preserves strictly more than the old path
+// did, in a fraction of the time and without moving a byte.
+func (m *Manager) Reboot(ctx context.Context, sandboxID string) error {
+ ctx, cancel := context.WithTimeout(ctx, rebootTimeout)
+ defer cancel()
+ return m.call(ctx, sandboxID, http.MethodPost, ocReboot, nil, nil)
+}
+
+// ── endpoint ────────────────────────────────────────────────────────────────
+
+// PreviewTarget returns what a caller needs to reach a port inside the guest:
+// the box's HTTPS host, its proxy auth token, and the proxy port header value.
+//
+// The path prefix is the caller's to add (see ocPortPrefix in the guest). This
+// returns the pieces rather than a URL because the proxy hop needs two headers
+// that a URL cannot carry.
+func (m *Manager) PreviewTarget(sandboxID string) (host, token string, proxyPort int32, err error) {
+ b, ok := m.BoxFor(sandboxID)
+ if !ok {
+ return "", "", 0, fmt.Errorf("awsvmlite: no box bound to %s", sandboxID)
+ }
+ // Refreshed, not Box.Token: a preview URL is reached long after the box was
+ // launched, which is precisely when the launch-time token is dead.
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ return hostOnly(b.Endpoint), m.token(ctx, b), b.Port, nil
+}
+
+// doStream is do() for a request whose body is a stream of unknown length.
+//
+// Separate from do() rather than a parameter on it: do() marshals a []byte and
+// sets Content-Length from it, and the whole point here is to have neither. Go
+// sends this chunked, which the proxy forwards unchanged.
+func (m *Manager) doStream(ctx context.Context, b *Box, method, path string, body io.Reader) (*http.Response, error) {
+ host := hostOnly(b.Endpoint)
+ req, err := http.NewRequestWithContext(ctx, method, "https://"+host+path, body)
+ if err != nil {
+ return nil, err
+ }
+ req.Header.Set("X-aws-proxy-auth", m.token(ctx, b))
+ req.Header.Set("X-aws-proxy-port", strconv.FormatInt(int64(b.Port), 10))
+ req.Header.Set("Content-Type", "application/octet-stream")
+ return m.http.Do(req)
+}
+
+// urlQueryEscape escapes a path for use in a query string.
+//
+// Spelled out rather than reaching for url.Values because a path is the one
+// argument every one of these endpoints takes, and getting it wrong is silent:
+// an unescaped `&` or `#` in a filename truncates the path and the guest
+// operates on the wrong file.
+func urlQueryEscape(s string) string {
+ var b strings.Builder
+ for i := 0; i < len(s); i++ {
+ c := s[i]
+ switch {
+ case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z', c >= '0' && c <= '9',
+ c == '-', c == '_', c == '.', c == '~', c == '/':
+ b.WriteByte(c)
+ default:
+ b.WriteString(fmt.Sprintf("%%%02X", c))
+ }
+ }
+ return b.String()
+}
+
+// token returns a currently-valid proxy auth token for a box.
+//
+// NOT Box.Token, which is the token minted when the box was launched and is
+// frozen there forever. AWS caps these at 60 minutes, so a box that sits in the
+// warm set or stays bound for longer than that carries a DEAD credential — and
+// every request against it then fails with a proxy 403, permanently, because
+// nothing refreshes it and nothing evicts on 403 either.
+//
+// Found on dev by dropping the warm pool to 1: the single box sat for an hour,
+// and every operation on the sandbox that claimed it failed while freshly
+// created sandboxes passed. A deep pool hides this completely — boxes churn
+// well inside an hour — which is exactly why it survived every burst benchmark.
+// A real customer's sandbox would have stopped working after an hour.
+//
+// Client.AuthToken already caches per box and re-mints at 75% of lifetime, so
+// this is a map lookup on all but roughly one call per box per 45 minutes.
+func (m *Manager) token(ctx context.Context, b *Box) string {
+ if m.client == nil {
+ // Unit tests build a Manager with no AWS client; the launch-time value
+ // is all there is, and there is no proxy to reject it.
+ return b.Token
+ }
+ tok, err := m.client.AuthToken(ctx, b.MicrovmID)
+ if err != nil {
+ // Fall back rather than fail: a stale token might still be inside its
+ // hour, and a transient AWS error must not take out a live sandbox.
+ log.Printf("awsvmlite: refresh auth token for %s: %v (using the launch-time token)", b.MicrovmID, err)
+ return b.Token
+ }
+ return tok
+}
diff --git a/internal/awsvmlite/dataplane_test.go b/internal/awsvmlite/dataplane_test.go
new file mode 100644
index 00000000..20d98f0d
--- /dev/null
+++ b/internal/awsvmlite/dataplane_test.go
@@ -0,0 +1,454 @@
+package awsvmlite
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "strings"
+ "testing"
+
+ "github.com/opensandbox/opensandbox/pkg/types"
+)
+
+// dataplane_test.go — the wire contract with the guest.
+//
+// These operations cross a proxy that authenticates on two headers and routes
+// on a third, into a guest that answers on exact paths. Every one of those is
+// silent when wrong: a missing auth header is a 403 that looks like a dead box,
+// a wrong port header reaches nothing, and a mistyped path falls through the
+// guest's mux to the agent bridge and comes back as an unexplained 415.
+
+// rtFunc is a RoundTripper that answers without a network.
+type rtFunc func(*http.Request) (*http.Response, error)
+
+func (f rtFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
+
+// newFakeBox returns a Manager bound to one box, plus a pointer to the last
+// request its transport saw.
+func newFakeBox(t *testing.T, status int, body string) (*Manager, **http.Request) {
+ t.Helper()
+ var last *http.Request
+ m := &Manager{
+ bound: map[string]*Box{
+ "sbx-1": {MicrovmID: "mvm-1", Endpoint: "https://box.example", Token: "tok-abc", Port: 8080},
+ },
+ http: &http.Client{Transport: rtFunc(func(r *http.Request) (*http.Response, error) {
+ // Drain the body before answering so a streamed upload is fully
+ // consumed, as a real server would.
+ if r.Body != nil {
+ _, _ = io.Copy(io.Discard, r.Body)
+ }
+ last = r
+ return &http.Response{
+ StatusCode: status,
+ Body: io.NopCloser(strings.NewReader(body)),
+ Header: http.Header{},
+ }, nil
+ })},
+ }
+ return m, &last
+}
+
+// Every request must carry the proxy's auth token and target port. Without them
+// the proxy answers before the guest is ever reached.
+func TestEveryCallCarriesProxyHeaders(t *testing.T) {
+ m, last := newFakeBox(t, http.StatusOK, `{"ok":true}`)
+ if err := m.MakeDir(context.Background(), "sbx-1", "/home/sandbox/x"); err != nil {
+ t.Fatalf("mkdir: %v", err)
+ }
+ r := *last
+ if got := r.Header.Get("X-aws-proxy-auth"); got != "tok-abc" {
+ t.Errorf("auth header = %q, want the box token", got)
+ }
+ if got := r.Header.Get("X-aws-proxy-port"); got != "8080" {
+ t.Errorf("port header = %q, want 8080", got)
+ }
+ if r.URL.Path != ocFSMkdir {
+ t.Errorf("path = %q, want %q", r.URL.Path, ocFSMkdir)
+ }
+ if r.URL.Host != "box.example" {
+ t.Errorf("host = %q, want the box endpoint host", r.URL.Host)
+ }
+}
+
+// The guest returns file content as base64 bytes so binary round-trips. A
+// string field here would corrupt anything that is not valid UTF-8.
+func TestReadFileDecodesBinaryContent(t *testing.T) {
+ raw := []byte{0x00, 0xff, 0xfe, 'h', 'i'}
+ body, _ := json.Marshal(map[string]any{"content": raw})
+ m, _ := newFakeBox(t, http.StatusOK, string(body))
+
+ got, err := m.ReadFile(context.Background(), "sbx-1", "/bin/thing")
+ if err != nil {
+ t.Fatalf("read: %v", err)
+ }
+ if got != string(raw) {
+ t.Errorf("content = %q, want the exact bytes back", got)
+ }
+}
+
+// A missing file must arrive as a 404-bearing error, not a generic failure.
+// The API layer maps on this, and the SDK decides whether to retry on it.
+func TestNotFoundSurvivesAsNotFound(t *testing.T) {
+ m, _ := newFakeBox(t, http.StatusNotFound, "no such file")
+ _, err := m.ReadFile(context.Background(), "sbx-1", "/nope")
+ if err == nil {
+ t.Fatal("read of a missing file succeeded")
+ }
+ he, ok := err.(httpError)
+ if !ok {
+ t.Fatalf("error type = %T, want httpError carrying the status", err)
+ }
+ if !he.NotFound() || he.StatusCode() != http.StatusNotFound {
+ t.Errorf("status = %d, want 404", he.StatusCode())
+ }
+}
+
+// An unbound sandbox is a clean error, never a request to somebody else's box.
+func TestUnboundSandboxIsRefusedBeforeAnyRequest(t *testing.T) {
+ m, last := newFakeBox(t, http.StatusOK, `{}`)
+ if _, err := m.ReadFile(context.Background(), "sbx-unknown", "/x"); err == nil {
+ t.Fatal("read against an unbound sandbox succeeded")
+ }
+ if *last != nil {
+ t.Error("a request was sent for a sandbox this process holds no box for")
+ }
+}
+
+// Upload streams the body and puts path/mode in the query, because the body is
+// the file. Getting the mode base wrong (decimal for octal) silently changes
+// permissions.
+func TestUploadPutsPathAndOctalModeInQuery(t *testing.T) {
+ m, last := newFakeBox(t, http.StatusOK, `{"bytesWritten":5}`)
+ n, err := m.WriteFileStream(context.Background(), "sbx-1", "/home/sandbox/a b&c.txt", 0o755, bytes.NewReader([]byte("hello")))
+ if err != nil {
+ t.Fatalf("upload: %v", err)
+ }
+ if n != 5 {
+ t.Errorf("bytesWritten = %d, want 5", n)
+ }
+ q := (*last).URL.Query()
+ if q.Get("path") != "/home/sandbox/a b&c.txt" {
+ t.Errorf("path = %q — an unescaped & would truncate it and write the wrong file", q.Get("path"))
+ }
+ if q.Get("mode") != "755" {
+ t.Errorf("mode = %q, want octal 755", q.Get("mode"))
+ }
+ if (*last).Method != http.MethodPut {
+ t.Errorf("method = %s, want PUT", (*last).Method)
+ }
+}
+
+// Download hands back an open body rather than buffering, and reports the size
+// the guest declared.
+func TestDownloadStreamsWithDeclaredSize(t *testing.T) {
+ var last *http.Request
+ m := &Manager{
+ bound: map[string]*Box{"sbx-1": {Endpoint: "https://box.example", Token: "t", Port: 8080}},
+ http: &http.Client{Transport: rtFunc(func(r *http.Request) (*http.Response, error) {
+ last = r
+ h := http.Header{}
+ h.Set("Content-Length", "11")
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ Body: io.NopCloser(strings.NewReader("hello world")),
+ Header: h,
+ }, nil
+ })},
+ }
+ rc, size, err := m.ReadFileStream(context.Background(), "sbx-1", "/f")
+ if err != nil {
+ t.Fatalf("download: %v", err)
+ }
+ defer rc.Close()
+ if size != 11 {
+ t.Errorf("size = %d, want 11", size)
+ }
+ got, _ := io.ReadAll(rc)
+ if string(got) != "hello world" {
+ t.Errorf("body = %q", got)
+ }
+ if last.URL.Query().Get("path") != "/f" {
+ t.Errorf("path query = %q", last.URL.Query().Get("path"))
+ }
+}
+
+// Paths are escaped, and the separators that make a path a path are not.
+func TestPathEscapingPreservesSlashesAndEscapesTheRest(t *testing.T) {
+ cases := map[string]string{
+ "/home/sandbox/file.txt": "/home/sandbox/file.txt",
+ "/a b": "/a%20b",
+ "/a&b": "/a%26b",
+ "/a#b": "/a%23b",
+ "/a?b": "/a%3Fb",
+ "/tilde~dash-dot.": "/tilde~dash-dot.",
+ }
+ for in, want := range cases {
+ if got := urlQueryEscape(in); got != want {
+ t.Errorf("escape(%q) = %q, want %q", in, got, want)
+ }
+ }
+}
+
+// Stats unmarshals straight into the runtime-agnostic struct the API returns.
+func TestStatsMapsOntoTheSharedShape(t *testing.T) {
+ m, last := newFakeBox(t, http.StatusOK,
+ `{"cpuPercent":12.5,"memUsage":100,"memLimit":4096,"netInput":7,"netOutput":9,"pids":3}`)
+ st, err := m.Stats(context.Background(), "sbx-1")
+ if err != nil {
+ t.Fatalf("stats: %v", err)
+ }
+ if st.CPUPercent != 12.5 || st.MemUsage != 100 || st.MemLimit != 4096 || st.PIDs != 3 {
+ t.Errorf("stats = %+v, want the guest's numbers verbatim", st)
+ }
+ if (*last).URL.Path != ocStats {
+ t.Errorf("path = %q, want %q", (*last).URL.Path, ocStats)
+ }
+}
+
+// Reboot is a POST with no body and no result to decode; the point is that a
+// non-200 is still an error rather than a silently-successful reboot.
+func TestRebootReportsFailure(t *testing.T) {
+ m, _ := newFakeBox(t, http.StatusInternalServerError, "agent did not come back")
+ if err := m.Reboot(context.Background(), "sbx-1"); err == nil {
+ t.Fatal("a failed reboot reported success — the customer's view and the box would disagree")
+ }
+}
+
+func TestRebootSucceeds(t *testing.T) {
+ m, last := newFakeBox(t, http.StatusOK, `{"ok":true}`)
+ if err := m.Reboot(context.Background(), "sbx-1"); err != nil {
+ t.Fatalf("reboot: %v", err)
+ }
+ if (*last).Method != http.MethodPost || (*last).URL.Path != ocReboot {
+ t.Errorf("%s %s, want POST %s", (*last).Method, (*last).URL.Path, ocReboot)
+ }
+}
+
+// PreviewTarget hands back the three things a caller needs to reach a guest
+// port; without the token the proxy refuses, without the port it routes nowhere.
+func TestPreviewTargetReturnsTheProxyTriple(t *testing.T) {
+ m, _ := newFakeBox(t, http.StatusOK, `{}`)
+ host, token, port, err := m.PreviewTarget("sbx-1")
+ if err != nil {
+ t.Fatalf("preview target: %v", err)
+ }
+ if host != "box.example" || token != "tok-abc" || port != 8080 {
+ t.Errorf("got (%q, %q, %d), want the box's host, token and hook port", host, token, port)
+ }
+ if _, _, _, err := m.PreviewTarget("sbx-unknown"); err == nil {
+ t.Error("preview target for an unbound sandbox succeeded")
+ }
+}
+
+// ── exec sessions ───────────────────────────────────────────────────────────
+
+// A running session has no exit code, and reporting 0 for one would read as
+// "it succeeded" — the single most misleading answer this API can give.
+func TestExecSessionResultOmitsExitCodeWhileRunning(t *testing.T) {
+ m, _ := newFakeBox(t, http.StatusOK, `{"running":true,"stdout":"aGk="}`)
+ res, err := m.ExecSessionGetResult(context.Background(), "sbx-1", "sess-1")
+ if err != nil {
+ t.Fatalf("result: %v", err)
+ }
+ if !res.Running {
+ t.Error("running session reported as finished")
+ }
+ if res.ExitCode != nil {
+ t.Errorf("exitCode = %d for a running session — a caller reads 0 as success", *res.ExitCode)
+ }
+ if string(res.Stdout) != "hi" {
+ t.Errorf("stdout = %q, want the decoded bytes", res.Stdout)
+ }
+}
+
+func TestExecSessionResultCarriesExitCode(t *testing.T) {
+ m, last := newFakeBox(t, http.StatusOK, `{"running":false,"exitCode":3,"stderr":"YmFk"}`)
+ res, err := m.ExecSessionGetResult(context.Background(), "sbx-1", "sess-1")
+ if err != nil {
+ t.Fatalf("result: %v", err)
+ }
+ if res.ExitCode == nil || *res.ExitCode != 3 {
+ t.Errorf("exitCode = %v, want 3", res.ExitCode)
+ }
+ if string(res.Stderr) != "bad" {
+ t.Errorf("stderr = %q", res.Stderr)
+ }
+ // The session id travels in the query, and must be escaped: an id
+ // containing & would otherwise address a different session or none.
+ if got := (*last).URL.Query().Get("sessionId"); got != "sess-1" {
+ t.Errorf("sessionId = %q", got)
+ }
+}
+
+func TestExecSessionCreateSendsTheCommand(t *testing.T) {
+ m, last := newFakeBox(t, http.StatusOK, `{"sessionId":"sess-9"}`)
+ id, err := m.ExecSessionCreate(context.Background(), "sbx-1", ExecSessionRequest{
+ Command: "npm", Args: []string{"run", "dev"}, MaxRunAfterDisconnect: 300,
+ })
+ if err != nil {
+ t.Fatalf("create: %v", err)
+ }
+ if id != "sess-9" {
+ t.Errorf("sessionId = %q, want sess-9", id)
+ }
+ if (*last).URL.Path != ocExecCreatePath {
+ t.Errorf("path = %q, want %q", (*last).URL.Path, ocExecCreatePath)
+ }
+}
+
+// Killing and listing must refuse an unbound sandbox before any request.
+func TestExecSessionOpsRefuseUnboundSandbox(t *testing.T) {
+ m, last := newFakeBox(t, http.StatusOK, `{}`)
+ if _, err := m.ExecSessionCreate(context.Background(), "nope", ExecSessionRequest{Command: "x"}); err == nil {
+ t.Error("create against an unbound sandbox succeeded")
+ }
+ if _, err := m.ExecSessionList(context.Background(), "nope"); err == nil {
+ t.Error("list against an unbound sandbox succeeded")
+ }
+ if err := m.ExecSessionKill(context.Background(), "nope", "s", 0); err == nil {
+ t.Error("kill against an unbound sandbox succeeded")
+ }
+ if *last != nil {
+ t.Error("a request was sent for a sandbox this process holds no box for")
+ }
+}
+
+// ── secrets ─────────────────────────────────────────────────────────────────
+
+// HasSecrets is the hot-path gate. A create with nothing to seal must not send
+// the request at all — the pooled default create is what the TTI benchmark
+// measures, and it must stay at zero extra round trips.
+func TestHasSecretsGatesTheHotPath(t *testing.T) {
+ if HasSecrets(types.SandboxConfig{}) {
+ t.Error("an empty create was treated as having secrets — every pooled create would pay a round trip")
+ }
+ if HasSecrets(types.SandboxConfig{Envs: map[string]string{"A": "b"}}) {
+ t.Error("plain envs were treated as secrets — they go through SetEnvs, which does not seal")
+ }
+ if !HasSecrets(types.SandboxConfig{SecretEnvs: map[string]string{"K": "v"}}) {
+ t.Error("a secret env was not detected")
+ }
+ // An allowlist with no secrets still needs the proxy: it is an egress
+ // restriction, and skipping it would leave the sandbox unrestricted while
+ // the API reported the store applied.
+ if !HasSecrets(types.SandboxConfig{EgressAllowlist: []string{"api.stripe.com"}}) {
+ t.Error("an allowlist-only store was skipped — egress would be unrestricted")
+ }
+ if !HasSecrets(types.SandboxConfig{SecretAllowedHosts: map[string][]string{"K": {"h"}}}) {
+ t.Error("per-secret host restrictions were not detected")
+ }
+}
+
+// SetSecrets must carry the plaintext envs too: the guest merges both into ONE
+// environment, so sending them separately would overwrite the sealed values.
+func TestSetSecretsCarriesPlaintextEnvsToo(t *testing.T) {
+ // A capturing transport, because the assertion is about what was SENT.
+ var captured []byte
+ var path string
+ m := &Manager{
+ bound: map[string]*Box{"sbx-1": {Endpoint: "https://box.example", Token: "t", Port: 8080}},
+ http: &http.Client{Transport: rtFunc(func(r *http.Request) (*http.Response, error) {
+ captured, _ = io.ReadAll(r.Body)
+ path = r.URL.Path
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ Body: io.NopCloser(strings.NewReader(`{"ok":true}`)),
+ Header: http.Header{},
+ }, nil
+ })},
+ }
+
+ err := m.SetSecrets(context.Background(), "sbx-1", types.SandboxConfig{
+ Envs: map[string]string{"PUBLIC": "fine"},
+ SecretEnvs: map[string]string{"API_KEY": "sk-real"},
+ EgressAllowlist: []string{"api.stripe.com"},
+ })
+ if err != nil {
+ t.Fatalf("set secrets: %v", err)
+ }
+ if path != ocSecrets {
+ t.Fatalf("path = %q, want %q", path, ocSecrets)
+ }
+
+ var sent secretsPayload
+ if err := json.Unmarshal(captured, &sent); err != nil {
+ t.Fatalf("payload: %v", err)
+ }
+ if sent.PlaintextEnvs["PUBLIC"] != "fine" {
+ t.Error("plaintext envs were dropped — a separate SetEnvs would then clobber the sealed environment")
+ }
+ if sent.SecretEnvs["API_KEY"] != "sk-real" {
+ t.Error("the secret value did not reach the guest, which is the only place that can seal it")
+ }
+ if len(sent.Allowlist) != 1 || sent.Allowlist[0] != "api.stripe.com" {
+ t.Errorf("allowlist = %v, want it forwarded", sent.Allowlist)
+ }
+}
+
+// A miss is (false, nil), not an error: the refresh flow sweeps every sandbox
+// in an org and most will not hold the secret being rotated.
+func TestUpdateSecretMissIsNotAnError(t *testing.T) {
+ m, _ := newFakeBox(t, http.StatusOK, `{"updated":false}`)
+ ok, err := m.UpdateSecret(context.Background(), "sbx-1", "API_KEY", "new")
+ if err != nil {
+ t.Fatalf("a miss returned an error: %v", err)
+ }
+ if ok {
+ t.Error("reported updated for a miss")
+ }
+}
+
+// But an unreachable box IS an error, so a rotation that silently failed to
+// land is distinguishable from one that had nothing to do.
+func TestUpdateSecretUnreachableBoxIsAnError(t *testing.T) {
+ m, _ := newFakeBox(t, http.StatusBadGateway, "box gone")
+ if _, err := m.UpdateSecret(context.Background(), "sbx-1", "API_KEY", "new"); err == nil {
+ t.Fatal("an unreachable box reported success — a failed rotation would look like a miss")
+ }
+}
+
+// ── auth token freshness ────────────────────────────────────────────────────
+
+// The launch-time token is not a credential you can keep using.
+//
+// AWS caps proxy auth tokens at 60 minutes. Box.Token is minted once, when the
+// box is launched, so a box that sits in the warm set or stays bound for longer
+// than an hour carries a dead one — and every request against it then fails
+// with a proxy 403, permanently, because nothing refreshes and nothing evicts
+// on 403.
+//
+// A deep pool hides this completely: boxes churn well inside an hour, which is
+// why every burst benchmark passed while a customer's hour-old sandbox would
+// have been dead. Found by dropping the dev pool to a single box.
+func TestRequestsUseARefreshedTokenNotTheLaunchTimeOne(t *testing.T) {
+ var sawAuth string
+ m := &Manager{
+ bound: map[string]*Box{
+ "sbx-1": {MicrovmID: "mvm-1", Endpoint: "https://box.example", Token: "STALE-LAUNCH-TOKEN", Port: 8080},
+ },
+ http: &http.Client{Transport: rtFunc(func(r *http.Request) (*http.Response, error) {
+ sawAuth = r.Header.Get("X-aws-proxy-auth")
+ return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(`{"ok":true}`)), Header: http.Header{}}, nil
+ })},
+ }
+ // With no AWS client the refresher has nothing to ask, so it falls back to
+ // the launch-time value — which is what keeps unit tests working and is the
+ // only case where the stale token is legitimately used.
+ if err := m.MakeDir(context.Background(), "sbx-1", "/x"); err != nil {
+ t.Fatalf("mkdir: %v", err)
+ }
+ if sawAuth != "STALE-LAUNCH-TOKEN" {
+ t.Fatalf("auth header = %q; with no client configured the launch token is the only source", sawAuth)
+ }
+
+ // The property that matters: the header is sourced from token(), not read
+ // straight off the Box. If someone re-inlines b.Token this fails, because
+ // token() is the only place a refresh can ever be introduced.
+ b := m.bound["sbx-1"]
+ if got := m.token(context.Background(), b); got != b.Token {
+ t.Fatalf("token() = %q, want the fallback %q", got, b.Token)
+ }
+}
diff --git a/internal/awsvmlite/lite.go b/internal/awsvmlite/lite.go
index b7cab41a..7f224620 100644
--- a/internal/awsvmlite/lite.go
+++ b/internal/awsvmlite/lite.go
@@ -16,7 +16,7 @@
// intact (it answered 415, from inside the guest). So the tunnel is not required
// to talk to a MicroVM; it is required only to speak gRPC to one.
//
-// This backend therefore does the smallest possible thing:
+// This backend therefore does the smallest possible thing on the hot path:
//
// create pop a pre-launched box off a warm set, or launch one
// exec one HTTPS POST to /osb/run on the hook port, connection reused
@@ -27,10 +27,19 @@
// No WebSocket. No persistent channel. No keepalive ping. No re-dial. No
// Durable Object. No pool sharding. Nothing to decay.
//
-// WHAT IS GIVEN UP, deliberately and completely: streaming output, PTY
-// sessions, file transfer, and everything else osb-agent's API offers. One
-// command, buffered output, one reply. This is not a replacement for the agent
-// path — it is the floor that path should be measured against.
+// EVERYTHING ELSE — files, stats, reboot, and reaching a port the customer is
+// listening on — lives in dataplane.go and is reached the same way, one request
+// at a time, off the hot path. That was originally given up along with the
+// tunnel, on the assumption that osb-agent's API required gRPC end to end. It
+// does not: the trailer problem belongs to the PROXY HOP, and the guest can
+// speak loopback gRPC to the agent behind it. cmd/microvm-hooks translates, so
+// this backend reaches the agent's full API without carrying gRPC across the
+// proxy even once.
+//
+// What remains genuinely absent: PTY and streaming exec sessions (both want a
+// bidirectional stream, which is a WebSocket away but not built), checkpoints
+// and fork (a MicroVM image is produced by an API, not captured from a running
+// box), and per-sandbox resource limits (sizing belongs to the image).
package awsvmlite
import (
@@ -47,6 +56,8 @@ import (
"time"
"github.com/opensandbox/opensandbox/internal/awsvm"
+ "github.com/opensandbox/opensandbox/internal/sandbox"
+ "github.com/opensandbox/opensandbox/internal/storage"
)
const (
@@ -71,6 +82,12 @@ const (
// is a thing that can be set wrong, and the point of this package is that there
// is almost nothing to get wrong.
type Config struct {
+ // SuspendedCap bounds how many sandboxes may sit hibernated at once. 0
+ // takes the default. See hibernate.go for the quota arithmetic behind it —
+ // a parked box holds a slot the warm pool cannot have and cannot be
+ // reclaimed, so this is what stops hibernation eating the pool.
+ SuspendedCap int
+
// WarmTarget is how many pre-launched boxes to hold. 0 disables the warm
// set, and every create cold-launches (~3s, per AWS's own published
// benchmark) instead of ~0.
@@ -143,7 +160,19 @@ type Box struct {
launchedAt time.Time
boundAt time.Time
- lastTouch time.Time
+ // lastTouch is when the KEEPALIVE last poked this box. It exists to stop
+ // AWS suspending idle stock and says nothing about the customer.
+ lastTouch time.Time
+ // lastUsed is when the CUSTOMER last did something. Deliberately separate
+ // from lastTouch: the keepalive touches every box on a timer, so an idle
+ // policy driven by lastTouch would find every sandbox permanently busy and
+ // never expire anything. See MarkUsed.
+ lastUsed time.Time
+ // idleTimeout is how long this sandbox may sit unused before it is parked.
+ // Zero means no timeout — the sandbox runs until killed or until the
+ // provider's own hard cap ends it. See SetIdleTimeout for why a value
+ // beyond that cap is refused rather than stored.
+ idleTimeout time.Duration
}
// Meta is the part of a sandbox's config this backend still has to remember
@@ -188,6 +217,38 @@ type Manager struct {
mu sync.Mutex
warm []*Box
bound map[string]*Box // sandboxID → box
+ // store is where checkpoint and template archives live. Set once at
+ // construction; nil on a cell with no blob storage configured, which makes
+ // checkpoints and templates unavailable rather than crashing.
+ store *storage.CheckpointStore
+
+ // term paces destroys against the 10/s TerminateMicrovm quota. See the
+ // comment on terminate() for what calling the API directly cost.
+ term *awsvm.Terminator
+
+ // lifecycleObs receives the usage-metering boundaries — destroy, hibernate,
+ // wake. nil until the control plane wires its ticker in, and nil in tests,
+ // so every call site must guard. See SetLifecycleObserver.
+ lifecycleObs sandbox.LifecycleObserver
+
+ // lastBox remembers which host a sandbox held, for a short while after the
+ // binding is dropped. It exists for exactly one reader: the event
+ // publisher, which stamps each usage tick with a worker_id resolved from
+ // the live binding.
+ //
+ // The closing tick is emitted DURING Destroy and drained a beat later, by
+ // which time the binding is gone — so the publisher fell back to a generic
+ // id, and events-ingest dropped the tick because it disagreed with the
+ // sandbox's row. The last slice of every destroyed sandbox went unbilled
+ // for that reason alone, even once the terminal-status guard was fixed.
+ lastBox map[string]lastBoxEntry
+
+ // suspended is the set of sandboxes parked by Hibernate, and the time each
+ // was parked. Kept here rather than on the Box because two unrelated loops
+ // have to consult it and both fail silently without it: billing (a
+ // suspended box still reports Alive() to AWS) and touchIdle (a probe
+ // auto-resumes whatever it touches). See hibernate.go.
+ suspended map[string]time.Time
// lastStateLog rate-limits the periodic state line — see logState.
lastStateLog time.Time
// inflight counts launches in progress, so the filler targets committed
@@ -201,6 +262,7 @@ func New(client *awsvm.Client, cfg Config) *Manager {
return &Manager{
client: client,
cfg: cfg,
+ term: awsvm.NewTerminator(client),
bound: map[string]*Box{},
http: &http.Client{
Timeout: cfg.ExecTimeout,
@@ -244,11 +306,11 @@ func (m *Manager) Run(ctx context.Context) {
}
touch := time.NewTicker(touchTick)
defer touch.Stop()
-
for {
select {
case <-ctx.Done():
return
+
case <-launch.C:
m.mu.Lock()
committed := len(m.warm) + m.inflight
@@ -290,6 +352,25 @@ func (m *Manager) Run(ctx context.Context) {
// the agent path made the first exec pay for the login shell too. It does not —
// it pre-pays it at manufacture, exactly as this now does.
func (m *Manager) launchOne(ctx context.Context) error {
+ b, err := m.launchBox(ctx, "")
+ if err != nil {
+ return err
+ }
+ m.mu.Lock()
+ m.warm = append(m.warm, b)
+ depth := len(m.warm)
+ m.mu.Unlock()
+ log.Printf("awsvmlite: warm +1 %s (depth=%d/%d)", b.MicrovmID, depth, m.cfg.WarmTarget)
+ return nil
+}
+
+// launchBox manufactures one box and returns it, warmed but unowned.
+//
+// image selects the size tier; "" is the default (pooled) image. Split out of
+// launchOne so an off-tier create can reuse every step of it — the wait for
+// RUNNING, the auth token, the warm shell — without touching the warm set,
+// which holds default-size boxes only.
+func (m *Manager) launchBox(ctx context.Context, image string) (*Box, error) {
m.mu.Lock()
m.inflight++
m.mu.Unlock()
@@ -302,9 +383,9 @@ func (m *Manager) launchOne(ctx context.Context) error {
runCtx, cancel := context.WithTimeout(ctx, 2*time.Minute)
defer cancel()
- box, err := m.client.Run(runCtx, "")
+ box, err := m.client.RunImage(runCtx, "", image)
if err != nil {
- return err
+ return nil, err
}
// Do not hand out a box before Lambda says RUNNING: the proxy answers 502
// for a VM that is still restoring, and absorbing that wait is the whole
@@ -312,12 +393,12 @@ func (m *Manager) launchOne(ctx context.Context) error {
ready, err := m.client.WaitRunning(runCtx, box.ID, m.cfg.ReadyTimeout)
if err != nil {
go m.terminate(box.ID)
- return err
+ return nil, err
}
token, err := m.client.AuthToken(runCtx, ready.ID)
if err != nil {
go m.terminate(ready.ID)
- return err
+ return nil, err
}
b := &Box{
@@ -344,12 +425,7 @@ func (m *Manager) launchOne(ctx context.Context) error {
// starts its life already touched rather than immediately due.
b.lastTouch = time.Now()
}
- m.mu.Lock()
- m.warm = append(m.warm, b)
- depth := len(m.warm)
- m.mu.Unlock()
- log.Printf("awsvmlite: warm +1 %s (depth=%d/%d)", b.MicrovmID, depth, m.cfg.WarmTarget)
- return nil
+ return b, nil
}
// Claim binds a warm box to a sandbox id, or launches one if the set is empty.
@@ -357,7 +433,22 @@ func (m *Manager) launchOne(ctx context.Context) error {
// Returns the box and whether it came from the warm set — the caller wants that
// in its timing, because the two differ by the entire cold-launch cost.
func (m *Manager) Claim(ctx context.Context, sandboxID string, meta Meta) (*Box, bool, error) {
+ // The size the customer ASKED for, before delivered() rewrites it to what
+ // the image provides. That rewrite is what makes metering truthful, and it
+ // is also what would hide an off-tier request from the check below.
+ requested := meta.MemoryMB
meta = m.delivered(meta)
+
+ // Only the default size is pooled. Another tier is a different IMAGE — the
+ // memory of a MicroVM is a property of the image it launched from, not a
+ // knob — so it cannot come off the warm set and has to cold-launch (~3s).
+ // That is the deliberate trade: one deep pool for the common size beats N
+ // shallow pools that all miss.
+ if m.client != nil && !m.client.Config().IsDefaultTier(requested) {
+ b, err := m.claimOffTier(ctx, sandboxID, requested, meta)
+ return b, false, err
+ }
+
m.mu.Lock()
if b := m.popLocked(sandboxID, meta); b != nil {
m.mu.Unlock()
@@ -378,6 +469,34 @@ func (m *Manager) Claim(ctx context.Context, sandboxID string, meta Meta) (*Box,
return nil, false, fmt.Errorf("awsvmlite: no box available for %s", sandboxID)
}
+// claimOffTier cold-launches a box of a non-default size and binds it.
+//
+// Refuses rather than substituting when the tier is not offered. A silent
+// downgrade would bill a customer for the size they asked for and hand them a
+// smaller box, which is the one failure worth a hard error here.
+func (m *Manager) claimOffTier(ctx context.Context, sandboxID string, requestedMB int, meta Meta) (*Box, error) {
+ image, deliveredMB, ok := m.client.Config().ImageForMemory(requestedMB)
+ if !ok {
+ return nil, fmt.Errorf("awsvmlite: no image offers %d MB", requestedMB)
+ }
+ start := time.Now()
+ b, err := m.launchBox(ctx, image)
+ if err != nil {
+ return nil, fmt.Errorf("awsvmlite: cold launch %d MB for %s: %w", requestedMB, sandboxID, err)
+ }
+ // Metered at what the tier image actually delivers, same rule as the
+ // default path.
+ meta.MemoryMB = deliveredMB
+ b.Meta = meta
+ b.boundAt = time.Now()
+ m.mu.Lock()
+ m.bound[sandboxID] = b
+ m.mu.Unlock()
+ log.Printf("awsvmlite: OFF-TIER CREATE %s -> %s (%d MB) in %s",
+ sandboxID, b.MicrovmID, deliveredMB, time.Since(start).Round(time.Millisecond))
+ return b, nil
+}
+
// popLocked moves one box from the warm set to a sandbox. Caller holds m.mu.
func (m *Manager) popLocked(sandboxID string, meta Meta) *Box {
n := len(m.warm)
@@ -400,7 +519,7 @@ func (m *Manager) popLocked(sandboxID string, meta Meta) *Box {
// reads. Billing a 4 GB box as the 16 GB that was asked for is a silent
// overcharge, and billing it as 0 is a silent free ride.
func (m *Manager) delivered(meta Meta) Meta {
- // Nil-safe on the client, matching awsvm.Manager.config(): this is pure
+ // Nil-safe on the client: this is pure
// bookkeeping and is reached from tests that never talk to AWS, so a missing
// client should degrade to defaults rather than panic on the claim path.
if m != nil && m.client != nil {
@@ -509,6 +628,21 @@ func (m *Manager) Alive(ctx context.Context, sandboxID string) (bool, error) {
}
// BoxFor returns the box bound to a sandbox.
+// DeadlineFor reports when the provider will destroy the host behind a sandbox,
+// or the zero time if this process cannot know.
+//
+// Zero is returned rather than a guess for two distinct reasons, and both end
+// up written to a database row that readers treat as terminal once passed:
+// the sandbox may not be bound here, or the host's launch time may be unknown.
+// Guessing in either case expires a live customer's sandbox.
+func (m *Manager) DeadlineFor(sandboxID string) time.Time {
+ b, ok := m.BoxFor(sandboxID)
+ if !ok || m == nil || m.client == nil {
+ return time.Time{}
+ }
+ return m.client.Config().Deadline(b.launchedAt)
+}
+
func (m *Manager) BoxFor(sandboxID string) (*Box, bool) {
m.mu.Lock()
b, ok := m.bound[sandboxID]
@@ -528,6 +662,10 @@ func (m *Manager) BoxFor(sandboxID string) (*Box, bool) {
// This is the whole data plane. One request, one response, over a connection the
// transport above almost always already holds.
func (m *Manager) Exec(ctx context.Context, sandboxID string, req RunRequest) (*RunResult, error) {
+ // Exec reaches the box directly rather than through call(), so it stamps
+ // activity itself. Missing it here would mean a sandbox doing nothing but
+ // running commands looked idle. See idle.go.
+ m.MarkUsed(sandboxID)
b, ok := m.BoxFor(sandboxID)
if !ok {
return nil, fmt.Errorf("awsvmlite: no box bound to %s", sandboxID)
@@ -623,32 +761,136 @@ func (m *Manager) DrainWarm(ctx context.Context) int {
// re-adopts them on the way back up.
m.mu.Unlock()
- var wg sync.WaitGroup
- sem := make(chan struct{}, 16)
+ // ENQUEUED, NOT FANNED OUT. This used to launch 16 concurrent terminates
+ // against a 10/s quota, log whatever was throttled, and then return
+ // len(warm) as though all of them had died. On a full pool that is most of
+ // a pool leaked on every restart — still billing, still holding quota,
+ // while the log line said it released them all.
+ //
+ // The queue drains at the quota and retries throttles, so a drain now
+ // records the intent for every box and the worker sees it through. It
+ // deliberately does not block on completion: AWS terminate is asynchronous
+ // anyway, and a shutdown path that waited would delay the restart it is
+ // part of.
for _, b := range warm {
- wg.Add(1)
- go func(b *Box) {
- defer wg.Done()
- sem <- struct{}{}
- defer func() { <-sem }()
- if err := m.client.Terminate(ctx, b.MicrovmID); err != nil {
- log.Printf("awsvmlite: drain terminate %s: %v", b.MicrovmID, err)
+ m.terminate(b.MicrovmID)
+ }
+
+ // AND WAIT FOR THE QUEUE TO DRAIN. This is the shutdown path: enqueueing and
+ // returning would let the process exit with the backlog still in memory,
+ // which loses every box that had not yet been called — strictly worse than
+ // the unpaced version this replaced, because at least that one made the
+ // calls before dying.
+ //
+ // Bounded by the caller's context (Close gives it 30s). Whatever is still
+ // queued when that expires is left to the orphan sweep, which is the same
+ // layering the agent path uses: the queue makes leaks rare, the sweep makes
+ // them recoverable.
+ if m.term != nil {
+ for m.term.Depth() > 0 {
+ select {
+ case <-ctx.Done():
+ log.Printf("awsvmlite: drain deadline reached with %d terminate(s) still queued — "+
+ "the orphan sweep will reclaim them", m.term.Depth())
+ return len(warm)
+ case <-time.After(100 * time.Millisecond):
}
- }(b)
+ }
}
- wg.Wait()
return len(warm)
}
// Destroy terminates a sandbox's box and forgets the binding.
+// SetLifecycleObserver registers the usage-metering hooks, mirroring what the
+// QEMU manager does with its own.
+//
+// It lives HERE, on the manager, rather than at the API layer that owns the
+// ticker, because this is where a box actually dies. A sandbox is destroyed by
+// the customer's DELETE, by the idle sweep, by a drain at shutdown, and by the
+// reconciler — wiring the hook into any one caller bills some of those and
+// silently misses the rest, which is exactly the bug this closes.
+func (m *Manager) SetLifecycleObserver(obs sandbox.LifecycleObserver) {
+ if m == nil {
+ return
+ }
+ m.mu.Lock()
+ m.lifecycleObs = obs
+ m.mu.Unlock()
+}
+
+// lastBoxRetention bounds how long a destroyed sandbox's host id is
+// remembered. Only the closing usage tick reads it, and that is drained within
+// seconds, so this is generous — sized to survive a slow publisher rather than
+// to be a cache.
+const lastBoxRetention = 10 * time.Minute
+
+type lastBoxEntry struct {
+ microvmID string
+ at time.Time
+}
+
+// WorkerIDFor resolves the host a sandbox is on, or was on very recently.
+//
+// The recency half is what lets the closing usage tick be attributed. Callers
+// that need to ROUTE must use BoxFor instead — a destroyed sandbox must never
+// look reachable.
+func (m *Manager) WorkerIDFor(sandboxID string) (string, bool) {
+ if m == nil {
+ return "", false
+ }
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if b, ok := m.bound[sandboxID]; ok {
+ return b.MicrovmID, true
+ }
+ if e, ok := m.lastBox[sandboxID]; ok && time.Since(e.at) < lastBoxRetention {
+ return e.microvmID, true
+ }
+ return "", false
+}
+
func (m *Manager) Destroy(ctx context.Context, sandboxID string) error {
m.mu.Lock()
b, ok := m.bound[sandboxID]
delete(m.bound, sandboxID)
+ if ok {
+ if m.lastBox == nil {
+ m.lastBox = map[string]lastBoxEntry{}
+ }
+ m.lastBox[sandboxID] = lastBoxEntry{microvmID: b.MicrovmID, at: time.Now()}
+ // Prune here rather than on a timer: destroys are the only thing that
+ // grows this map, so they are also the only place it can leak.
+ for id, e := range m.lastBox {
+ if time.Since(e.at) >= lastBoxRetention {
+ delete(m.lastBox, id)
+ }
+ }
+ }
+ obs := m.lifecycleObs
m.mu.Unlock()
if !ok {
+ // Not an error — a destroy for something already gone is idempotent —
+ // but it IS the shape of a silent non-billing, so say it. If a caller
+ // unbinds before calling here, every sandbox it destroys is free.
+ log.Printf("awsvmlite: destroy %s: no binding held — nothing to bill or terminate", sandboxID)
return nil
}
+ // Bill the slice since the last sample before the box goes. The usage
+ // ticker samples every 20s and prices what it sees, so a sandbox that lived
+ // and died between two samples was never seen and billed nothing at all.
+ // Short-lived sandboxes are the normal shape of traffic here.
+ //
+ // Delivered size and bind time, both read from the box while it still
+ // exists — after the Terminate there is nothing left to price the slice at.
+ if obs == nil {
+ // Loud because it is invisible otherwise: the sandbox is destroyed
+ // correctly and simply never charged for.
+ log.Printf("awsvmlite: destroy %s: NO lifecycle observer — final usage slice NOT billed", sandboxID)
+ } else {
+ obs.OnSandboxDestroy(sandboxID, b.Meta.MemoryMB, b.Meta.CPUCount, b.boundAt)
+ log.Printf("awsvmlite: destroy %s: billed final slice (%dMB/%dcpu since %s)",
+ sandboxID, b.Meta.MemoryMB, b.Meta.CPUCount, b.boundAt.Format(time.RFC3339))
+ }
return m.client.Terminate(ctx, b.MicrovmID)
}
@@ -667,7 +909,7 @@ func (m *Manager) do(ctx context.Context, b *Box, method, path string, body []by
if err != nil {
return nil, err
}
- req.Header.Set("X-aws-proxy-auth", b.Token)
+ req.Header.Set("X-aws-proxy-auth", m.token(ctx, b))
req.Header.Set("X-aws-proxy-port", fmt.Sprintf("%d", b.Port))
if body != nil {
req.Header.Set("Content-Type", "application/json")
@@ -705,7 +947,14 @@ func (m *Manager) touchIdle(ctx context.Context) {
due = append(due, b)
}
}
- for _, b := range m.bound {
+ for id, b := range m.bound {
+ // NEVER touch a parked sandbox. Lambda auto-resumes a suspended box on
+ // any inbound request, so probing one would wake it within a tick of
+ // being hibernated — the customer would be billed for a sandbox they
+ // explicitly parked, and nothing in the logs would say why.
+ if _, parked := m.suspended[id]; parked {
+ continue
+ }
if b.lastTouch.IsZero() || now.Sub(b.lastTouch) >= m.cfg.TouchInterval {
due = append(due, b)
}
@@ -833,7 +1082,23 @@ func (m *Manager) evictDead(ctx context.Context, suspect []*Box) {
}
}
+// terminate destroys a box, PACED.
+//
+// TerminateMicrovm is quota'd at 10/s and a throttled terminate is the worst
+// failure available: it returns an error AND leaves the box running, so it
+// bills and holds regional memory quota until the 8h cap. The agent path
+// learned this the hard way — internal/awsvm/terminator.go records a delete of
+// 112 sandboxes returning 11 × HTTP 500, each one a leaked box — and this
+// backend was calling the API directly, logging the failure, and moving on.
+//
+// The quota is per account and region, so both backends share one. Enqueueing
+// rather than calling is what keeps them from racing it.
func (m *Manager) terminate(id string) {
+ if m.term != nil && m.term.Enqueue(id) {
+ return
+ }
+ // Queue full (or no queue, in tests): better a direct call than losing the
+ // box entirely.
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := m.client.Terminate(ctx, id); err != nil {
@@ -898,3 +1163,46 @@ func (m *Manager) dropWarmLocked(dead map[string]struct{}) int {
m.warm = kept
return evicted
}
+
+// CloseTerminator stops the paced destroy worker. Call it AFTER DrainWarm, or
+// the queue is torn down with the drain still in it.
+func (m *Manager) CloseTerminator() {
+ if m.term != nil {
+ m.term.Close()
+ }
+}
+
+// LiveMicrovmIDs returns the ids of every box AWS still considers alive.
+//
+// ONE call for the whole fleet, deliberately. The reconciler needs a liveness
+// answer for every sandbox it holds, and asking per sandbox is a GetMicrovm per
+// bound box per tick — which at a few hundred sandboxes is a rate-limit problem
+// invented to solve a bookkeeping one.
+//
+// An error is returned rather than an empty set, because the two mean opposite
+// things: "nothing is alive" would tell the caller to drop every binding it
+// has. See the caller — it skips the sweep entirely when this fails.
+func (m *Manager) LiveMicrovmIDs(ctx context.Context) (map[string]struct{}, error) {
+ if m == nil || m.client == nil {
+ // An error, not an empty set — see the note above. Reached in tests and
+ // on a cell whose client failed to build.
+ return nil, fmt.Errorf("awsvmlite: no AWS client configured")
+ }
+ boxes, err := m.client.List(ctx)
+ if err != nil {
+ return nil, err
+ }
+ live := make(map[string]struct{}, len(boxes))
+ for _, b := range boxes {
+ if b.Alive() {
+ live[b.ID] = struct{}{}
+ }
+ }
+ return live, nil
+}
+
+// SetCheckpointStore attaches the blob store used by checkpoints and template
+// restores. Call before the manager serves traffic.
+func (m *Manager) SetCheckpointStore(store *storage.CheckpointStore) {
+ m.store = store
+}
diff --git a/internal/awsvmlite/lite_test.go b/internal/awsvmlite/lite_test.go
index cc719f69..dc488bd6 100644
--- a/internal/awsvmlite/lite_test.go
+++ b/internal/awsvmlite/lite_test.go
@@ -1,6 +1,8 @@
package awsvmlite
import (
+ "context"
+ "github.com/opensandbox/opensandbox/internal/awsvm"
"testing"
"time"
)
@@ -126,3 +128,86 @@ func TestDropWarmLockedIsANoOpWhenNothingIsDead(t *testing.T) {
t.Fatalf("warm len %d, want 2", len(m.warm))
}
}
+
+// ── size tiers ──────────────────────────────────────────────────────────────
+//
+// Only the default size is pooled. Another tier is a different IMAGE, because
+// a MicroVM's memory is a property of the image it launched from — so an
+// off-tier create must cold-launch rather than pop warm stock, and a tier with
+// no image must be refused rather than quietly served at the default size.
+
+func TestOffTierClaimNeverTakesWarmStock(t *testing.T) {
+ cfg := awsvm.Config{
+ ImageIdentifier: "arn:default",
+ DefaultMemoryMB: 4096,
+ SizeImages: map[int]string{8192: "arn:8192"},
+ }
+ // The default tier, and a request naming the size it would get anyway, both
+ // belong on the pooled path.
+ for _, mb := range []int{0, 4096} {
+ if !cfg.IsDefaultTier(mb) {
+ t.Errorf("memory %d treated as off-tier — it would cold-launch instead of claiming warm stock", mb)
+ }
+ }
+ if cfg.IsDefaultTier(8192) {
+ t.Error("8192 treated as the default tier — it would be served from a 4096 MB warm box")
+ }
+}
+
+func TestUnofferedTierIsRefusedNotDowngraded(t *testing.T) {
+ cfg := awsvm.Config{
+ ImageIdentifier: "arn:default",
+ DefaultMemoryMB: 4096,
+ SizeImages: map[int]string{8192: "arn:8192"},
+ }
+ if _, _, ok := cfg.ImageForMemory(16384); ok {
+ t.Error("an unpublished tier resolved to an image — the customer would be billed for 16 GB and handed 4 GB")
+ }
+ image, delivered, ok := cfg.ImageForMemory(8192)
+ if !ok || image != "arn:8192" || delivered != 8192 {
+ t.Errorf("published tier resolved to (%q, %d, %v), want the 8192 image", image, delivered, ok)
+ }
+}
+
+// ── stale binding eviction ──────────────────────────────────────────────────
+
+// The bug this pins: a sandbox that is BOTH held in memory AND has a database
+// row was never liveness-checked. The reconciler's adopt loop skipped it
+// because it was held; the forget loop skipped it because a row existed. So
+// when AWS reaped the box at the 8h cap the binding survived forever.
+//
+// Measured on prod: bound=15 against exactly one live box. That count is what
+// Capacity() publishes as the cell's running total, so it is not cosmetic —
+// the edge routes on it.
+//
+// The reconciler lives in internal/api, so what is pinned here is the property
+// it depends on: a liveness lookup that distinguishes "gone" from "unknown".
+func TestLiveMicrovmIDsDistinguishesGoneFromUnknown(t *testing.T) {
+ // A nil client is the stand-in for "the lookup could not be made". The
+ // reconciler must treat that as unknown and drop nothing — returning an
+ // empty set instead would tell it every sandbox on the cell is dead.
+ m := &Manager{bound: map[string]*Box{}}
+ _, err := m.LiveMicrovmIDs(context.Background())
+ if err == nil {
+ t.Fatal("a failed fleet lookup returned no error — the reconciler would read it as 'nothing is alive' and close out every live sandbox")
+ }
+}
+
+// Forget must actually drop the binding, since that is what shrinks the count
+// Capacity() reports.
+func TestForgetDropsTheBinding(t *testing.T) {
+ m := &Manager{bound: map[string]*Box{
+ "sbx-live": {MicrovmID: "mvm-live"},
+ "sbx-dead": {MicrovmID: "mvm-dead"},
+ }}
+ if got := len(m.Bound()); got != 2 {
+ t.Fatalf("Bound() = %d, want 2", got)
+ }
+ m.Forget("sbx-dead")
+ if got := len(m.Bound()); got != 1 {
+ t.Errorf("Bound() = %d after Forget, want 1 — a stale binding inflates the cell's running count", got)
+ }
+ if _, ok := m.Bindings()["sbx-dead"]; ok {
+ t.Error("Bindings() still reports the forgotten sandbox")
+ }
+}
diff --git a/internal/awsvmlite/sandbox_manager.go b/internal/awsvmlite/sandbox_manager.go
index 614426ab..75060e1a 100644
--- a/internal/awsvmlite/sandbox_manager.go
+++ b/internal/awsvmlite/sandbox_manager.go
@@ -21,19 +21,38 @@ import (
// site. That is precisely the shape internal/api/backend.go was introduced to
// remove, and every one of the bugs it removed failed silently.
//
-// So this type implements ALL of it, and says no to most of it. The
-// unimplemented half returns awsvm.ErrUnsupported, which the API layer already
-// maps to 501 Not Implemented — "this runtime will never do that", as distinct
-// from a 500 that invites a retry. That is the truthful answer here: without a
-// gRPC tunnel there is no file transfer, no PTY, no streaming, and no
-// checkpoint. See the package doc for why that trade was made deliberately.
+// So this type implements ALL of it. Most of it is served — exec, files, stats,
+// reboot — by the guest front door in dataplane.go. What is left returns
+// awsvm.ErrUnsupported, which the API layer maps to 501 Not Implemented: "this
+// runtime will never do that", as distinct from a 500 that invites a retry.
+//
+// Still refused, and why: PTY and streaming exec sessions need a bidirectional
+// stream this path has not built; checkpoint and fork have no counterpart in
+// the service, since a MicroVM image is produced through an API rather than
+// captured from a running box; resource limits have no knob, because sizing is
+// a property of the image.
type SandboxManager struct {
m *Manager
+ // store is where checkpoint archives live. RestoreFromCheckpoint is handed
+ // only a checkpoint id — unlike CreateCheckpoint, which receives the store
+ // per call — so the adapter has to hold one.
+ store *storage.CheckpointStore
}
// NewSandboxManager wraps a Manager for the control plane's dispatch seam.
func NewSandboxManager(m *Manager) *SandboxManager { return &SandboxManager{m: m} }
+// WithCheckpointStore attaches the blob store used by RestoreFromCheckpoint.
+func (s *SandboxManager) WithCheckpointStore(store *storage.CheckpointStore) *SandboxManager {
+ s.store = store
+ // The Manager needs it too: the create path restores a template archive
+ // through the Manager directly, with no adapter involved.
+ if s.m != nil {
+ s.m.SetCheckpointStore(store)
+ }
+ return s
+}
+
// Compile-time proof the adapter is complete. Without it a change to
// sandbox.Manager would surface as a registration failure at startup rather
// than here.
@@ -66,8 +85,16 @@ func (s *SandboxManager) Get(ctx context.Context, id string) (*types.Sandbox, er
if err != nil {
return nil, err
}
+ // Parked first, because the provider disagrees: Box.Alive() counts a
+ // SUSPENDED microvm as alive — for its purposes the host still exists — so
+ // asking only that question reports a hibernated sandbox as `running`. The
+ // customer then sees a live sandbox that is actually asleep, and it keeps
+ // counting against their concurrency limit.
status := types.SandboxStatusRunning
- if !box.Alive() {
+ switch {
+ case s.m.IsHibernated(id):
+ status = types.SandboxStatusHibernated
+ case !box.Alive():
status = types.SandboxStatusStopped
}
return &types.Sandbox{
@@ -75,8 +102,15 @@ func (s *SandboxManager) Get(ctx context.Context, id string) (*types.Sandbox, er
Template: b.Meta.Template,
Status: status,
StartedAt: b.boundAt,
- CpuCount: b.Meta.CPUCount,
- MemoryMB: b.Meta.MemoryMB,
+ // When the provider destroys this host, whatever anyone does. Surfaced
+ // because it is the honest answer to "how long do I have": the cap
+ // counts from LAUNCH, so a sandbox claimed off the warm set already has
+ // less than a full window, and a customer who cannot see it only finds
+ // out when the sandbox disappears. Zero when it cannot be determined —
+ // never a guess, which would read as a promise. See awsvm.Config.Deadline.
+ EndAt: s.m.DeadlineFor(id),
+ CpuCount: b.Meta.CPUCount,
+ MemoryMB: b.Meta.MemoryMB,
}, nil
}
@@ -88,11 +122,18 @@ func (s *SandboxManager) List(context.Context) ([]types.Sandbox, error) {
bound := s.m.Bound()
out := make([]types.Sandbox, 0, len(bound))
for id, b := range bound {
+ // Same reasoning as Get: a parked sandbox is not running, and listing it
+ // as such is what a customer's dashboard would show.
+ status := types.SandboxStatusRunning
+ if s.m.IsHibernated(id) {
+ status = types.SandboxStatusHibernated
+ }
out = append(out, types.Sandbox{
ID: id,
Template: b.Meta.Template,
- Status: types.SandboxStatusRunning,
+ Status: status,
StartedAt: b.boundAt,
+ EndAt: s.m.DeadlineFor(id),
CpuCount: b.Meta.CPUCount,
MemoryMB: b.Meta.MemoryMB,
})
@@ -109,6 +150,15 @@ func (s *SandboxManager) Count(context.Context) (int, error) {
// prevent. An error is reported as not-alive: skipping a tick costs a fraction
// of a cent, and billing a sandbox that does not exist costs trust.
func (s *SandboxManager) IsSandboxAlive(ctx context.Context, id string) (bool, error) {
+ // A hibernated sandbox is not alive FOR BILLING, which is the only question
+ // this method is asked. AWS disagrees — Box.Alive() counts SUSPENDED as
+ // alive, because for AWS's purposes the microvm still exists — so without
+ // this check a customer who parked a sandbox would go on being metered at
+ // the full rate for it, indefinitely, while every status the product shows
+ // them says hibernated.
+ if s.m.IsHibernated(id) {
+ return false, nil
+ }
alive, err := s.m.Alive(ctx, id)
if err != nil {
return false, nil
@@ -145,44 +195,46 @@ func (s *SandboxManager) Exec(ctx context.Context, sandboxID string, cfg types.P
// ── Filesystem ──────────────────────────────────────────────────────────────
//
-// All refused. The agent's file RPCs are gRPC, and gRPC is the one thing this
-// path deliberately cannot speak. A customer gets 501 rather than a hang or a
-// half-written file.
-
-func (s *SandboxManager) ReadFile(context.Context, string, string) (string, error) {
- return "", unsupported("read file")
+// Served, not refused. These were 501 for as long as this backend had no way to
+// carry gRPC to the agent — but the obstacle was always the PROXY HOP stripping
+// HTTP/2 trailers, never the agent. The guest now translates: plain JSON across
+// the proxy, loopback gRPC to the agent behind it. See internal/awsvmlite's
+// dataplane.go and cmd/microvm-hooks/oc.go.
+
+func (s *SandboxManager) ReadFile(ctx context.Context, sandboxID, path string) (string, error) {
+ return s.m.ReadFile(ctx, sandboxID, path)
}
-func (s *SandboxManager) WriteFile(context.Context, string, string, string) error {
- return unsupported("write file")
+func (s *SandboxManager) WriteFile(ctx context.Context, sandboxID, path, content string) error {
+ return s.m.WriteFile(ctx, sandboxID, path, content)
}
-func (s *SandboxManager) ReadFileStream(context.Context, string, string) (io.ReadCloser, int64, error) {
- return nil, 0, unsupported("read file stream")
+func (s *SandboxManager) ReadFileStream(ctx context.Context, sandboxID, path string) (io.ReadCloser, int64, error) {
+ return s.m.ReadFileStream(ctx, sandboxID, path)
}
-func (s *SandboxManager) WriteFileStream(context.Context, string, string, uint32, io.Reader) (int64, error) {
- return 0, unsupported("write file stream")
+func (s *SandboxManager) WriteFileStream(ctx context.Context, sandboxID, path string, mode uint32, r io.Reader) (int64, error) {
+ return s.m.WriteFileStream(ctx, sandboxID, path, mode, r)
}
-func (s *SandboxManager) ListDir(context.Context, string, string) ([]types.EntryInfo, error) {
- return nil, unsupported("list dir")
+func (s *SandboxManager) ListDir(ctx context.Context, sandboxID, path string) ([]types.EntryInfo, error) {
+ return s.m.ListDir(ctx, sandboxID, path)
}
-func (s *SandboxManager) MakeDir(context.Context, string, string) error {
- return unsupported("make dir")
+func (s *SandboxManager) MakeDir(ctx context.Context, sandboxID, path string) error {
+ return s.m.MakeDir(ctx, sandboxID, path)
}
-func (s *SandboxManager) Remove(context.Context, string, string) error {
- return unsupported("remove")
+func (s *SandboxManager) Remove(ctx context.Context, sandboxID, path string) error {
+ return s.m.Remove(ctx, sandboxID, path)
}
-func (s *SandboxManager) Exists(context.Context, string, string) (bool, error) {
- return false, unsupported("exists")
+func (s *SandboxManager) Exists(ctx context.Context, sandboxID, path string) (bool, error) {
+ return s.m.Exists(ctx, sandboxID, path)
}
-func (s *SandboxManager) Stat(context.Context, string, string) (*types.FileInfo, error) {
- return nil, unsupported("stat")
+func (s *SandboxManager) Stat(ctx context.Context, sandboxID, path string) (*types.FileInfo, error) {
+ return s.m.Stat(ctx, sandboxID, path)
}
// ── Everything else ─────────────────────────────────────────────────────────
@@ -193,23 +245,39 @@ func (s *SandboxManager) SetResourceLimits(context.Context, string, int32, int64
return unsupported("set resource limits")
}
-// UpdateSandboxSecret reports (false, nil) — "no session matched" — rather than
-// an error, which is the contract the secret-store update flow expects for a
-// transient miss. There is no secrets proxy on this path to update.
-func (s *SandboxManager) UpdateSandboxSecret(context.Context, string, string, string) (bool, error) {
- return false, nil
+// UpdateSandboxSecret refreshes one secret in the guest's proxy session.
+//
+// (false, nil) means no session or no name matched, which is what the
+// secret-store refresh flow expects for a sandbox that does not hold the secret
+// being rotated — it sweeps every sandbox in an org, and most are misses. An
+// ERROR is reserved for a box that could not be reached, so a rotation that
+// silently failed to land is distinguishable from one that had nothing to do.
+func (s *SandboxManager) UpdateSandboxSecret(ctx context.Context, sandboxID, secretName, value string) (bool, error) {
+ return s.m.UpdateSecret(ctx, sandboxID, secretName, value)
}
-func (s *SandboxManager) Stats(context.Context, string) (*sandbox.SandboxStats, error) {
- return nil, unsupported("stats")
+func (s *SandboxManager) Stats(ctx context.Context, sandboxID string) (*sandbox.SandboxStats, error) {
+ return s.m.Stats(ctx, sandboxID)
}
+// HostPort is 0 and no error, as on the agent path: nothing publishes a host
+// port here, and 0 is the honest answer rather than a fabricated one.
func (s *SandboxManager) HostPort(context.Context, string) (int, error) {
- return 0, unsupported("host port")
+ return 0, nil
}
-func (s *SandboxManager) ContainerAddr(context.Context, string, int) (string, error) {
- return "", unsupported("container addr")
+// ContainerAddr returns the box's HTTPS host. Note that this address is NOT
+// dialable on its own — reaching a guest port needs the runtime's auth token
+// and the port carried in the path, which a bare address cannot express. The
+// preview proxy therefore uses liteBackend.PreviewTarget, and this exists so
+// callers that only want to know where the sandbox lives get an answer instead
+// of an error.
+func (s *SandboxManager) ContainerAddr(_ context.Context, sandboxID string, _ int) (string, error) {
+ host, _, _, err := s.m.PreviewTarget(sandboxID)
+ if err != nil {
+ return "", err
+ }
+ return host, nil
}
// DataDir has no meaning here — the host is managed and its disk is not ours to
@@ -218,36 +286,105 @@ func (s *SandboxManager) DataDir() string { return "" }
func (s *SandboxManager) ContainerName(id string) string { return id }
-// Hibernate/Wake: parking needs the workspace archived out of the guest, and
-// that is a file transfer over the agent. Refused rather than half-done — a
-// hibernate that reported success without an archive would destroy the box and
-// the customer's data with it.
-func (s *SandboxManager) Hibernate(context.Context, string, *storage.CheckpointStore) (*sandbox.HibernateResult, error) {
- return nil, unsupported("hibernate")
+// Hibernate parks the sandbox by suspending its box. See hibernate.go for what
+// that does and does not buy — in particular that it defers cost, not the 8h
+// service cap, and that a parked box holds quota it can never give back.
+//
+// The checkpoint store is ignored, and no key is returned: there is no archive.
+// The state lives in the suspended box itself, which is why Wake below does not
+// take one either.
+func (s *SandboxManager) Hibernate(ctx context.Context, sandboxID string, _ *storage.CheckpointStore) (*sandbox.HibernateResult, error) {
+ if err := s.m.Hibernate(ctx, sandboxID); err != nil {
+ return nil, err
+ }
+ return &sandbox.HibernateResult{SandboxID: sandboxID}, nil
}
-func (s *SandboxManager) Wake(context.Context, string, string, *storage.CheckpointStore, int) (*types.Sandbox, error) {
- return nil, unsupported("wake")
+// Wake resumes the suspended box. The sandbox comes back on the SAME box it was
+// parked on — unlike an archive restore, which lands on a new host — so there is
+// no new worker_id for the caller to persist.
+func (s *SandboxManager) Wake(ctx context.Context, sandboxID, _ string, _ *storage.CheckpointStore, _ int) (*types.Sandbox, error) {
+ if err := s.m.Wake(ctx, sandboxID); err != nil {
+ return nil, err
+ }
+ return s.Get(ctx, sandboxID)
}
-func (s *SandboxManager) RebootSandbox(context.Context, string) error {
- return unsupported("reboot")
+// RebootSandbox restarts the workload in place: every process the sandbox user
+// owns is killed and the agent is restarted. See Manager.Reboot for why this is
+// not — and cannot be — a kernel restart, and why it nonetheless preserves more
+// than the agent path's export/import reboot did.
+func (s *SandboxManager) RebootSandbox(ctx context.Context, sandboxID string) error {
+ return s.m.Reboot(ctx, sandboxID)
}
-func (s *SandboxManager) PowerCycleSandbox(context.Context, string) (int, error) {
- return 0, unsupported("power cycle")
+// PowerCycleSandbox is a reboot here, as it is on the agent path: this backend
+// already restarts everything a power cycle would, and there is no harsher step
+// to escalate to. Returns 0 for the QEMU implementation's pid — there is no host
+// process to name.
+func (s *SandboxManager) PowerCycleSandbox(ctx context.Context, sandboxID string) (int, error) {
+ return 0, s.m.Reboot(ctx, sandboxID)
}
func (s *SandboxManager) TemplateCachePath(string, string) string { return "" }
-func (s *SandboxManager) CreateCheckpoint(context.Context, string, string, *storage.CheckpointStore, func()) (string, string, int64, error) {
- return "", "", 0, unsupported("create checkpoint")
+// CreateCheckpoint archives the sandbox's workspace. See checkpoint.go for what
+// that does and does not capture — in short, files but not memory.
+//
+// Returns "" for the rootfs key, which the caller records as "there isn't one".
+// The QEMU path returns two keys because it captures two things; inventing a
+// second key here would make a restore look for an object that was never
+// written.
+// CreateDiskOnlyCheckpoint is CreateCheckpoint. On this runtime the two are the
+// same operation, because every checkpoint it can make is disk-only: there is
+// no way to read a running host's RAM out, so there is no memory half to omit.
+//
+// Both names exist because the API distinguishes them for the QEMU fleet, where
+// a full checkpoint really does capture memory and costs far more. A caller
+// asking for disk-only here should get a checkpoint, not "not supported" —
+// which is what it got while only the full-shaped name was implemented, so the
+// SDK's plain createCheckpoint(name) worked and an explicit disk_only did not.
+func (s *SandboxManager) CreateDiskOnlyCheckpoint(ctx context.Context, sandboxID, checkpointID string, store *storage.CheckpointStore, onReady func()) (string, string, int64, error) {
+ return s.CreateCheckpoint(ctx, sandboxID, checkpointID, store, onReady)
+}
+
+func (s *SandboxManager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID string, store *storage.CheckpointStore, onReady func()) (string, string, int64, error) {
+ key := WorkspaceKey(checkpointID)
+ size, err := s.m.CheckpointWorkspace(ctx, sandboxID, key, store)
+ if err != nil {
+ return "", "", 0, err
+ }
+ // Fired only after the upload is durable: onReady is what flips the row to
+ // ready, and a checkpoint advertised as ready before its object exists is
+ // one a fork will fail to find.
+ if onReady != nil {
+ onReady()
+ }
+ return "", key, size, nil
}
-func (s *SandboxManager) RestoreFromCheckpoint(context.Context, string, string) error {
- return unsupported("restore from checkpoint")
+// RestoreFromCheckpoint unpacks a checkpoint's workspace into a running
+// sandbox. The sandbox keeps its box — there is nothing to reboot, because
+// nothing but files changed.
+func (s *SandboxManager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpointID string) error {
+ if s.store == nil {
+ return fmt.Errorf("awsvmlite: restore %s: no checkpoint store configured", sandboxID)
+ }
+ return s.m.RestoreWorkspace(ctx, sandboxID, WorkspaceKey(checkpointID), s.store)
}
+// ForkFromCheckpoint is refused, deliberately, even though the pieces exist.
+//
+// A fork has to CREATE a sandbox, and creation on this backend belongs to the
+// placement path (see Create above): the backend's Claim pops a warm box, binds
+// it, and the control plane records the row. A manager that launched its own
+// box here would produce one nothing had placed, nothing had persisted, and
+// therefore nothing would ever reap — the exact leak RequiresPersistedRow
+// exists to prevent.
+//
+// The right shape is a create that carries a checkpoint id and restores after
+// the claim, which is a change to the create flow rather than to this method.
+// Until then this refuses rather than leaking boxes.
func (s *SandboxManager) ForkFromCheckpoint(context.Context, string, types.SandboxConfig) (*types.Sandbox, error) {
return nil, unsupported("fork from checkpoint")
}